Update gitignore (sorry)
Some checks failed
Android Build / publish (push) Successful in 33s
Linux Build / publish (push) Failing after 25s

This commit is contained in:
olcxja 2026-05-10 14:02:17 +02:00
commit cca8b02fea
6604 changed files with 1219661 additions and 4 deletions

22
electron/node_modules/electron-updater/LICENSE generated vendored Normal file
View file

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Loopline Systems
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.

15
electron/node_modules/electron-updater/README.md generated vendored Normal file
View file

@ -0,0 +1,15 @@
# electron-updater
This module allows you to automatically update your application. You only need to install this module and write two lines of code!
To publish your updates you just need simple file hosting, it does not require a dedicated server.
See [Auto Update](https://electron.build/auto-update) for more information.
Supported OS:
- macOS ([Squirrel.Mac](https://github.com/Squirrel/Squirrel.Mac)).
- Windows (NSIS).
- Linux (AppImage).
## Credits
Thanks to [Evolve Labs](https://www.evolvehq.com) for donating the npm package name.

View file

@ -0,0 +1,15 @@
(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.

View file

@ -0,0 +1,262 @@
Node.js: fs-extra
=================
`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
[![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![License](https://img.shields.io/npm/l/fs-extra.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
[![build status](https://img.shields.io/github/workflow/status/jprichardson/node-fs-extra/Node.js%20CI/master)](https://github.com/jprichardson/node-fs-extra/actions/workflows/ci.yml?query=branch%3Amaster)
[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
Why?
----
I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
Installation
------------
npm install fs-extra
Usage
-----
`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
You don't ever need to include the original `fs` module again:
```js
const fs = require('fs') // this is no longer necessary
```
you can now do this:
```js
const fs = require('fs-extra')
```
or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
to name your `fs` variable `fse` like so:
```js
const fse = require('fs-extra')
```
you can also keep both, but it's redundant:
```js
const fs = require('fs')
const fse = require('fs-extra')
```
Sync vs Async vs Async/Await
-------------
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
```js
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
```
Methods
-------
### Async
- [copy](docs/copy.md)
- [emptyDir](docs/emptyDir.md)
- [ensureFile](docs/ensureFile.md)
- [ensureDir](docs/ensureDir.md)
- [ensureLink](docs/ensureLink.md)
- [ensureSymlink](docs/ensureSymlink.md)
- [mkdirp](docs/ensureDir.md)
- [mkdirs](docs/ensureDir.md)
- [move](docs/move.md)
- [outputFile](docs/outputFile.md)
- [outputJson](docs/outputJson.md)
- [pathExists](docs/pathExists.md)
- [readJson](docs/readJson.md)
- [remove](docs/remove.md)
- [writeJson](docs/writeJson.md)
### Sync
- [copySync](docs/copy-sync.md)
- [emptyDirSync](docs/emptyDir-sync.md)
- [ensureFileSync](docs/ensureFile-sync.md)
- [ensureDirSync](docs/ensureDir-sync.md)
- [ensureLinkSync](docs/ensureLink-sync.md)
- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
- [mkdirpSync](docs/ensureDir-sync.md)
- [mkdirsSync](docs/ensureDir-sync.md)
- [moveSync](docs/move-sync.md)
- [outputFileSync](docs/outputFile-sync.md)
- [outputJsonSync](docs/outputJson-sync.md)
- [pathExistsSync](docs/pathExists-sync.md)
- [readJsonSync](docs/readJson-sync.md)
- [removeSync](docs/remove-sync.md)
- [writeJsonSync](docs/writeJson-sync.md)
**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md)
### What happened to `walk()` and `walkSync()`?
They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
Third Party
-----------
### CLI
[fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts.
### TypeScript
If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
### File / Directory Watching
If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
### Obtain Filesystem (Devices, Partitions) Information
[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
### Misc.
- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
Hacking on fs-extra
-------------------
Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Improve test coverage.
Note: If you make any big changes, **you should definitely file an issue for discussion first.**
### Running the Test Suite
fs-extra contains hundreds of tests.
- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
- `npm run unit`: runs the unit tests
- `npm test`: runs both the linter and the tests
### Windows
If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my `fs-extra` directory and run the tests.
Naming
------
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
* https://github.com/jprichardson/node-fs-extra/issues/2
* https://github.com/flatiron/utile/issues/11
* https://github.com/ryanmcgrath/wrench-js/issues/29
* https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
Credit
------
`fs-extra` wouldn't be possible without using the modules from the following authors:
- [Isaac Shlueter](https://github.com/isaacs)
- [Charlie McConnel](https://github.com/avianflu)
- [James Halliday](https://github.com/substack)
- [Andrew Kelley](https://github.com/andrewrk)
License
-------
Licensed under MIT
Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson)
[1]: http://nodejs.org/docs/latest/api/fs.html
[jsonfile]: https://github.com/jprichardson/node-jsonfile

View file

@ -0,0 +1,169 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirsSync = require('../mkdirs').mkdirsSync
const utimesMillisSync = require('../util/utimes').utimesMillisSync
const stat = require('../util/stat')
function copySync (src, dest, opts) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0002'
)
}
const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'copy')
return handleFilterAndCopy(destStat, src, dest, opts)
}
function handleFilterAndCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
const destParent = path.dirname(dest)
if (!fs.existsSync(destParent)) mkdirsSync(destParent)
return getStats(destStat, src, dest, opts)
}
function startCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
return getStats(destStat, src, dest, opts)
}
function getStats (destStat, src, dest, opts) {
const statSync = opts.dereference ? fs.statSync : fs.lstatSync
const srcStat = statSync(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
throw new Error(`Unknown file: ${src}`)
}
function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
return mayCopyFile(srcStat, src, dest, opts)
}
function mayCopyFile (srcStat, src, dest, opts) {
if (opts.overwrite) {
fs.unlinkSync(dest)
return copyFile(srcStat, src, dest, opts)
} else if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
function copyFile (srcStat, src, dest, opts) {
fs.copyFileSync(src, dest)
if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
return setDestMode(dest, srcStat.mode)
}
function handleTimestamps (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)) makeFileWritable(dest, srcMode)
return setDestTimestamps(src, dest)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return setDestMode(dest, srcMode | 0o200)
}
function setDestMode (dest, srcMode) {
return fs.chmodSync(dest, srcMode)
}
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 = fs.statSync(src)
return utimesMillisSync(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)
}
function mkDirAndCopy (srcMode, src, dest, opts) {
fs.mkdirSync(dest)
copyDir(src, dest, opts)
return setDestMode(dest, srcMode)
}
function copyDir (src, dest, opts) {
fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
}
function copyDirItem (item, src, dest, opts) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts)
return startCopy(destStat, srcItem, destItem, opts)
}
function onLink (destStat, src, dest, opts) {
let resolvedSrc = fs.readlinkSync(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlinkSync(resolvedSrc, dest)
} else {
let resolvedDest
try {
resolvedDest = fs.readlinkSync(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.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
throw err
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// prevent 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.
if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
return copyLink(resolvedSrc, dest)
}
}
function copyLink (resolvedSrc, dest) {
fs.unlinkSync(dest)
return fs.symlinkSync(resolvedSrc, dest)
}
module.exports = copySync

View file

@ -0,0 +1,235 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirs = require('../mkdirs').mkdirs
const pathExists = require('../path-exists').pathExists
const utimesMillis = require('../util/utimes').utimesMillis
const stat = require('../util/stat')
function copy (src, dest, opts, cb) {
if (typeof opts === 'function' && !cb) {
cb = opts
opts = {}
} else if (typeof opts === 'function') {
opts = { filter: opts }
}
cb = cb || function () {}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0001'
)
}
stat.checkPaths(src, dest, 'copy', opts, (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
stat.checkParentPaths(src, srcStat, dest, 'copy', err => {
if (err) return cb(err)
if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)
return checkParentDir(destStat, src, dest, opts, cb)
})
})
}
function checkParentDir (destStat, src, dest, opts, cb) {
const destParent = path.dirname(dest)
pathExists(destParent, (err, dirExists) => {
if (err) return cb(err)
if (dirExists) return getStats(destStat, src, dest, opts, cb)
mkdirs(destParent, err => {
if (err) return cb(err)
return getStats(destStat, src, dest, opts, cb)
})
})
}
function handleFilter (onInclude, destStat, src, dest, opts, cb) {
Promise.resolve(opts.filter(src, dest)).then(include => {
if (include) return onInclude(destStat, src, dest, opts, cb)
return cb()
}, error => cb(error))
}
function startCopy (destStat, src, dest, opts, cb) {
if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb)
return getStats(destStat, src, dest, opts, cb)
}
function getStats (destStat, src, dest, opts, cb) {
const stat = opts.dereference ? fs.stat : fs.lstat
stat(src, (err, srcStat) => {
if (err) return cb(err)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb)
else if (srcStat.isSocket()) return cb(new Error(`Cannot copy a socket file: ${src}`))
else if (srcStat.isFIFO()) return cb(new Error(`Cannot copy a FIFO pipe: ${src}`))
return cb(new Error(`Unknown file: ${src}`))
})
}
function onFile (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return copyFile(srcStat, src, dest, opts, cb)
return mayCopyFile(srcStat, src, dest, opts, cb)
}
function mayCopyFile (srcStat, src, dest, opts, cb) {
if (opts.overwrite) {
fs.unlink(dest, err => {
if (err) return cb(err)
return copyFile(srcStat, src, dest, opts, cb)
})
} else if (opts.errorOnExist) {
return cb(new Error(`'${dest}' already exists`))
} else return cb()
}
function copyFile (srcStat, src, dest, opts, cb) {
fs.copyFile(src, dest, err => {
if (err) return cb(err)
if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)
return setDestMode(dest, srcStat.mode, cb)
})
}
function handleTimestampsAndMode (srcMode, src, dest, cb) {
// 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)) {
return makeFileWritable(dest, srcMode, err => {
if (err) return cb(err)
return setDestTimestampsAndMode(srcMode, src, dest, cb)
})
}
return setDestTimestampsAndMode(srcMode, src, dest, cb)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode, cb) {
return setDestMode(dest, srcMode | 0o200, cb)
}
function setDestTimestampsAndMode (srcMode, src, dest, cb) {
setDestTimestamps(src, dest, err => {
if (err) return cb(err)
return setDestMode(dest, srcMode, cb)
})
}
function setDestMode (dest, srcMode, cb) {
return fs.chmod(dest, srcMode, cb)
}
function setDestTimestamps (src, dest, cb) {
// 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)
fs.stat(src, (err, updatedSrcStat) => {
if (err) return cb(err)
return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)
})
}
function onDir (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb)
return copyDir(src, dest, opts, cb)
}
function mkDirAndCopy (srcMode, src, dest, opts, cb) {
fs.mkdir(dest, err => {
if (err) return cb(err)
copyDir(src, dest, opts, err => {
if (err) return cb(err)
return setDestMode(dest, srcMode, cb)
})
})
}
function copyDir (src, dest, opts, cb) {
fs.readdir(src, (err, items) => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
}
function copyDirItems (items, src, dest, opts, cb) {
const item = items.pop()
if (!item) return cb()
return copyDirItem(items, item, src, dest, opts, cb)
}
function copyDirItem (items, item, src, dest, opts, cb) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
stat.checkPaths(srcItem, destItem, 'copy', opts, (err, stats) => {
if (err) return cb(err)
const { destStat } = stats
startCopy(destStat, srcItem, destItem, opts, err => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
})
}
function onLink (destStat, src, dest, opts, cb) {
fs.readlink(src, (err, resolvedSrc) => {
if (err) return cb(err)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlink(resolvedSrc, dest, cb)
} else {
fs.readlink(dest, (err, resolvedDest) => {
if (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.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb)
return cb(err)
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))
}
// 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.
if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
}
return copyLink(resolvedSrc, dest, cb)
})
}
})
}
function copyLink (resolvedSrc, dest, cb) {
fs.unlink(dest, err => {
if (err) return cb(err)
return fs.symlink(resolvedSrc, dest, cb)
})
}
module.exports = copy

View file

@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromCallback
module.exports = {
copy: u(require('./copy')),
copySync: require('./copy-sync')
}

View file

@ -0,0 +1,39 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const remove = require('../remove')
const emptyDir = u(async function emptyDir (dir) {
let items
try {
items = await fs.readdir(dir)
} catch {
return mkdir.mkdirs(dir)
}
return Promise.all(items.map(item => remove.remove(path.join(dir, item))))
})
function emptyDirSync (dir) {
let items
try {
items = fs.readdirSync(dir)
} catch {
return mkdir.mkdirsSync(dir)
}
items.forEach(item => {
item = path.join(dir, item)
remove.removeSync(item)
})
}
module.exports = {
emptyDirSync,
emptydirSync: emptyDirSync,
emptyDir,
emptydir: emptyDir
}

View file

@ -0,0 +1,69 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
function createFile (file, callback) {
function makeFile () {
fs.writeFile(file, '', err => {
if (err) return callback(err)
callback()
})
}
fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
if (!err && stats.isFile()) return callback()
const dir = path.dirname(file)
fs.stat(dir, (err, stats) => {
if (err) {
// if the directory doesn't exist, make it
if (err.code === 'ENOENT') {
return mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeFile()
})
}
return callback(err)
}
if (stats.isDirectory()) makeFile()
else {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdir(dir, err => {
if (err) return callback(err)
})
}
})
})
}
function createFileSync (file) {
let stats
try {
stats = fs.statSync(file)
} catch {}
if (stats && stats.isFile()) return
const dir = path.dirname(file)
try {
if (!fs.statSync(dir).isDirectory()) {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdirSync(dir)
}
} catch (err) {
// If the stat call above failed because the directory doesn't exist, create it
if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
else throw err
}
fs.writeFileSync(file, '')
}
module.exports = {
createFile: u(createFile),
createFileSync
}

View file

@ -0,0 +1,23 @@
'use strict'
const { createFile, createFileSync } = require('./file')
const { createLink, createLinkSync } = require('./link')
const { createSymlink, createSymlinkSync } = require('./symlink')
module.exports = {
// file
createFile,
createFileSync,
ensureFile: createFile,
ensureFileSync: createFileSync,
// link
createLink,
createLinkSync,
ensureLink: createLink,
ensureLinkSync: createLinkSync,
// symlink
createSymlink,
createSymlinkSync,
ensureSymlink: createSymlink,
ensureSymlinkSync: createSymlinkSync
}

View file

@ -0,0 +1,64 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
const { areIdentical } = require('../util/stat')
function createLink (srcpath, dstpath, callback) {
function makeLink (srcpath, dstpath) {
fs.link(srcpath, dstpath, err => {
if (err) return callback(err)
callback(null)
})
}
fs.lstat(dstpath, (_, dstStat) => {
fs.lstat(srcpath, (err, srcStat) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureLink')
return callback(err)
}
if (dstStat && areIdentical(srcStat, dstStat)) return callback(null)
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return makeLink(srcpath, dstpath)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeLink(srcpath, dstpath)
})
})
})
})
}
function createLinkSync (srcpath, dstpath) {
let dstStat
try {
dstStat = fs.lstatSync(dstpath)
} catch {}
try {
const srcStat = fs.lstatSync(srcpath)
if (dstStat && areIdentical(srcStat, dstStat)) return
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
const dir = path.dirname(dstpath)
const dirExists = fs.existsSync(dir)
if (dirExists) return fs.linkSync(srcpath, dstpath)
mkdir.mkdirsSync(dir)
return fs.linkSync(srcpath, dstpath)
}
module.exports = {
createLink: u(createLink),
createLinkSync
}

View file

@ -0,0 +1,99 @@
'use strict'
const path = require('path')
const fs = require('graceful-fs')
const pathExists = require('../path-exists').pathExists
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
function symlinkPaths (srcpath, dstpath, callback) {
if (path.isAbsolute(srcpath)) {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
toCwd: srcpath,
toDst: srcpath
})
})
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
return pathExists(relativeToDst, (err, exists) => {
if (err) return callback(err)
if (exists) {
return callback(null, {
toCwd: relativeToDst,
toDst: srcpath
})
} else {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
})
})
}
})
}
}
function symlinkPathsSync (srcpath, dstpath) {
let exists
if (path.isAbsolute(srcpath)) {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
toCwd: srcpath,
toDst: srcpath
}
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
exists = fs.existsSync(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
} else {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('relative srcpath does not exist')
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
}
}
module.exports = {
symlinkPaths,
symlinkPathsSync
}

View file

@ -0,0 +1,31 @@
'use strict'
const fs = require('graceful-fs')
function symlinkType (srcpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
if (type) return callback(null, type)
fs.lstat(srcpath, (err, stats) => {
if (err) return callback(null, 'file')
type = (stats && stats.isDirectory()) ? 'dir' : 'file'
callback(null, type)
})
}
function symlinkTypeSync (srcpath, type) {
let stats
if (type) return type
try {
stats = fs.lstatSync(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
symlinkType,
symlinkTypeSync
}

View file

@ -0,0 +1,82 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('../fs')
const _mkdirs = require('../mkdirs')
const mkdirs = _mkdirs.mkdirs
const mkdirsSync = _mkdirs.mkdirsSync
const _symlinkPaths = require('./symlink-paths')
const symlinkPaths = _symlinkPaths.symlinkPaths
const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
const _symlinkType = require('./symlink-type')
const symlinkType = _symlinkType.symlinkType
const symlinkTypeSync = _symlinkType.symlinkTypeSync
const pathExists = require('../path-exists').pathExists
const { areIdentical } = require('../util/stat')
function createSymlink (srcpath, dstpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
fs.lstat(dstpath, (err, stats) => {
if (!err && stats.isSymbolicLink()) {
Promise.all([
fs.stat(srcpath),
fs.stat(dstpath)
]).then(([srcStat, dstStat]) => {
if (areIdentical(srcStat, dstStat)) return callback(null)
_createSymlink(srcpath, dstpath, type, callback)
})
} else _createSymlink(srcpath, dstpath, type, callback)
})
}
function _createSymlink (srcpath, dstpath, type, callback) {
symlinkPaths(srcpath, dstpath, (err, relative) => {
if (err) return callback(err)
srcpath = relative.toDst
symlinkType(relative.toCwd, type, (err, type) => {
if (err) return callback(err)
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
mkdirs(dir, err => {
if (err) return callback(err)
fs.symlink(srcpath, dstpath, type, callback)
})
})
})
})
}
function createSymlinkSync (srcpath, dstpath, type) {
let stats
try {
stats = fs.lstatSync(dstpath)
} catch {}
if (stats && stats.isSymbolicLink()) {
const srcStat = fs.statSync(srcpath)
const dstStat = fs.statSync(dstpath)
if (areIdentical(srcStat, dstStat)) return
}
const relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
const dir = path.dirname(dstpath)
const exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: u(createSymlink),
createSymlinkSync
}

View file

@ -0,0 +1,128 @@
'use strict'
// This is adapted from https://github.com/normalize/mz
// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const api = [
'access',
'appendFile',
'chmod',
'chown',
'close',
'copyFile',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'lchmod',
'lchown',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'opendir',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rm',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
].filter(key => {
// Some commands are not available on some systems. Ex:
// fs.opendir was added in Node.js v12.12.0
// fs.rm was added in Node.js v14.14.0
// fs.lchown is not available on at least some Linux
return typeof fs[key] === 'function'
})
// Export cloned fs:
Object.assign(exports, fs)
// Universalify async methods:
api.forEach(method => {
exports[method] = u(fs[method])
})
// We differ from mz/fs in that we still ship the old, broken, fs.exists()
// since we are a drop-in replacement for the native module
exports.exists = function (filename, callback) {
if (typeof callback === 'function') {
return fs.exists(filename, callback)
}
return new Promise(resolve => {
return fs.exists(filename, resolve)
})
}
// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args
exports.read = function (fd, buffer, offset, length, position, callback) {
if (typeof callback === 'function') {
return fs.read(fd, buffer, offset, length, position, callback)
}
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) return reject(err)
resolve({ bytesRead, buffer })
})
})
}
// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.write(fd, buffer, ...args)
}
return new Promise((resolve, reject) => {
fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
if (err) return reject(err)
resolve({ bytesWritten, buffer })
})
})
}
// fs.writev only available in Node v12.9.0+
if (typeof fs.writev === 'function') {
// Function signature is
// s.writev(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.writev = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.writev(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
if (err) return reject(err)
resolve({ bytesWritten, buffers })
})
})
}
}
// fs.realpath.native sometimes not available if fs is monkey-patched
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
} else {
process.emitWarning(
'fs.realpath.native is not a function. Is fs being monkey-patched?',
'Warning', 'fs-extra-WARN0003'
)
}

View file

@ -0,0 +1,16 @@
'use strict'
module.exports = {
// Export promiseified graceful-fs:
...require('./fs'),
// Export extra methods:
...require('./copy'),
...require('./empty'),
...require('./ensure'),
...require('./json'),
...require('./mkdirs'),
...require('./move'),
...require('./output-file'),
...require('./path-exists'),
...require('./remove')
}

View file

@ -0,0 +1,16 @@
'use strict'
const u = require('universalify').fromPromise
const jsonFile = require('./jsonfile')
jsonFile.outputJson = u(require('./output-json'))
jsonFile.outputJsonSync = require('./output-json-sync')
// aliases
jsonFile.outputJSON = jsonFile.outputJson
jsonFile.outputJSONSync = jsonFile.outputJsonSync
jsonFile.writeJSON = jsonFile.writeJson
jsonFile.writeJSONSync = jsonFile.writeJsonSync
jsonFile.readJSON = jsonFile.readJson
jsonFile.readJSONSync = jsonFile.readJsonSync
module.exports = jsonFile

View file

@ -0,0 +1,11 @@
'use strict'
const jsonFile = require('jsonfile')
module.exports = {
// jsonfile exports
readJson: jsonFile.readFile,
readJsonSync: jsonFile.readFileSync,
writeJson: jsonFile.writeFile,
writeJsonSync: jsonFile.writeFileSync
}

View file

@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFileSync } = require('../output-file')
function outputJsonSync (file, data, options) {
const str = stringify(data, options)
outputFileSync(file, str, options)
}
module.exports = outputJsonSync

View file

@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFile } = require('../output-file')
async function outputJson (file, data, options = {}) {
const str = stringify(data, options)
await outputFile(file, str, options)
}
module.exports = outputJson

View file

@ -0,0 +1,14 @@
'use strict'
const u = require('universalify').fromPromise
const { makeDir: _makeDir, makeDirSync } = require('./make-dir')
const makeDir = u(_makeDir)
module.exports = {
mkdirs: makeDir,
mkdirsSync: makeDirSync,
// alias
mkdirp: makeDir,
mkdirpSync: makeDirSync,
ensureDir: makeDir,
ensureDirSync: makeDirSync
}

View file

@ -0,0 +1,27 @@
'use strict'
const fs = require('../fs')
const { checkPath } = require('./utils')
const getMode = options => {
const defaults = { mode: 0o777 }
if (typeof options === 'number') return options
return ({ ...defaults, ...options }).mode
}
module.exports.makeDir = async (dir, options) => {
checkPath(dir)
return fs.mkdir(dir, {
mode: getMode(options),
recursive: true
})
}
module.exports.makeDirSync = (dir, options) => {
checkPath(dir)
return fs.mkdirSync(dir, {
mode: getMode(options),
recursive: true
})
}

View file

@ -0,0 +1,21 @@
// Adapted from https://github.com/sindresorhus/make-dir
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
'use strict'
const path = require('path')
// https://github.com/nodejs/node/issues/8987
// https://github.com/libuv/libuv/pull/1088
module.exports.checkPath = function checkPath (pth) {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
if (pathHasInvalidWinCharacters) {
const error = new Error(`Path contains invalid characters: ${pth}`)
error.code = 'EINVAL'
throw error
}
}
}

View file

@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromCallback
module.exports = {
move: u(require('./move')),
moveSync: require('./move-sync')
}

View file

@ -0,0 +1,54 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copySync = require('../copy').copySync
const removeSync = require('../remove').removeSync
const mkdirpSync = require('../mkdirs').mkdirpSync
const stat = require('../util/stat')
function moveSync (src, dest, opts) {
opts = opts || {}
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'move')
if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest))
return doRename(src, dest, overwrite, isChangingCase)
}
function isParentRoot (dest) {
const parent = path.dirname(dest)
const parsedPath = path.parse(parent)
return parsedPath.root === parent
}
function doRename (src, dest, overwrite, isChangingCase) {
if (isChangingCase) return rename(src, dest, overwrite)
if (overwrite) {
removeSync(dest)
return rename(src, dest, overwrite)
}
if (fs.existsSync(dest)) throw new Error('dest already exists.')
return rename(src, dest, overwrite)
}
function rename (src, dest, overwrite) {
try {
fs.renameSync(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') throw err
return moveAcrossDevice(src, dest, overwrite)
}
}
function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true
}
copySync(src, dest, opts)
return removeSync(src)
}
module.exports = moveSync

View file

@ -0,0 +1,75 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copy = require('../copy').copy
const remove = require('../remove').remove
const mkdirp = require('../mkdirs').mkdirp
const pathExists = require('../path-exists').pathExists
const stat = require('../util/stat')
function move (src, dest, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = opts || {}
const overwrite = opts.overwrite || opts.clobber || false
stat.checkPaths(src, dest, 'move', opts, (err, stats) => {
if (err) return cb(err)
const { srcStat, isChangingCase = false } = stats
stat.checkParentPaths(src, srcStat, dest, 'move', err => {
if (err) return cb(err)
if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb)
mkdirp(path.dirname(dest), err => {
if (err) return cb(err)
return doRename(src, dest, overwrite, isChangingCase, cb)
})
})
})
}
function isParentRoot (dest) {
const parent = path.dirname(dest)
const parsedPath = path.parse(parent)
return parsedPath.root === parent
}
function doRename (src, dest, overwrite, isChangingCase, cb) {
if (isChangingCase) return rename(src, dest, overwrite, cb)
if (overwrite) {
return remove(dest, err => {
if (err) return cb(err)
return rename(src, dest, overwrite, cb)
})
}
pathExists(dest, (err, destExists) => {
if (err) return cb(err)
if (destExists) return cb(new Error('dest already exists.'))
return rename(src, dest, overwrite, cb)
})
}
function rename (src, dest, overwrite, cb) {
fs.rename(src, dest, err => {
if (!err) return cb()
if (err.code !== 'EXDEV') return cb(err)
return moveAcrossDevice(src, dest, overwrite, cb)
})
}
function moveAcrossDevice (src, dest, overwrite, cb) {
const opts = {
overwrite,
errorOnExist: true
}
copy(src, dest, opts, err => {
if (err) return cb(err)
return remove(src, cb)
})
}
module.exports = move

View file

@ -0,0 +1,40 @@
'use strict'
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
function outputFile (file, data, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding
encoding = 'utf8'
}
const dir = path.dirname(file)
pathExists(dir, (err, itDoes) => {
if (err) return callback(err)
if (itDoes) return fs.writeFile(file, data, encoding, callback)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
fs.writeFile(file, data, encoding, callback)
})
})
}
function outputFileSync (file, ...args) {
const dir = path.dirname(file)
if (fs.existsSync(dir)) {
return fs.writeFileSync(file, ...args)
}
mkdir.mkdirsSync(dir)
fs.writeFileSync(file, ...args)
}
module.exports = {
outputFile: u(outputFile),
outputFileSync
}

View file

@ -0,0 +1,12 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
function pathExists (path) {
return fs.access(path).then(() => true).catch(() => false)
}
module.exports = {
pathExists: u(pathExists),
pathExistsSync: fs.existsSync
}

View file

@ -0,0 +1,22 @@
'use strict'
const fs = require('graceful-fs')
const u = require('universalify').fromCallback
const rimraf = require('./rimraf')
function remove (path, callback) {
// Node 14.14.0+
if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback)
rimraf(path, callback)
}
function removeSync (path) {
// Node 14.14.0+
if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true })
rimraf.sync(path)
}
module.exports = {
remove: u(remove),
removeSync
}

View file

@ -0,0 +1,302 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const assert = require('assert')
const isWindows = (process.platform === 'win32')
function defaults (options) {
const methods = [
'unlink',
'chmod',
'stat',
'lstat',
'rmdir',
'readdir'
]
methods.forEach(m => {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
options.maxBusyTries = options.maxBusyTries || 3
}
function rimraf (p, options, cb) {
let busyTries = 0
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p, 'rimraf: missing path')
assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required')
assert(options, 'rimraf: invalid options argument provided')
assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
defaults(options)
rimraf_(p, options, function CB (er) {
if (er) {
if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
busyTries < options.maxBusyTries) {
busyTries++
const time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(() => rimraf_(p, options, CB), time)
}
// already gone
if (er.code === 'ENOENT') er = null
}
cb(er)
})
}
// Two possible strategies.
// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong. However, there
// are likely far more normal files in the world than directories. This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow. But until then, YAGNI.
function rimraf_ (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
// sunos lets the root user unlink directories, which is... weird.
// so we have to lstat here and make sure it's not a dir.
options.lstat(p, (er, st) => {
if (er && er.code === 'ENOENT') {
return cb(null)
}
// Windows can EPERM on stat. Life is suffering.
if (er && er.code === 'EPERM' && isWindows) {
return fixWinEPERM(p, options, er, cb)
}
if (st && st.isDirectory()) {
return rmdir(p, options, er, cb)
}
options.unlink(p, er => {
if (er) {
if (er.code === 'ENOENT') {
return cb(null)
}
if (er.code === 'EPERM') {
return (isWindows)
? fixWinEPERM(p, options, er, cb)
: rmdir(p, options, er, cb)
}
if (er.code === 'EISDIR') {
return rmdir(p, options, er, cb)
}
}
return cb(er)
})
})
}
function fixWinEPERM (p, options, er, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.chmod(p, 0o666, er2 => {
if (er2) {
cb(er2.code === 'ENOENT' ? null : er)
} else {
options.stat(p, (er3, stats) => {
if (er3) {
cb(er3.code === 'ENOENT' ? null : er)
} else if (stats.isDirectory()) {
rmdir(p, options, er, cb)
} else {
options.unlink(p, cb)
}
})
}
})
}
function fixWinEPERMSync (p, options, er) {
let stats
assert(p)
assert(options)
try {
options.chmodSync(p, 0o666)
} catch (er2) {
if (er2.code === 'ENOENT') {
return
} else {
throw er
}
}
try {
stats = options.statSync(p)
} catch (er3) {
if (er3.code === 'ENOENT') {
return
} else {
throw er
}
}
if (stats.isDirectory()) {
rmdirSync(p, options, er)
} else {
options.unlinkSync(p)
}
}
function rmdir (p, options, originalEr, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
// try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
// if we guessed wrong, and it's not a directory, then
// raise the original error.
options.rmdir(p, er => {
if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
rmkids(p, options, cb)
} else if (er && er.code === 'ENOTDIR') {
cb(originalEr)
} else {
cb(er)
}
})
}
function rmkids (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.readdir(p, (er, files) => {
if (er) return cb(er)
let n = files.length
let errState
if (n === 0) return options.rmdir(p, cb)
files.forEach(f => {
rimraf(path.join(p, f), options, er => {
if (errState) {
return
}
if (er) return cb(errState = er)
if (--n === 0) {
options.rmdir(p, cb)
}
})
})
})
}
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
let st
options = options || {}
defaults(options)
assert(p, 'rimraf: missing path')
assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
assert(options, 'rimraf: missing options')
assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
try {
st = options.lstatSync(p)
} catch (er) {
if (er.code === 'ENOENT') {
return
}
// Windows can EPERM on stat. Life is suffering.
if (er.code === 'EPERM' && isWindows) {
fixWinEPERMSync(p, options, er)
}
}
try {
// sunos lets the root user unlink directories, which is... weird.
if (st && st.isDirectory()) {
rmdirSync(p, options, null)
} else {
options.unlinkSync(p)
}
} catch (er) {
if (er.code === 'ENOENT') {
return
} else if (er.code === 'EPERM') {
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
} else if (er.code !== 'EISDIR') {
throw er
}
rmdirSync(p, options, er)
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === 'ENOTDIR') {
throw originalEr
} else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
rmkidsSync(p, options)
} else if (er.code !== 'ENOENT') {
throw er
}
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
if (isWindows) {
// We only end up here once we got ENOTEMPTY at least once, and
// at this point, we are guaranteed to have removed all the kids.
// So, we know that it won't be ENOENT or ENOTDIR or anything else.
// try really hard to delete stuff on windows, because it has a
// PROFOUNDLY annoying habit of not closing handles promptly when
// files are deleted, resulting in spurious ENOTEMPTY errors.
const startTime = Date.now()
do {
try {
const ret = options.rmdirSync(p, options)
return ret
} catch {}
} while (Date.now() - startTime < 500) // give up after 500ms
} else {
const ret = options.rmdirSync(p, options)
return ret
}
}
module.exports = rimraf
rimraf.sync = rimrafSync

View file

@ -0,0 +1,154 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const util = require('util')
function getStats (src, dest, opts) {
const statFunc = opts.dereference
? (file) => fs.stat(file, { bigint: true })
: (file) => fs.lstat(file, { bigint: true })
return Promise.all([
statFunc(src),
statFunc(dest).catch(err => {
if (err.code === 'ENOENT') return null
throw err
})
]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}
function getStatsSync (src, dest, opts) {
let destStat
const statFunc = opts.dereference
? (file) => fs.statSync(file, { bigint: true })
: (file) => fs.lstatSync(file, { bigint: true })
const srcStat = statFunc(src)
try {
destStat = statFunc(dest)
} catch (err) {
if (err.code === 'ENOENT') return { srcStat, destStat: null }
throw err
}
return { srcStat, destStat }
}
function checkPaths (src, dest, funcName, opts, cb) {
util.callbackify(getStats)(src, dest, opts, (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return cb(null, { srcStat, destStat, isChangingCase: true })
}
return cb(new Error('Source and destination must not be the same.'))
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`))
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return cb(null, { srcStat, destStat })
})
}
function checkPathsSync (src, dest, funcName, opts) {
const { srcStat, destStat } = getStatsSync(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
// 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.
function checkParentPaths (src, srcStat, dest, funcName, cb) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
fs.stat(destParent, { bigint: true }, (err, destStat) => {
if (err) {
if (err.code === 'ENOENT') return cb()
return cb(err)
}
if (areIdentical(srcStat, destStat)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return checkParentPaths(src, srcStat, destParent, funcName, cb)
})
}
function checkParentPathsSync (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = fs.statSync(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPathsSync(src, srcStat, destParent, funcName)
}
function areIdentical (srcStat, destStat) {
return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
}
// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
const srcArr = path.resolve(src).split(path.sep).filter(i => i)
const destArr = path.resolve(dest).split(path.sep).filter(i => i)
return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
}
function errMsg (src, dest, funcName) {
return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}
module.exports = {
checkPaths,
checkPathsSync,
checkParentPaths,
checkParentPathsSync,
isSrcSubdir,
areIdentical
}

View file

@ -0,0 +1,26 @@
'use strict'
const fs = require('graceful-fs')
function utimesMillis (path, atime, mtime, callback) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
fs.open(path, 'r+', (err, fd) => {
if (err) return callback(err)
fs.futimes(fd, atime, mtime, futimesErr => {
fs.close(fd, closeErr => {
if (callback) callback(futimesErr || closeErr)
})
})
})
}
function utimesMillisSync (path, atime, mtime) {
const fd = fs.openSync(path, 'r+')
fs.futimesSync(fd, atime, mtime)
return fs.closeSync(fd)
}
module.exports = {
utimesMillis,
utimesMillisSync
}

View file

@ -0,0 +1,67 @@
{
"name": "fs-extra",
"version": "10.1.0",
"description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.",
"engines": {
"node": ">=12"
},
"homepage": "https://github.com/jprichardson/node-fs-extra",
"repository": {
"type": "git",
"url": "https://github.com/jprichardson/node-fs-extra"
},
"keywords": [
"fs",
"file",
"file system",
"copy",
"directory",
"extra",
"mkdirp",
"mkdir",
"mkdirs",
"recursive",
"json",
"read",
"write",
"extra",
"delete",
"remove",
"touch",
"create",
"text",
"output",
"move",
"promise"
],
"author": "JP Richardson <jprichardson@gmail.com>",
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"devDependencies": {
"at-least-node": "^1.0.0",
"klaw": "^2.1.1",
"klaw-sync": "^3.0.2",
"minimist": "^1.1.1",
"mocha": "^5.0.5",
"nyc": "^15.0.0",
"proxyquire": "^2.0.1",
"read-dir-files": "^0.1.1",
"standard": "^16.0.3"
},
"main": "./lib/index.js",
"files": [
"lib/",
"!lib/**/__tests__/"
],
"scripts": {
"lint": "standard",
"test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha",
"test": "npm run lint && npm run unit",
"unit": "nyc node test.js"
},
"sideEffects": false
}

View file

@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2012-2015, JP Richardson <jprichardson@gmail.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.

View file

@ -0,0 +1,230 @@
Node.js - jsonfile
================
Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._
[![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile)
[![linux build status](https://img.shields.io/github/actions/workflow/status/jprichardson/node-jsonfile/ci.yml?branch=master)](https://github.com/jprichardson/node-jsonfile/actions?query=branch%3Amaster)
[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master)
<a href="https://github.com/feross/standard"><img src="https://cdn.rawgit.com/feross/standard/master/sticker.svg" alt="Standard JavaScript" width="100"></a>
Why?
----
Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying.
Installation
------------
npm install --save jsonfile
API
---
* [`readFile(filename, [options], callback)`](#readfilefilename-options-callback)
* [`readFileSync(filename, [options])`](#readfilesyncfilename-options)
* [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback)
* [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options)
----
### readFile(filename, [options], callback)
`options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback.
If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
console.dir(obj)
})
```
You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file)
.then(obj => console.dir(obj))
.catch(error => console.error(error))
```
----
### readFileSync(filename, [options])
`options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
console.dir(jsonfile.readFileSync(file))
```
----
### writeFile(filename, obj, [options], callback)
`options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, function (err) {
if (err) console.error(err)
})
```
Or use with promises as follows:
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj)
.then(res => {
console.log('Write complete')
})
.catch(error => console.error(error))
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) {
if (err) console.error(err)
})
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) {
if (err) console.error(err)
})
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) {
if (err) console.log(err)
})
```
**appending to an existing JSON file:**
You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) {
if (err) console.error(err)
})
```
----
### writeFileSync(filename, obj, [options])
`options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj)
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2 })
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' })
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false })
```
**appending to an existing JSON file:**
You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { flag: 'a' })
```
License
-------
(MIT License)
Copyright 2012-2016, JP Richardson <jprichardson@gmail.com>

View file

@ -0,0 +1,88 @@
let _fs
try {
_fs = require('graceful-fs')
} catch (_) {
_fs = require('fs')
}
const universalify = require('universalify')
const { stringify, stripBom } = require('./utils')
async function _readFile (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
let data = await universalify.fromCallback(fs.readFile)(file, options)
data = stripBom(data)
let obj
try {
obj = JSON.parse(data, options ? options.reviver : null)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
return obj
}
const readFile = universalify.fromPromise(_readFile)
function readFileSync (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
try {
let content = fs.readFileSync(file, options)
content = stripBom(content)
return JSON.parse(content, options.reviver)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
}
async function _writeFile (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
await universalify.fromCallback(fs.writeFile)(file, str, options)
}
const writeFile = universalify.fromPromise(_writeFile)
function writeFileSync (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
// not sure if fs.writeFileSync returns anything, but just in case
return fs.writeFileSync(file, str, options)
}
// NOTE: do not change this export format; required for ESM compat
// see https://github.com/jprichardson/node-jsonfile/pull/162 for details
module.exports = {
readFile,
readFileSync,
writeFile,
writeFileSync
}

View file

@ -0,0 +1,40 @@
{
"name": "jsonfile",
"version": "6.2.1",
"description": "Easily read/write JSON files.",
"repository": {
"type": "git",
"url": "git@github.com:jprichardson/node-jsonfile.git"
},
"keywords": [
"read",
"write",
"file",
"json",
"fs",
"fs-extra"
],
"author": "JP Richardson <jprichardson@gmail.com>",
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
},
"devDependencies": {
"mocha": "^8.2.0",
"rimraf": "^2.4.0",
"standard": "^16.0.1"
},
"main": "index.js",
"files": [
"index.js",
"utils.js"
],
"scripts": {
"lint": "standard",
"test": "npm run lint && npm run unit",
"unit": "mocha"
}
}

View file

@ -0,0 +1,18 @@
function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
const EOF = finalEOL ? EOL : ''
const str = JSON.stringify(obj, replacer, spaces)
if (str === undefined) {
throw new TypeError(`Converting ${typeof obj} value to JSON is not supported`)
}
return str.replace(/\n/g, EOL) + EOF
}
function stripBom (content) {
// we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
if (Buffer.isBuffer(content)) content = content.toString('utf8')
return content.replace(/^\uFEFF/, '')
}
module.exports = { stringify, stripBom }

View file

@ -0,0 +1,21 @@
export interface AppAdapter {
readonly version: string;
readonly name: string;
readonly isPackaged: boolean;
/**
* Path to update metadata file.
*/
readonly appUpdateConfigPath: string;
/**
* Path to user data directory.
*/
readonly userDataPath: string;
/**
* Path to cache directory.
*/
readonly baseCachePath: string;
whenReady(): Promise<void>;
quit(): void;
onQuit(handler: (exitCode: number) => void): void;
}
export declare function getAppCacheDir(): string;

View file

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppCacheDir = void 0;
const path = require("path");
const os_1 = require("os");
function getAppCacheDir() {
const homedir = os_1.homedir();
// https://github.com/electron/electron/issues/1404#issuecomment-194391247
let result;
if (process.platform === "win32") {
result = process.env["LOCALAPPDATA"] || path.join(homedir, "AppData", "Local");
}
else if (process.platform === "darwin") {
result = path.join(homedir, "Library", "Application Support", "Caches");
}
else {
result = process.env["XDG_CACHE_HOME"] || path.join(homedir, ".cache");
}
return result;
}
exports.getAppCacheDir = getAppCacheDir;
//# sourceMappingURL=AppAdapter.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"AppAdapter.js","sourceRoot":"","sources":["../src/AppAdapter.ts"],"names":[],"mappings":";;;AAAA,6BAA4B;AAC5B,2BAA0C;AA8B1C,SAAgB,cAAc;IAC5B,MAAM,OAAO,GAAG,YAAU,EAAE,CAAA;IAC5B,0EAA0E;IAC1E,IAAI,MAAc,CAAA;IAClB,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;QAChC,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAA;KAC/E;SAAM,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACxC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,qBAAqB,EAAE,QAAQ,CAAC,CAAA;KACxE;SAAM;QACL,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;KACvE;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAZD,wCAYC","sourcesContent":["import * as path from \"path\"\nimport { homedir as getHomedir } from \"os\"\n\nexport interface AppAdapter {\n readonly version: string\n readonly name: string\n\n readonly isPackaged: boolean\n\n /**\n * Path to update metadata file.\n */\n readonly appUpdateConfigPath: string\n\n /**\n * Path to user data directory.\n */\n readonly userDataPath: string\n\n /**\n * Path to cache directory.\n */\n readonly baseCachePath: string\n\n whenReady(): Promise<void>\n\n quit(): void\n\n onQuit(handler: (exitCode: number) => void): void\n}\n\nexport function getAppCacheDir() {\n const homedir = getHomedir()\n // https://github.com/electron/electron/issues/1404#issuecomment-194391247\n let result: string\n if (process.platform === \"win32\") {\n result = process.env[\"LOCALAPPDATA\"] || path.join(homedir, \"AppData\", \"Local\")\n } else if (process.platform === \"darwin\") {\n result = path.join(homedir, \"Library\", \"Application Support\", \"Caches\")\n } else {\n result = process.env[\"XDG_CACHE_HOME\"] || path.join(homedir, \".cache\")\n }\n return result\n}\n"]}

View file

@ -0,0 +1,10 @@
import { AllPublishOptions } from "builder-util-runtime";
import { DownloadUpdateOptions } from "./AppUpdater";
import { BaseUpdater, InstallOptions } from "./BaseUpdater";
export declare class AppImageUpdater extends BaseUpdater {
constructor(options?: AllPublishOptions | null, app?: any);
isUpdaterActive(): boolean;
/*** @private */
protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>;
protected doInstall(options: InstallOptions): boolean;
}

View file

@ -0,0 +1,111 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppImageUpdater = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const child_process_1 = require("child_process");
const fs_extra_1 = require("fs-extra");
const fs_1 = require("fs");
const path = require("path");
const BaseUpdater_1 = require("./BaseUpdater");
const FileWithEmbeddedBlockMapDifferentialDownloader_1 = require("./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader");
const main_1 = require("./main");
const Provider_1 = require("./providers/Provider");
class AppImageUpdater extends BaseUpdater_1.BaseUpdater {
constructor(options, app) {
super(options, app);
}
isUpdaterActive() {
if (process.env["APPIMAGE"] == null) {
if (process.env["SNAP"] == null) {
this._logger.warn("APPIMAGE env is not defined, current application is not an AppImage");
}
else {
this._logger.info("SNAP env is defined, updater is disabled");
}
return false;
}
return super.isUpdaterActive();
}
/*** @private */
doDownloadUpdate(downloadUpdateOptions) {
const provider = downloadUpdateOptions.updateInfoAndProvider.provider;
const fileInfo = Provider_1.findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "AppImage");
return this.executeDownload({
fileExtension: "AppImage",
fileInfo,
downloadUpdateOptions,
task: async (updateFile, downloadOptions) => {
const oldFile = process.env["APPIMAGE"];
if (oldFile == null) {
throw builder_util_runtime_1.newError("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND");
}
let isDownloadFull = false;
try {
const downloadOptions = {
newUrl: fileInfo.url,
oldFile,
logger: this._logger,
newFile: updateFile,
isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,
requestHeaders: downloadUpdateOptions.requestHeaders,
cancellationToken: downloadUpdateOptions.cancellationToken,
};
if (this.listenerCount(main_1.DOWNLOAD_PROGRESS) > 0) {
downloadOptions.onProgress = it => this.emit(main_1.DOWNLOAD_PROGRESS, it);
}
await new FileWithEmbeddedBlockMapDifferentialDownloader_1.FileWithEmbeddedBlockMapDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download();
}
catch (e) {
this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`);
// during test (developer machine mac) we must throw error
isDownloadFull = process.platform === "linux";
}
if (isDownloadFull) {
await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions);
}
await fs_extra_1.chmod(updateFile, 0o755);
},
});
}
doInstall(options) {
const appImageFile = process.env["APPIMAGE"];
if (appImageFile == null) {
throw builder_util_runtime_1.newError("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND");
}
// https://stackoverflow.com/a/1712051/1910191
fs_1.unlinkSync(appImageFile);
let destination;
const existingBaseName = path.basename(appImageFile);
// https://github.com/electron-userland/electron-builder/issues/2964
// if no version in existing file name, it means that user wants to preserve current custom name
if (path.basename(options.installerPath) === existingBaseName || !/\d+\.\d+\.\d+/.test(existingBaseName)) {
// no version in the file name, overwrite existing
destination = appImageFile;
}
else {
destination = path.join(path.dirname(appImageFile), path.basename(options.installerPath));
}
child_process_1.execFileSync("mv", ["-f", options.installerPath, destination]);
if (destination !== appImageFile) {
this.emit("appimage-filename-updated", destination);
}
const env = {
...process.env,
APPIMAGE_SILENT_INSTALL: "true",
};
if (options.isForceRunAfter) {
child_process_1.spawn(destination, [], {
detached: true,
stdio: "ignore",
env,
}).unref();
}
else {
env.APPIMAGE_EXIT_AFTER_INSTALL = "true";
child_process_1.execFileSync(destination, [], { env });
}
return true;
}
}
exports.AppImageUpdater = AppImageUpdater;
//# sourceMappingURL=AppImageUpdater.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,202 @@
/// <reference types="node" />
import { AllPublishOptions, CancellationToken, PublishConfiguration, UpdateInfo, DownloadOptions, ProgressInfo } from "builder-util-runtime";
import { OutgoingHttpHeaders } from "http";
import { Lazy } from "lazy-val";
import { SemVer } from "semver";
import { AppAdapter } from "./AppAdapter";
import { DownloadedUpdateHelper } from "./DownloadedUpdateHelper";
import { LoginCallback } from "./electronHttpExecutor";
import { Logger, Provider, ResolvedUpdateFileInfo, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from "./main";
import { ProviderPlatform } from "./providers/Provider";
import type TypedEmitter from "typed-emitter";
import Session = Electron.Session;
import { AuthInfo } from "electron";
export declare type AppUpdaterEvents = {
error: (error: Error, message?: string) => void;
login: (info: AuthInfo, callback: LoginCallback) => void;
"checking-for-update": () => void;
"update-not-available": (info: UpdateInfo) => void;
"update-available": (info: UpdateInfo) => void;
"update-downloaded": (event: UpdateDownloadedEvent) => void;
"download-progress": (info: ProgressInfo) => void;
"update-cancelled": (info: UpdateInfo) => void;
"appimage-filename-updated": (path: string) => void;
};
declare const AppUpdater_base: new () => TypedEmitter<AppUpdaterEvents>;
export declare abstract class AppUpdater extends AppUpdater_base {
/**
* Whether to automatically download an update when it is found.
*/
autoDownload: boolean;
/**
* Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).
*/
autoInstallOnAppQuit: boolean;
/**
* *windows-only* Whether to run the app after finish install when run the installer NOT in silent mode.
* @default true
*/
autoRunAppAfterInstall: boolean;
/**
* *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.
*
* If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).
*/
allowPrerelease: boolean;
/**
* *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.
* @default false
*/
fullChangelog: boolean;
/**
* Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).
*
* Taken in account only if channel differs (pre-release version component in terms of semantic versioning).
*
* @default false
*/
allowDowngrade: boolean;
/**
* Web installer files might not have signature verification, this switch prevents to load them unless it is needed.
*
* Currently false to prevent breaking the current API, but it should be changed to default true at some point that
* breaking changes are allowed.
*
* @default false
*/
disableWebInstaller: boolean;
/**
* Allows developer to force the updater to work in "dev" mode, looking for "dev-app-update.yml" instead of "app-update.yml"
* Dev: `path.join(this.app.getAppPath(), "dev-app-update.yml")`
* Prod: `path.join(process.resourcesPath!, "app-update.yml")`
*
* @default false
*/
forceDevUpdateConfig: boolean;
/**
* The current application version.
*/
readonly currentVersion: SemVer;
private _channel;
protected downloadedUpdateHelper: DownloadedUpdateHelper | null;
/**
* Get the update channel. Not applicable for GitHub. Doesn't return `channel` from the update configuration, only if was previously set.
*/
get channel(): string | null;
/**
* Set the update channel. Not applicable for GitHub. Overrides `channel` in the update configuration.
*
* `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.
*/
set channel(value: string | null);
/**
* The request headers.
*/
requestHeaders: OutgoingHttpHeaders | null;
/**
* Shortcut for explicitly adding auth tokens to request headers
*/
addAuthHeader(token: string): void;
protected _logger: Logger;
get netSession(): Session;
/**
* The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.
* Set it to `null` if you would like to disable a logging feature.
*/
get logger(): Logger | null;
set logger(value: Logger | null);
/**
* For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`
*/
readonly signals: UpdaterSignal;
private _appUpdateConfigPath;
/**
* test only
* @private
*/
set updateConfigPath(value: string | null);
private clientPromise;
protected readonly stagingUserIdPromise: Lazy<string>;
private checkForUpdatesPromise;
protected readonly app: AppAdapter;
protected updateInfoAndProvider: UpdateInfoAndProvider | null;
protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter);
getFeedURL(): string | null | undefined;
/**
* Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.
* @param options If you want to override configuration in the `app-update.yml`.
*/
setFeedURL(options: PublishConfiguration | AllPublishOptions | string): void;
/**
* Asks the server whether there is an update.
*/
checkForUpdates(): Promise<UpdateCheckResult | null>;
isUpdaterActive(): boolean;
checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise<UpdateCheckResult | null>;
private static formatDownloadNotification;
private isStagingMatch;
private computeFinalHeaders;
private isUpdateAvailable;
protected getUpdateInfoAndProvider(): Promise<UpdateInfoAndProvider>;
private createProviderRuntimeOptions;
private doCheckForUpdates;
protected onUpdateAvailable(updateInfo: UpdateInfo): void;
/**
* Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.
* @returns {Promise<Array<string>>} Paths to downloaded files.
*/
downloadUpdate(cancellationToken?: CancellationToken): Promise<Array<string>>;
protected dispatchError(e: Error): void;
protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void;
protected abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>;
/**
* Restarts the app and installs the update after it has been downloaded.
* It should only be called after `update-downloaded` has been emitted.
*
* **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.
* This is different from the normal quit event sequence.
*
* @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.
* @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS.
* Ignored if `isSilent` is set to `false`(In this case you can still set `autoRunAppAfterInstall` to `false` to prevent run the app after finish).
*/
abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void;
private loadUpdateConfig;
private computeRequestHeaders;
private getOrCreateStagingUserId;
private getOrCreateDownloadHelper;
protected executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>>;
}
export interface DownloadUpdateOptions {
readonly updateInfoAndProvider: UpdateInfoAndProvider;
readonly requestHeaders: OutgoingHttpHeaders;
readonly cancellationToken: CancellationToken;
readonly disableWebInstaller?: boolean;
}
/** @private */
export declare class NoOpLogger implements Logger {
info(message?: any): void;
warn(message?: any): void;
error(message?: any): void;
}
export interface UpdateInfoAndProvider {
info: UpdateInfo;
provider: Provider<any>;
}
export interface DownloadExecutorTask {
readonly fileExtension: string;
readonly fileInfo: ResolvedUpdateFileInfo;
readonly downloadUpdateOptions: DownloadUpdateOptions;
readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise<any>) => Promise<any>;
readonly done?: (event: UpdateDownloadedEvent) => Promise<any>;
}
export interface DownloadNotification {
body: string;
title: string;
}
/** @private */
export interface TestOnlyUpdaterOptions {
platform: ProviderPlatform;
isUseDifferentialDownload?: boolean;
}
export {};

View file

@ -0,0 +1,574 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoOpLogger = exports.AppUpdater = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const crypto_1 = require("crypto");
const events_1 = require("events");
const fs_extra_1 = require("fs-extra");
const js_yaml_1 = require("js-yaml");
const lazy_val_1 = require("lazy-val");
const path = require("path");
const semver_1 = require("semver");
const DownloadedUpdateHelper_1 = require("./DownloadedUpdateHelper");
const ElectronAppAdapter_1 = require("./ElectronAppAdapter");
const electronHttpExecutor_1 = require("./electronHttpExecutor");
const GenericProvider_1 = require("./providers/GenericProvider");
const main_1 = require("./main");
const providerFactory_1 = require("./providerFactory");
class AppUpdater extends events_1.EventEmitter {
constructor(options, app) {
super();
/**
* Whether to automatically download an update when it is found.
*/
this.autoDownload = true;
/**
* Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).
*/
this.autoInstallOnAppQuit = true;
/**
* *windows-only* Whether to run the app after finish install when run the installer NOT in silent mode.
* @default true
*/
this.autoRunAppAfterInstall = true;
/**
* *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.
*
* If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).
*/
this.allowPrerelease = false;
/**
* *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.
* @default false
*/
this.fullChangelog = false;
/**
* Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).
*
* Taken in account only if channel differs (pre-release version component in terms of semantic versioning).
*
* @default false
*/
this.allowDowngrade = false;
/**
* Web installer files might not have signature verification, this switch prevents to load them unless it is needed.
*
* Currently false to prevent breaking the current API, but it should be changed to default true at some point that
* breaking changes are allowed.
*
* @default false
*/
this.disableWebInstaller = false;
/**
* Allows developer to force the updater to work in "dev" mode, looking for "dev-app-update.yml" instead of "app-update.yml"
* Dev: `path.join(this.app.getAppPath(), "dev-app-update.yml")`
* Prod: `path.join(process.resourcesPath!, "app-update.yml")`
*
* @default false
*/
this.forceDevUpdateConfig = false;
this._channel = null;
this.downloadedUpdateHelper = null;
/**
* The request headers.
*/
this.requestHeaders = null;
this._logger = console;
// noinspection JSUnusedGlobalSymbols
/**
* For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`
*/
this.signals = new main_1.UpdaterSignal(this);
this._appUpdateConfigPath = null;
this.clientPromise = null;
this.stagingUserIdPromise = new lazy_val_1.Lazy(() => this.getOrCreateStagingUserId());
// public, allow to read old config for anyone
/** @internal */
this.configOnDisk = new lazy_val_1.Lazy(() => this.loadUpdateConfig());
this.checkForUpdatesPromise = null;
this.updateInfoAndProvider = null;
/**
* @private
* @internal
*/
this._testOnlyOptions = null;
this.on("error", (error) => {
this._logger.error(`Error: ${error.stack || error.message}`);
});
if (app == null) {
this.app = new ElectronAppAdapter_1.ElectronAppAdapter();
this.httpExecutor = new electronHttpExecutor_1.ElectronHttpExecutor((authInfo, callback) => this.emit("login", authInfo, callback));
}
else {
this.app = app;
this.httpExecutor = null;
}
const currentVersionString = this.app.version;
const currentVersion = semver_1.parse(currentVersionString);
if (currentVersion == null) {
throw builder_util_runtime_1.newError(`App version is not a valid semver version: "${currentVersionString}"`, "ERR_UPDATER_INVALID_VERSION");
}
this.currentVersion = currentVersion;
this.allowPrerelease = hasPrereleaseComponents(currentVersion);
if (options != null) {
this.setFeedURL(options);
if (typeof options !== "string" && options.requestHeaders) {
this.requestHeaders = options.requestHeaders;
}
}
}
/**
* Get the update channel. Not applicable for GitHub. Doesn't return `channel` from the update configuration, only if was previously set.
*/
get channel() {
return this._channel;
}
/**
* Set the update channel. Not applicable for GitHub. Overrides `channel` in the update configuration.
*
* `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.
*/
set channel(value) {
if (this._channel != null) {
// noinspection SuspiciousTypeOfGuard
if (typeof value !== "string") {
throw builder_util_runtime_1.newError(`Channel must be a string, but got: ${value}`, "ERR_UPDATER_INVALID_CHANNEL");
}
else if (value.length === 0) {
throw builder_util_runtime_1.newError(`Channel must be not an empty string`, "ERR_UPDATER_INVALID_CHANNEL");
}
}
this._channel = value;
this.allowDowngrade = true;
}
/**
* Shortcut for explicitly adding auth tokens to request headers
*/
addAuthHeader(token) {
this.requestHeaders = Object.assign({}, this.requestHeaders, {
authorization: token,
});
}
// noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols
get netSession() {
return electronHttpExecutor_1.getNetSession();
}
/**
* The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.
* Set it to `null` if you would like to disable a logging feature.
*/
get logger() {
return this._logger;
}
set logger(value) {
this._logger = value == null ? new NoOpLogger() : value;
}
// noinspection JSUnusedGlobalSymbols
/**
* test only
* @private
*/
set updateConfigPath(value) {
this.clientPromise = null;
this._appUpdateConfigPath = value;
this.configOnDisk = new lazy_val_1.Lazy(() => this.loadUpdateConfig());
}
//noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols
getFeedURL() {
return "Deprecated. Do not use it.";
}
/**
* Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.
* @param options If you want to override configuration in the `app-update.yml`.
*/
setFeedURL(options) {
const runtimeOptions = this.createProviderRuntimeOptions();
// https://github.com/electron-userland/electron-builder/issues/1105
let provider;
if (typeof options === "string") {
provider = new GenericProvider_1.GenericProvider({ provider: "generic", url: options }, this, {
...runtimeOptions,
isUseMultipleRangeRequest: providerFactory_1.isUrlProbablySupportMultiRangeRequests(options),
});
}
else {
provider = providerFactory_1.createClient(options, this, runtimeOptions);
}
this.clientPromise = Promise.resolve(provider);
}
/**
* Asks the server whether there is an update.
*/
checkForUpdates() {
if (!this.isUpdaterActive()) {
return Promise.resolve(null);
}
let checkForUpdatesPromise = this.checkForUpdatesPromise;
if (checkForUpdatesPromise != null) {
this._logger.info("Checking for update (already in progress)");
return checkForUpdatesPromise;
}
const nullizePromise = () => (this.checkForUpdatesPromise = null);
this._logger.info("Checking for update");
checkForUpdatesPromise = this.doCheckForUpdates()
.then(it => {
nullizePromise();
return it;
})
.catch(e => {
nullizePromise();
this.emit("error", e, `Cannot check for updates: ${(e.stack || e).toString()}`);
throw e;
});
this.checkForUpdatesPromise = checkForUpdatesPromise;
return checkForUpdatesPromise;
}
isUpdaterActive() {
const isEnabled = this.app.isPackaged || this.forceDevUpdateConfig;
if (!isEnabled) {
this._logger.info("Skip checkForUpdates because application is not packed and dev update config is not forced");
return false;
}
return true;
}
// noinspection JSUnusedGlobalSymbols
checkForUpdatesAndNotify(downloadNotification) {
return this.checkForUpdates().then(it => {
if (!(it === null || it === void 0 ? void 0 : it.downloadPromise)) {
if (this._logger.debug != null) {
this._logger.debug("checkForUpdatesAndNotify called, downloadPromise is null");
}
return it;
}
void it.downloadPromise.then(() => {
const notificationContent = AppUpdater.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification);
new (require("electron").Notification)(notificationContent).show();
});
return it;
});
}
static formatDownloadNotification(version, appName, downloadNotification) {
if (downloadNotification == null) {
downloadNotification = {
title: "A new update is ready to install",
body: `{appName} version {version} has been downloaded and will be automatically installed on exit`,
};
}
downloadNotification = {
title: downloadNotification.title.replace("{appName}", appName).replace("{version}", version),
body: downloadNotification.body.replace("{appName}", appName).replace("{version}", version),
};
return downloadNotification;
}
async isStagingMatch(updateInfo) {
const rawStagingPercentage = updateInfo.stagingPercentage;
let stagingPercentage = rawStagingPercentage;
if (stagingPercentage == null) {
return true;
}
stagingPercentage = parseInt(stagingPercentage, 10);
if (isNaN(stagingPercentage)) {
this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`);
return true;
}
// convert from user 0-100 to internal 0-1
stagingPercentage = stagingPercentage / 100;
const stagingUserId = await this.stagingUserIdPromise.value;
const val = builder_util_runtime_1.UUID.parse(stagingUserId).readUInt32BE(12);
const percentage = val / 0xffffffff;
this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`);
return percentage < stagingPercentage;
}
computeFinalHeaders(headers) {
if (this.requestHeaders != null) {
Object.assign(headers, this.requestHeaders);
}
return headers;
}
async isUpdateAvailable(updateInfo) {
const latestVersion = semver_1.parse(updateInfo.version);
if (latestVersion == null) {
throw builder_util_runtime_1.newError(`This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: "${updateInfo.version}"`, "ERR_UPDATER_INVALID_VERSION");
}
const currentVersion = this.currentVersion;
if (semver_1.eq(latestVersion, currentVersion)) {
return false;
}
const isStagingMatch = await this.isStagingMatch(updateInfo);
if (!isStagingMatch) {
return false;
}
// https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227
// https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797
const isLatestVersionNewer = semver_1.gt(latestVersion, currentVersion);
const isLatestVersionOlder = semver_1.lt(latestVersion, currentVersion);
if (isLatestVersionNewer) {
return true;
}
return this.allowDowngrade && isLatestVersionOlder;
}
async getUpdateInfoAndProvider() {
await this.app.whenReady();
if (this.clientPromise == null) {
this.clientPromise = this.configOnDisk.value.then(it => providerFactory_1.createClient(it, this, this.createProviderRuntimeOptions()));
}
const client = await this.clientPromise;
const stagingUserId = await this.stagingUserIdPromise.value;
client.setRequestHeaders(this.computeFinalHeaders({ "x-user-staging-id": stagingUserId }));
return {
info: await client.getLatestVersion(),
provider: client,
};
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
createProviderRuntimeOptions() {
return {
isUseMultipleRangeRequest: true,
platform: this._testOnlyOptions == null ? process.platform : this._testOnlyOptions.platform,
executor: this.httpExecutor,
};
}
async doCheckForUpdates() {
this.emit("checking-for-update");
const result = await this.getUpdateInfoAndProvider();
const updateInfo = result.info;
if (!(await this.isUpdateAvailable(updateInfo))) {
this._logger.info(`Update for version ${this.currentVersion} is not available (latest version: ${updateInfo.version}, downgrade is ${this.allowDowngrade ? "allowed" : "disallowed"}).`);
this.emit("update-not-available", updateInfo);
return {
versionInfo: updateInfo,
updateInfo,
};
}
this.updateInfoAndProvider = result;
this.onUpdateAvailable(updateInfo);
const cancellationToken = new builder_util_runtime_1.CancellationToken();
//noinspection ES6MissingAwait
return {
versionInfo: updateInfo,
updateInfo,
cancellationToken,
downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null,
};
}
onUpdateAvailable(updateInfo) {
this._logger.info(`Found version ${updateInfo.version} (url: ${builder_util_runtime_1.asArray(updateInfo.files)
.map(it => it.url)
.join(", ")})`);
this.emit("update-available", updateInfo);
}
/**
* Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.
* @returns {Promise<Array<string>>} Paths to downloaded files.
*/
downloadUpdate(cancellationToken = new builder_util_runtime_1.CancellationToken()) {
const updateInfoAndProvider = this.updateInfoAndProvider;
if (updateInfoAndProvider == null) {
const error = new Error("Please check update first");
this.dispatchError(error);
return Promise.reject(error);
}
this._logger.info(`Downloading update from ${builder_util_runtime_1.asArray(updateInfoAndProvider.info.files)
.map(it => it.url)
.join(", ")}`);
const errorHandler = (e) => {
// https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159
if (!(e instanceof builder_util_runtime_1.CancellationError)) {
try {
this.dispatchError(e);
}
catch (nestedError) {
this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`);
}
}
return e;
};
try {
return this.doDownloadUpdate({
updateInfoAndProvider,
requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),
cancellationToken,
disableWebInstaller: this.disableWebInstaller,
}).catch(e => {
throw errorHandler(e);
});
}
catch (e) {
return Promise.reject(errorHandler(e));
}
}
dispatchError(e) {
this.emit("error", e, (e.stack || e).toString());
}
dispatchUpdateDownloaded(event) {
this.emit(main_1.UPDATE_DOWNLOADED, event);
}
async loadUpdateConfig() {
if (this._appUpdateConfigPath == null) {
this._appUpdateConfigPath = this.app.appUpdateConfigPath;
}
return js_yaml_1.load(await fs_extra_1.readFile(this._appUpdateConfigPath, "utf-8"));
}
computeRequestHeaders(provider) {
const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders;
if (fileExtraDownloadHeaders != null) {
const requestHeaders = this.requestHeaders;
return requestHeaders == null
? fileExtraDownloadHeaders
: {
...fileExtraDownloadHeaders,
...requestHeaders,
};
}
return this.computeFinalHeaders({ accept: "*/*" });
}
async getOrCreateStagingUserId() {
const file = path.join(this.app.userDataPath, ".updaterId");
try {
const id = await fs_extra_1.readFile(file, "utf-8");
if (builder_util_runtime_1.UUID.check(id)) {
return id;
}
else {
this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`);
}
}
catch (e) {
if (e.code !== "ENOENT") {
this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`);
}
}
const id = builder_util_runtime_1.UUID.v5(crypto_1.randomBytes(4096), builder_util_runtime_1.UUID.OID);
this._logger.info(`Generated new staging user ID: ${id}`);
try {
await fs_extra_1.outputFile(file, id);
}
catch (e) {
this._logger.warn(`Couldn't write out staging user ID: ${e}`);
}
return id;
}
/** @internal */
get isAddNoCacheQuery() {
const headers = this.requestHeaders;
// https://github.com/electron-userland/electron-builder/issues/3021
if (headers == null) {
return true;
}
for (const headerName of Object.keys(headers)) {
const s = headerName.toLowerCase();
if (s === "authorization" || s === "private-token") {
return false;
}
}
return true;
}
async getOrCreateDownloadHelper() {
let result = this.downloadedUpdateHelper;
if (result == null) {
const dirName = (await this.configOnDisk.value).updaterCacheDirName;
const logger = this._logger;
if (dirName == null) {
logger.error("updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?");
}
const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name);
if (logger.debug != null) {
logger.debug(`updater cache dir: ${cacheDir}`);
}
result = new DownloadedUpdateHelper_1.DownloadedUpdateHelper(cacheDir);
this.downloadedUpdateHelper = result;
}
return result;
}
async executeDownload(taskOptions) {
const fileInfo = taskOptions.fileInfo;
const downloadOptions = {
headers: taskOptions.downloadUpdateOptions.requestHeaders,
cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,
sha2: fileInfo.info.sha2,
sha512: fileInfo.info.sha512,
};
if (this.listenerCount(main_1.DOWNLOAD_PROGRESS) > 0) {
downloadOptions.onProgress = it => this.emit(main_1.DOWNLOAD_PROGRESS, it);
}
const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info;
const version = updateInfo.version;
const packageInfo = fileInfo.packageInfo;
function getCacheUpdateFileName() {
// NodeJS URL doesn't decode automatically
const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname);
if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {
return path.basename(urlPath);
}
else {
// url like /latest, generate name
return `update.${taskOptions.fileExtension}`;
}
}
const downloadedUpdateHelper = await this.getOrCreateDownloadHelper();
const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate;
await fs_extra_1.mkdir(cacheDir, { recursive: true });
const updateFileName = getCacheUpdateFileName();
let updateFile = path.join(cacheDir, updateFileName);
const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || ".7z"}`);
const done = async (isSaveCache) => {
await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache);
await taskOptions.done({
...updateInfo,
downloadedFile: updateFile,
});
return packageFile == null ? [updateFile] : [updateFile, packageFile];
};
const log = this._logger;
const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log);
if (cachedUpdateFile != null) {
updateFile = cachedUpdateFile;
return await done(false);
}
const removeFileIfAny = async () => {
await downloadedUpdateHelper.clear().catch(() => {
// ignore
});
return await fs_extra_1.unlink(updateFile).catch(() => {
// ignore
});
};
const tempUpdateFile = await DownloadedUpdateHelper_1.createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log);
try {
await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny);
await fs_extra_1.rename(tempUpdateFile, updateFile);
}
catch (e) {
await removeFileIfAny();
if (e instanceof builder_util_runtime_1.CancellationError) {
log.info("cancelled");
this.emit("update-cancelled", updateInfo);
}
throw e;
}
log.info(`New version ${version} has been downloaded to ${updateFile}`);
return await done(true);
}
}
exports.AppUpdater = AppUpdater;
function hasPrereleaseComponents(version) {
const versionPrereleaseComponent = semver_1.prerelease(version);
return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0;
}
/** @private */
class NoOpLogger {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
info(message) {
// ignore
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
warn(message) {
// ignore
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
error(message) {
// ignore
}
}
exports.NoOpLogger = NoOpLogger;
//# sourceMappingURL=AppUpdater.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,19 @@
import { AllPublishOptions } from "builder-util-runtime";
import { AppAdapter } from "./AppAdapter";
import { AppUpdater, DownloadExecutorTask } from "./AppUpdater";
export declare abstract class BaseUpdater extends AppUpdater {
protected quitAndInstallCalled: boolean;
private quitHandlerAdded;
protected constructor(options?: AllPublishOptions | null, app?: AppAdapter);
quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void;
protected executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>>;
protected abstract doInstall(options: InstallOptions): boolean;
protected install(isSilent: boolean, isForceRunAfter: boolean): boolean;
protected addQuitHandler(): void;
}
export interface InstallOptions {
readonly installerPath: string;
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
readonly isAdminRightsRequired: boolean;
}

View file

@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseUpdater = void 0;
const AppUpdater_1 = require("./AppUpdater");
class BaseUpdater extends AppUpdater_1.AppUpdater {
constructor(options, app) {
super(options, app);
this.quitAndInstallCalled = false;
this.quitHandlerAdded = false;
}
quitAndInstall(isSilent = false, isForceRunAfter = false) {
this._logger.info(`Install on explicit quitAndInstall`);
// If NOT in silent mode use `autoRunAppAfterInstall` to determine whether to force run the app
const isInstalled = this.install(isSilent, isSilent ? isForceRunAfter : this.autoRunAppAfterInstall);
if (isInstalled) {
setImmediate(() => {
// this event is normally emitted when calling quitAndInstall, this emulates that
require("electron").autoUpdater.emit("before-quit-for-update");
this.app.quit();
});
}
else {
this.quitAndInstallCalled = false;
}
}
executeDownload(taskOptions) {
return super.executeDownload({
...taskOptions,
done: event => {
this.dispatchUpdateDownloaded(event);
this.addQuitHandler();
return Promise.resolve();
},
});
}
// must be sync (because quit even handler is not async)
install(isSilent, isForceRunAfter) {
if (this.quitAndInstallCalled) {
this._logger.warn("install call ignored: quitAndInstallCalled is set to true");
return false;
}
const downloadedUpdateHelper = this.downloadedUpdateHelper;
const installerPath = downloadedUpdateHelper == null ? null : downloadedUpdateHelper.file;
const downloadedFileInfo = downloadedUpdateHelper == null ? null : downloadedUpdateHelper.downloadedFileInfo;
if (installerPath == null || downloadedFileInfo == null) {
this.dispatchError(new Error("No valid update available, can't quit and install"));
return false;
}
// prevent calling several times
this.quitAndInstallCalled = true;
try {
this._logger.info(`Install: isSilent: ${isSilent}, isForceRunAfter: ${isForceRunAfter}`);
return this.doInstall({
installerPath,
isSilent,
isForceRunAfter,
isAdminRightsRequired: downloadedFileInfo.isAdminRightsRequired,
});
}
catch (e) {
this.dispatchError(e);
return false;
}
}
addQuitHandler() {
if (this.quitHandlerAdded || !this.autoInstallOnAppQuit) {
return;
}
this.quitHandlerAdded = true;
this.app.onQuit(exitCode => {
if (this.quitAndInstallCalled) {
this._logger.info("Update installer has already been triggered. Quitting application.");
return;
}
if (!this.autoInstallOnAppQuit) {
this._logger.info("Update will not be installed on quit because autoInstallOnAppQuit is set to false.");
return;
}
if (exitCode !== 0) {
this._logger.info(`Update will be not installed on quit because application is quitting with exit code ${exitCode}`);
return;
}
this._logger.info("Auto install update on quit");
this.install(true, false);
});
}
}
exports.BaseUpdater = BaseUpdater;
//# sourceMappingURL=BaseUpdater.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,34 @@
import { UpdateInfo } from "builder-util-runtime";
import { Logger, ResolvedUpdateFileInfo } from "./main";
/** @private **/
export declare class DownloadedUpdateHelper {
readonly cacheDir: string;
private _file;
private _packageFile;
private versionInfo;
private fileInfo;
constructor(cacheDir: string);
private _downloadedFileInfo;
get downloadedFileInfo(): CachedUpdateInfo | null;
get file(): string | null;
get packageFile(): string | null;
get cacheDirForPendingUpdate(): string;
validateDownloadedPath(updateFile: string, updateInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null>;
setDownloadedFile(downloadedFile: string, packageFile: string | null, versionInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, updateFileName: string, isSaveCache: boolean): Promise<void>;
clear(): Promise<void>;
private cleanCacheDirForPendingUpdate;
/**
* Returns "update-info.json" which is created in the update cache directory's "pending" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated.
* @param fileInfo
* @param logger
*/
private getValidCachedUpdateFile;
private getUpdateInfoFile;
}
interface CachedUpdateInfo {
fileName: string;
sha512: string;
readonly isAdminRightsRequired: boolean;
}
export declare function createTempUpdateFile(name: string, cacheDir: string, log: Logger): Promise<string>;
export {};

View file

@ -0,0 +1,170 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTempUpdateFile = exports.DownloadedUpdateHelper = void 0;
const crypto_1 = require("crypto");
const fs_1 = require("fs");
// @ts-ignore
const isEqual = require("lodash.isequal");
const fs_extra_1 = require("fs-extra");
const path = require("path");
/** @private **/
class DownloadedUpdateHelper {
constructor(cacheDir) {
this.cacheDir = cacheDir;
this._file = null;
this._packageFile = null;
this.versionInfo = null;
this.fileInfo = null;
this._downloadedFileInfo = null;
}
get downloadedFileInfo() {
return this._downloadedFileInfo;
}
get file() {
return this._file;
}
get packageFile() {
return this._packageFile;
}
get cacheDirForPendingUpdate() {
return path.join(this.cacheDir, "pending");
}
async validateDownloadedPath(updateFile, updateInfo, fileInfo, logger) {
if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) {
// update has already been downloaded from this running instance
// check here only existence, not checksum
if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await fs_extra_1.pathExists(updateFile))) {
return updateFile;
}
else {
return null;
}
}
// update has already been downloaded from some previous app launch
const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger);
if (cachedUpdateFile === null) {
return null;
}
logger.info(`Update has already been downloaded to ${updateFile}).`);
this._file = cachedUpdateFile;
return cachedUpdateFile;
}
async setDownloadedFile(downloadedFile, packageFile, versionInfo, fileInfo, updateFileName, isSaveCache) {
this._file = downloadedFile;
this._packageFile = packageFile;
this.versionInfo = versionInfo;
this.fileInfo = fileInfo;
this._downloadedFileInfo = {
fileName: updateFileName,
sha512: fileInfo.info.sha512,
isAdminRightsRequired: fileInfo.info.isAdminRightsRequired === true,
};
if (isSaveCache) {
await fs_extra_1.outputJson(this.getUpdateInfoFile(), this._downloadedFileInfo);
}
}
async clear() {
this._file = null;
this._packageFile = null;
this.versionInfo = null;
this.fileInfo = null;
await this.cleanCacheDirForPendingUpdate();
}
async cleanCacheDirForPendingUpdate() {
try {
// remove stale data
await fs_extra_1.emptyDir(this.cacheDirForPendingUpdate);
}
catch (ignore) {
// ignore
}
}
/**
* Returns "update-info.json" which is created in the update cache directory's "pending" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated.
* @param fileInfo
* @param logger
*/
async getValidCachedUpdateFile(fileInfo, logger) {
var _a;
const updateInfoFilePath = this.getUpdateInfoFile();
const doesUpdateInfoFileExist = await fs_extra_1.pathExists(updateInfoFilePath);
if (!doesUpdateInfoFileExist) {
return null;
}
let cachedInfo;
try {
cachedInfo = await fs_extra_1.readJson(updateInfoFilePath);
}
catch (error) {
let message = `No cached update info available`;
if (error.code !== "ENOENT") {
await this.cleanCacheDirForPendingUpdate();
message += ` (error on read: ${error.message})`;
}
logger.info(message);
return null;
}
const isCachedInfoFileNameValid = (_a = (cachedInfo === null || cachedInfo === void 0 ? void 0 : cachedInfo.fileName) !== null) !== null && _a !== void 0 ? _a : false;
if (!isCachedInfoFileNameValid) {
logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`);
await this.cleanCacheDirForPendingUpdate();
return null;
}
if (fileInfo.info.sha512 !== cachedInfo.sha512) {
logger.info(`Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`);
await this.cleanCacheDirForPendingUpdate();
return null;
}
const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName);
if (!(await fs_extra_1.pathExists(updateFile))) {
logger.info("Cached update file doesn't exist");
return null;
}
const sha512 = await hashFile(updateFile);
if (fileInfo.info.sha512 !== sha512) {
logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`);
await this.cleanCacheDirForPendingUpdate();
return null;
}
this._downloadedFileInfo = cachedInfo;
return updateFile;
}
getUpdateInfoFile() {
return path.join(this.cacheDirForPendingUpdate, "update-info.json");
}
}
exports.DownloadedUpdateHelper = DownloadedUpdateHelper;
function hashFile(file, algorithm = "sha512", encoding = "base64", options) {
return new Promise((resolve, reject) => {
const hash = crypto_1.createHash(algorithm);
hash.on("error", reject).setEncoding(encoding);
fs_1.createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ })
.on("error", reject)
.on("end", () => {
hash.end();
resolve(hash.read());
})
.pipe(hash, { end: false });
});
}
async function createTempUpdateFile(name, cacheDir, log) {
// https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912
let nameCounter = 0;
let result = path.join(cacheDir, name);
for (let i = 0; i < 3; i++) {
try {
await fs_extra_1.unlink(result);
return result;
}
catch (e) {
if (e.code === "ENOENT") {
return result;
}
log.warn(`Error on remove temp update file: ${e}`);
result = path.join(cacheDir, `${nameCounter++}-${name}`);
}
}
return result;
}
exports.createTempUpdateFile = createTempUpdateFile;
//# sourceMappingURL=DownloadedUpdateHelper.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,14 @@
import { AppAdapter } from "./AppAdapter";
export declare class ElectronAppAdapter implements AppAdapter {
private readonly app;
constructor(app?: any);
whenReady(): Promise<void>;
get version(): string;
get name(): string;
get isPackaged(): boolean;
get appUpdateConfigPath(): string;
get userDataPath(): string;
get baseCachePath(): string;
quit(): void;
onQuit(handler: (exitCode: number) => void): void;
}

View file

@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ElectronAppAdapter = void 0;
const path = require("path");
const AppAdapter_1 = require("./AppAdapter");
class ElectronAppAdapter {
constructor(app = require("electron").app) {
this.app = app;
}
whenReady() {
return this.app.whenReady();
}
get version() {
return this.app.getVersion();
}
get name() {
return this.app.getName();
}
get isPackaged() {
return this.app.isPackaged === true;
}
get appUpdateConfigPath() {
return this.isPackaged ? path.join(process.resourcesPath, "app-update.yml") : path.join(this.app.getAppPath(), "dev-app-update.yml");
}
get userDataPath() {
return this.app.getPath("userData");
}
get baseCachePath() {
return AppAdapter_1.getAppCacheDir();
}
quit() {
this.app.quit();
}
onQuit(handler) {
this.app.once("quit", (_, exitCode) => handler(exitCode));
}
}
exports.ElectronAppAdapter = ElectronAppAdapter;
//# sourceMappingURL=ElectronAppAdapter.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"ElectronAppAdapter.js","sourceRoot":"","sources":["../src/ElectronAppAdapter.ts"],"names":[],"mappings":";;;AAAA,6BAA4B;AAC5B,6CAAyD;AAEzD,MAAa,kBAAkB;IAC7B,YAA6B,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG;QAA7B,QAAG,GAAH,GAAG,CAA0B;IAAG,CAAC;IAE9D,SAAS;QACP,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,CAAA;IAC7B,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,CAAA;IAC9B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAA;IAC3B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,KAAK,IAAI,CAAA;IACrC,CAAC;IAED,IAAI,mBAAmB;QACrB,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAc,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,oBAAoB,CAAC,CAAA;IACvI,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;IACrC,CAAC;IAED,IAAI,aAAa;QACf,OAAO,2BAAc,EAAE,CAAA;IACzB,CAAC;IAED,IAAI;QACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACjB,CAAC;IAED,MAAM,CAAC,OAAmC;QACxC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAQ,EAAE,QAAgB,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AAtCD,gDAsCC","sourcesContent":["import * as path from \"path\"\nimport { AppAdapter, getAppCacheDir } from \"./AppAdapter\"\n\nexport class ElectronAppAdapter implements AppAdapter {\n constructor(private readonly app = require(\"electron\").app) {}\n\n whenReady(): Promise<void> {\n return this.app.whenReady()\n }\n\n get version(): string {\n return this.app.getVersion()\n }\n\n get name(): string {\n return this.app.getName()\n }\n\n get isPackaged(): boolean {\n return this.app.isPackaged === true\n }\n\n get appUpdateConfigPath(): string {\n return this.isPackaged ? path.join(process.resourcesPath!, \"app-update.yml\") : path.join(this.app.getAppPath(), \"dev-app-update.yml\")\n }\n\n get userDataPath(): string {\n return this.app.getPath(\"userData\")\n }\n\n get baseCachePath(): string {\n return getAppCacheDir()\n }\n\n quit(): void {\n this.app.quit()\n }\n\n onQuit(handler: (exitCode: number) => void): void {\n this.app.once(\"quit\", (_: Event, exitCode: number) => handler(exitCode))\n }\n}\n"]}

View file

@ -0,0 +1,13 @@
import { AllPublishOptions } from "builder-util-runtime";
import { AppAdapter } from "./AppAdapter";
import { AppUpdater, DownloadUpdateOptions } from "./AppUpdater";
export declare class MacUpdater extends AppUpdater {
private readonly nativeUpdater;
private squirrelDownloadedUpdate;
private server?;
constructor(options?: AllPublishOptions, app?: AppAdapter);
private debug;
protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>;
private updateDownloaded;
quitAndInstall(): void;
}

View file

@ -0,0 +1,213 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MacUpdater = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const fs_extra_1 = require("fs-extra");
const fs_1 = require("fs");
const http_1 = require("http");
const AppUpdater_1 = require("./AppUpdater");
const Provider_1 = require("./providers/Provider");
const child_process_1 = require("child_process");
const crypto_1 = require("crypto");
class MacUpdater extends AppUpdater_1.AppUpdater {
constructor(options, app) {
super(options, app);
this.nativeUpdater = require("electron").autoUpdater;
this.squirrelDownloadedUpdate = false;
this.nativeUpdater.on("error", it => {
this._logger.warn(it);
this.emit("error", it);
});
this.nativeUpdater.on("update-downloaded", () => {
this.squirrelDownloadedUpdate = true;
});
}
debug(message) {
if (this._logger.debug != null) {
this._logger.debug(message);
}
}
async doDownloadUpdate(downloadUpdateOptions) {
let files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info);
const log = this._logger;
// detect if we are running inside Rosetta emulation
const sysctlRosettaInfoKey = "sysctl.proc_translated";
let isRosetta = false;
try {
this.debug("Checking for macOS Rosetta environment");
const result = child_process_1.execFileSync("sysctl", [sysctlRosettaInfoKey], { encoding: "utf8" });
isRosetta = result.includes(`${sysctlRosettaInfoKey}: 1`);
log.info(`Checked for macOS Rosetta environment (isRosetta=${isRosetta})`);
}
catch (e) {
log.warn(`sysctl shell command to check for macOS Rosetta environment failed: ${e}`);
}
let isArm64Mac = false;
try {
this.debug("Checking for arm64 in uname");
const result = child_process_1.execFileSync("uname", ["-a"], { encoding: "utf8" });
const isArm = result.includes("ARM");
log.info(`Checked 'uname -a': arm64=${isArm}`);
isArm64Mac = isArm64Mac || isArm;
}
catch (e) {
log.warn(`uname shell command to check for arm64 failed: ${e}`);
}
isArm64Mac = isArm64Mac || process.arch === "arm64" || isRosetta;
// allow arm64 macs to install universal or rosetta2(x64) - https://github.com/electron-userland/electron-builder/pull/5524
const isArm64 = (file) => { var _a; return file.url.pathname.includes("arm64") || ((_a = file.info.url) === null || _a === void 0 ? void 0 : _a.includes("arm64")); };
if (isArm64Mac && files.some(isArm64)) {
files = files.filter(file => isArm64Mac === isArm64(file));
}
else {
files = files.filter(file => !isArm64(file));
}
const zipFileInfo = Provider_1.findFile(files, "zip", ["pkg", "dmg"]);
if (zipFileInfo == null) {
throw builder_util_runtime_1.newError(`ZIP file not provided: ${builder_util_runtime_1.safeStringifyJson(files)}`, "ERR_UPDATER_ZIP_FILE_NOT_FOUND");
}
return this.executeDownload({
fileExtension: "zip",
fileInfo: zipFileInfo,
downloadUpdateOptions,
task: (destinationFile, downloadOptions) => {
return this.httpExecutor.download(zipFileInfo.url, destinationFile, downloadOptions);
},
done: event => this.updateDownloaded(zipFileInfo, event),
});
}
async updateDownloaded(zipFileInfo, event) {
var _a, _b;
const downloadedFile = event.downloadedFile;
const updateFileSize = (_a = zipFileInfo.info.size) !== null && _a !== void 0 ? _a : (await fs_extra_1.stat(downloadedFile)).size;
const log = this._logger;
const logContext = `fileToProxy=${zipFileInfo.url.href}`;
this.debug(`Creating proxy server for native Squirrel.Mac (${logContext})`);
(_b = this.server) === null || _b === void 0 ? void 0 : _b.close();
this.server = http_1.createServer();
this.debug(`Proxy server for native Squirrel.Mac is created (${logContext})`);
this.server.on("close", () => {
log.info(`Proxy server for native Squirrel.Mac is closed (${logContext})`);
});
// must be called after server is listening, otherwise address is null
const getServerUrl = (s) => {
const address = s.address();
if (typeof address === "string") {
return address;
}
return `http://127.0.0.1:${address === null || address === void 0 ? void 0 : address.port}`;
};
return await new Promise((resolve, reject) => {
const pass = crypto_1.randomBytes(64).toString("base64").replace(/\//g, "_").replace(/\+/g, "-");
const authInfo = Buffer.from(`autoupdater:${pass}`, "ascii");
// insecure random is ok
const fileUrl = `/${crypto_1.randomBytes(64).toString("hex")}.zip`;
this.server.on("request", (request, response) => {
const requestUrl = request.url;
log.info(`${requestUrl} requested`);
if (requestUrl === "/") {
// check for basic auth header
if (!request.headers.authorization || request.headers.authorization.indexOf("Basic ") === -1) {
response.statusCode = 401;
response.statusMessage = "Invalid Authentication Credentials";
response.end();
log.warn("No authenthication info");
return;
}
// verify auth credentials
const base64Credentials = request.headers.authorization.split(" ")[1];
const credentials = Buffer.from(base64Credentials, "base64").toString("ascii");
const [username, password] = credentials.split(":");
if (username !== "autoupdater" || password !== pass) {
response.statusCode = 401;
response.statusMessage = "Invalid Authentication Credentials";
response.end();
log.warn("Invalid authenthication credentials");
return;
}
const data = Buffer.from(`{ "url": "${getServerUrl(this.server)}${fileUrl}" }`);
response.writeHead(200, { "Content-Type": "application/json", "Content-Length": data.length });
response.end(data);
return;
}
if (!requestUrl.startsWith(fileUrl)) {
log.warn(`${requestUrl} requested, but not supported`);
response.writeHead(404);
response.end();
return;
}
log.info(`${fileUrl} requested by Squirrel.Mac, pipe ${downloadedFile}`);
let errorOccurred = false;
response.on("finish", () => {
if (!errorOccurred) {
this.nativeUpdater.removeListener("error", reject);
resolve([]);
}
});
const readStream = fs_1.createReadStream(downloadedFile);
readStream.on("error", error => {
try {
response.end();
}
catch (e) {
log.warn(`cannot end response: ${e}`);
}
errorOccurred = true;
this.nativeUpdater.removeListener("error", reject);
reject(new Error(`Cannot pipe "${downloadedFile}": ${error}`));
});
response.writeHead(200, {
"Content-Type": "application/zip",
"Content-Length": updateFileSize,
});
readStream.pipe(response);
});
this.debug(`Proxy server for native Squirrel.Mac is starting to listen (${logContext})`);
this.server.listen(0, "127.0.0.1", () => {
this.debug(`Proxy server for native Squirrel.Mac is listening (address=${getServerUrl(this.server)}, ${logContext})`);
this.nativeUpdater.setFeedURL({
url: getServerUrl(this.server),
headers: {
"Cache-Control": "no-cache",
Authorization: `Basic ${authInfo.toString("base64")}`,
},
});
// The update has been downloaded and is ready to be served to Squirrel
this.dispatchUpdateDownloaded(event);
if (this.autoInstallOnAppQuit) {
this.nativeUpdater.once("error", reject);
// This will trigger fetching and installing the file on Squirrel side
this.nativeUpdater.checkForUpdates();
}
else {
resolve([]);
}
});
});
}
quitAndInstall() {
var _a;
if (this.squirrelDownloadedUpdate) {
// update already fetched by Squirrel, it's ready to install
this.nativeUpdater.quitAndInstall();
(_a = this.server) === null || _a === void 0 ? void 0 : _a.close();
}
else {
// Quit and install as soon as Squirrel get the update
this.nativeUpdater.on("update-downloaded", () => {
var _a;
this.nativeUpdater.quitAndInstall();
(_a = this.server) === null || _a === void 0 ? void 0 : _a.close();
});
if (!this.autoInstallOnAppQuit) {
/**
* If this was not `true` previously then MacUpdater.doDownloadUpdate()
* would not actually initiate the downloading by electron's autoUpdater
*/
this.nativeUpdater.checkForUpdates();
}
}
}
}
exports.MacUpdater = MacUpdater;
//# sourceMappingURL=MacUpdater.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,18 @@
import { AllPublishOptions } from "builder-util-runtime";
import { AppAdapter } from "./AppAdapter";
import { DownloadUpdateOptions } from "./AppUpdater";
import { BaseUpdater, InstallOptions } from "./BaseUpdater";
export declare class NsisUpdater extends BaseUpdater {
/**
* Specify custom install directory path
*
*/
installDirectory?: string;
constructor(options?: AllPublishOptions | null, app?: AppAdapter);
/*** @private */
protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>;
private verifySignature;
protected doInstall(options: InstallOptions): boolean;
private differentialDownloadInstaller;
private differentialDownloadWebPackage;
}

View file

@ -0,0 +1,229 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NsisUpdater = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const child_process_1 = require("child_process");
const path = require("path");
const BaseUpdater_1 = require("./BaseUpdater");
const FileWithEmbeddedBlockMapDifferentialDownloader_1 = require("./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader");
const GenericDifferentialDownloader_1 = require("./differentialDownloader/GenericDifferentialDownloader");
const main_1 = require("./main");
const util_1 = require("./util");
const Provider_1 = require("./providers/Provider");
const fs_extra_1 = require("fs-extra");
const windowsExecutableCodeSignatureVerifier_1 = require("./windowsExecutableCodeSignatureVerifier");
const url_1 = require("url");
const zlib_1 = require("zlib");
class NsisUpdater extends BaseUpdater_1.BaseUpdater {
constructor(options, app) {
super(options, app);
}
/*** @private */
doDownloadUpdate(downloadUpdateOptions) {
const provider = downloadUpdateOptions.updateInfoAndProvider.provider;
const fileInfo = Provider_1.findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "exe");
return this.executeDownload({
fileExtension: "exe",
downloadUpdateOptions,
fileInfo,
task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => {
const packageInfo = fileInfo.packageInfo;
const isWebInstaller = packageInfo != null && packageFile != null;
if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) {
throw builder_util_runtime_1.newError(`Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`, "ERR_UPDATER_WEB_INSTALLER_DISABLED");
}
if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) {
this._logger.warn("disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version.");
}
if (isWebInstaller || (await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider))) {
await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions);
}
const signatureVerificationStatus = await this.verifySignature(destinationFile);
if (signatureVerificationStatus != null) {
await removeTempDirIfAny();
// noinspection ThrowInsideFinallyBlockJS
throw builder_util_runtime_1.newError(`New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`, "ERR_UPDATER_INVALID_SIGNATURE");
}
if (isWebInstaller) {
if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) {
try {
await this.httpExecutor.download(new url_1.URL(packageInfo.path), packageFile, {
headers: downloadUpdateOptions.requestHeaders,
cancellationToken: downloadUpdateOptions.cancellationToken,
sha512: packageInfo.sha512,
});
}
catch (e) {
try {
await fs_extra_1.unlink(packageFile);
}
catch (ignored) {
// ignore
}
throw e;
}
}
}
},
});
}
// $certificateInfo = (Get-AuthenticodeSignature 'xxx\yyy.exe'
// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains("CN=siemens.com")})
// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }
async verifySignature(tempUpdateFile) {
let publisherName;
try {
publisherName = (await this.configOnDisk.value).publisherName;
if (publisherName == null) {
return null;
}
}
catch (e) {
if (e.code === "ENOENT") {
// no app-update.yml
return null;
}
throw e;
}
return await windowsExecutableCodeSignatureVerifier_1.verifySignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile, this._logger);
}
doInstall(options) {
const args = ["--updated"];
if (options.isSilent) {
args.push("/S");
}
if (options.isForceRunAfter) {
args.push("--force-run");
}
if (this.installDirectory) {
// maybe check if folder exists
args.push(`/D=${this.installDirectory}`);
}
const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile;
if (packagePath != null) {
// only = form is supported
args.push(`--package-file=${packagePath}`);
}
const callUsingElevation = () => {
_spawn(path.join(process.resourcesPath, "elevate.exe"), [options.installerPath].concat(args)).catch(e => this.dispatchError(e));
};
if (options.isAdminRightsRequired) {
this._logger.info("isAdminRightsRequired is set to true, run installer using elevate.exe");
callUsingElevation();
return true;
}
_spawn(options.installerPath, args).catch((e) => {
// https://github.com/electron-userland/electron-builder/issues/1129
// Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors
const errorCode = e.code;
this._logger.info(`Cannot run installer: error code: ${errorCode}, error message: "${e.message}", will be executed again using elevate if EACCES"`);
if (errorCode === "UNKNOWN" || errorCode === "EACCES") {
callUsingElevation();
}
else {
this.dispatchError(e);
}
});
return true;
}
async differentialDownloadInstaller(fileInfo, downloadUpdateOptions, installerPath, provider) {
try {
if (this._testOnlyOptions != null && !this._testOnlyOptions.isUseDifferentialDownload) {
return true;
}
const blockmapFileUrls = util_1.blockmapFiles(fileInfo.url, this.app.version, downloadUpdateOptions.updateInfoAndProvider.info.version);
this._logger.info(`Download block maps (old: "${blockmapFileUrls[0]}", new: ${blockmapFileUrls[1]})`);
const downloadBlockMap = async (url) => {
const data = await this.httpExecutor.downloadToBuffer(url, {
headers: downloadUpdateOptions.requestHeaders,
cancellationToken: downloadUpdateOptions.cancellationToken,
});
if (data == null || data.length === 0) {
throw new Error(`Blockmap "${url.href}" is empty`);
}
try {
return JSON.parse(zlib_1.gunzipSync(data).toString());
}
catch (e) {
throw new Error(`Cannot parse blockmap "${url.href}", error: ${e}`);
}
};
const downloadOptions = {
newUrl: fileInfo.url,
oldFile: path.join(this.downloadedUpdateHelper.cacheDir, builder_util_runtime_1.CURRENT_APP_INSTALLER_FILE_NAME),
logger: this._logger,
newFile: installerPath,
isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,
requestHeaders: downloadUpdateOptions.requestHeaders,
cancellationToken: downloadUpdateOptions.cancellationToken,
};
if (this.listenerCount(main_1.DOWNLOAD_PROGRESS) > 0) {
downloadOptions.onProgress = it => this.emit(main_1.DOWNLOAD_PROGRESS, it);
}
const blockMapDataList = await Promise.all(blockmapFileUrls.map(u => downloadBlockMap(u)));
await new GenericDifferentialDownloader_1.GenericDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(blockMapDataList[0], blockMapDataList[1]);
return false;
}
catch (e) {
this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`);
if (this._testOnlyOptions != null) {
// test mode
throw e;
}
return true;
}
}
async differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packagePath, provider) {
if (packageInfo.blockMapSize == null) {
return true;
}
try {
const downloadOptions = {
newUrl: new url_1.URL(packageInfo.path),
oldFile: path.join(this.downloadedUpdateHelper.cacheDir, builder_util_runtime_1.CURRENT_APP_PACKAGE_FILE_NAME),
logger: this._logger,
newFile: packagePath,
requestHeaders: this.requestHeaders,
isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,
cancellationToken: downloadUpdateOptions.cancellationToken,
};
if (this.listenerCount(main_1.DOWNLOAD_PROGRESS) > 0) {
downloadOptions.onProgress = it => this.emit(main_1.DOWNLOAD_PROGRESS, it);
}
await new FileWithEmbeddedBlockMapDifferentialDownloader_1.FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download();
}
catch (e) {
this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`);
// during test (developer machine mac or linux) we must throw error
return process.platform === "win32";
}
return false;
}
}
exports.NsisUpdater = NsisUpdater;
/**
* This handles both node 8 and node 10 way of emitting error when spawning a process
* - node 8: Throws the error
* - node 10: Emit the error(Need to listen with on)
*/
async function _spawn(exe, args) {
return new Promise((resolve, reject) => {
try {
const process = child_process_1.spawn(exe, args, {
detached: true,
stdio: "ignore",
});
process.on("error", error => {
reject(error);
});
process.unref();
if (process.pid !== undefined) {
resolve(true);
}
}
catch (error) {
reject(error);
}
});
}
//# sourceMappingURL=NsisUpdater.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,33 @@
/// <reference types="node" />
import { Writable } from "stream";
import { Operation } from "./downloadPlanBuilder";
export interface PartListDataTask {
readonly oldFileFd: number;
readonly tasks: Array<Operation>;
readonly start: number;
readonly end: number;
}
export declare function copyData(task: Operation, out: Writable, oldFileFd: number, reject: (error: Error) => void, resolve: () => void): void;
export declare class DataSplitter extends Writable {
private readonly out;
private readonly options;
private readonly partIndexToTaskIndex;
private readonly partIndexToLength;
private readonly finishHandler;
partIndex: number;
private headerListBuffer;
private readState;
private ignoreByteCount;
private remainingPartDataCount;
private readonly boundaryLength;
constructor(out: Writable, options: PartListDataTask, partIndexToTaskIndex: Map<number, number>, boundary: string, partIndexToLength: Array<number>, finishHandler: () => any);
get isFinished(): boolean;
_write(data: Buffer, encoding: string, callback: (error?: Error) => void): void;
private handleData;
private copyExistingData;
private searchHeaderListEnd;
private actualPartLength;
private onPartEnd;
private processPartStarted;
private processPartData;
}

View file

@ -0,0 +1,202 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataSplitter = exports.copyData = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const fs_1 = require("fs");
const stream_1 = require("stream");
const downloadPlanBuilder_1 = require("./downloadPlanBuilder");
const DOUBLE_CRLF = Buffer.from("\r\n\r\n");
var ReadState;
(function (ReadState) {
ReadState[ReadState["INIT"] = 0] = "INIT";
ReadState[ReadState["HEADER"] = 1] = "HEADER";
ReadState[ReadState["BODY"] = 2] = "BODY";
})(ReadState || (ReadState = {}));
function copyData(task, out, oldFileFd, reject, resolve) {
const readStream = fs_1.createReadStream("", {
fd: oldFileFd,
autoClose: false,
start: task.start,
// end is inclusive
end: task.end - 1,
});
readStream.on("error", reject);
readStream.once("end", resolve);
readStream.pipe(out, {
end: false,
});
}
exports.copyData = copyData;
class DataSplitter extends stream_1.Writable {
constructor(out, options, partIndexToTaskIndex, boundary, partIndexToLength, finishHandler) {
super();
this.out = out;
this.options = options;
this.partIndexToTaskIndex = partIndexToTaskIndex;
this.partIndexToLength = partIndexToLength;
this.finishHandler = finishHandler;
this.partIndex = -1;
this.headerListBuffer = null;
this.readState = ReadState.INIT;
this.ignoreByteCount = 0;
this.remainingPartDataCount = 0;
this.actualPartLength = 0;
this.boundaryLength = boundary.length + 4; /* size of \r\n-- */
// first chunk doesn't start with \r\n
this.ignoreByteCount = this.boundaryLength - 2;
}
get isFinished() {
return this.partIndex === this.partIndexToLength.length;
}
// noinspection JSUnusedGlobalSymbols
_write(data, encoding, callback) {
if (this.isFinished) {
console.error(`Trailing ignored data: ${data.length} bytes`);
return;
}
this.handleData(data).then(callback).catch(callback);
}
async handleData(chunk) {
let start = 0;
if (this.ignoreByteCount !== 0 && this.remainingPartDataCount !== 0) {
throw builder_util_runtime_1.newError("Internal error", "ERR_DATA_SPLITTER_BYTE_COUNT_MISMATCH");
}
if (this.ignoreByteCount > 0) {
const toIgnore = Math.min(this.ignoreByteCount, chunk.length);
this.ignoreByteCount -= toIgnore;
start = toIgnore;
}
else if (this.remainingPartDataCount > 0) {
const toRead = Math.min(this.remainingPartDataCount, chunk.length);
this.remainingPartDataCount -= toRead;
await this.processPartData(chunk, 0, toRead);
start = toRead;
}
if (start === chunk.length) {
return;
}
if (this.readState === ReadState.HEADER) {
const headerListEnd = this.searchHeaderListEnd(chunk, start);
if (headerListEnd === -1) {
return;
}
start = headerListEnd;
this.readState = ReadState.BODY;
// header list is ignored, we don't need it
this.headerListBuffer = null;
}
while (true) {
if (this.readState === ReadState.BODY) {
this.readState = ReadState.INIT;
}
else {
this.partIndex++;
let taskIndex = this.partIndexToTaskIndex.get(this.partIndex);
if (taskIndex == null) {
if (this.isFinished) {
taskIndex = this.options.end;
}
else {
throw builder_util_runtime_1.newError("taskIndex is null", "ERR_DATA_SPLITTER_TASK_INDEX_IS_NULL");
}
}
const prevTaskIndex = this.partIndex === 0 ? this.options.start : this.partIndexToTaskIndex.get(this.partIndex - 1) + 1; /* prev part is download, next maybe copy */
if (prevTaskIndex < taskIndex) {
await this.copyExistingData(prevTaskIndex, taskIndex);
}
else if (prevTaskIndex > taskIndex) {
throw builder_util_runtime_1.newError("prevTaskIndex must be < taskIndex", "ERR_DATA_SPLITTER_TASK_INDEX_ASSERT_FAILED");
}
if (this.isFinished) {
this.onPartEnd();
this.finishHandler();
return;
}
start = this.searchHeaderListEnd(chunk, start);
if (start === -1) {
this.readState = ReadState.HEADER;
return;
}
}
const partLength = this.partIndexToLength[this.partIndex];
const end = start + partLength;
const effectiveEnd = Math.min(end, chunk.length);
await this.processPartStarted(chunk, start, effectiveEnd);
this.remainingPartDataCount = partLength - (effectiveEnd - start);
if (this.remainingPartDataCount > 0) {
return;
}
start = end + this.boundaryLength;
if (start >= chunk.length) {
this.ignoreByteCount = this.boundaryLength - (chunk.length - end);
return;
}
}
}
copyExistingData(index, end) {
return new Promise((resolve, reject) => {
const w = () => {
if (index === end) {
resolve();
return;
}
const task = this.options.tasks[index];
if (task.kind !== downloadPlanBuilder_1.OperationKind.COPY) {
reject(new Error("Task kind must be COPY"));
return;
}
copyData(task, this.out, this.options.oldFileFd, reject, () => {
index++;
w();
});
};
w();
});
}
searchHeaderListEnd(chunk, readOffset) {
const headerListEnd = chunk.indexOf(DOUBLE_CRLF, readOffset);
if (headerListEnd !== -1) {
return headerListEnd + DOUBLE_CRLF.length;
}
// not all headers data were received, save to buffer
const partialChunk = readOffset === 0 ? chunk : chunk.slice(readOffset);
if (this.headerListBuffer == null) {
this.headerListBuffer = partialChunk;
}
else {
this.headerListBuffer = Buffer.concat([this.headerListBuffer, partialChunk]);
}
return -1;
}
onPartEnd() {
const expectedLength = this.partIndexToLength[this.partIndex - 1];
if (this.actualPartLength !== expectedLength) {
throw builder_util_runtime_1.newError(`Expected length: ${expectedLength} differs from actual: ${this.actualPartLength}`, "ERR_DATA_SPLITTER_LENGTH_MISMATCH");
}
this.actualPartLength = 0;
}
processPartStarted(data, start, end) {
if (this.partIndex !== 0) {
this.onPartEnd();
}
return this.processPartData(data, start, end);
}
processPartData(data, start, end) {
this.actualPartLength += end - start;
const out = this.out;
if (out.write(start === 0 && data.length === end ? data : data.slice(start, end))) {
return Promise.resolve();
}
else {
return new Promise((resolve, reject) => {
out.on("error", reject);
out.once("drain", () => {
out.removeListener("error", reject);
resolve();
});
});
}
}
}
exports.DataSplitter = DataSplitter;
//# sourceMappingURL=DataSplitter.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,31 @@
/// <reference types="node" />
import { BlockMapDataHolder, HttpExecutor } from "builder-util-runtime";
import { BlockMap } from "builder-util-runtime/out/blockMapApi";
import { OutgoingHttpHeaders, RequestOptions } from "http";
import { ProgressInfo, CancellationToken } from "builder-util-runtime";
import { Logger } from "../main";
import { URL } from "url";
export interface DifferentialDownloaderOptions {
readonly oldFile: string;
readonly newUrl: URL;
readonly logger: Logger;
readonly newFile: string;
readonly requestHeaders: OutgoingHttpHeaders | null;
readonly isUseMultipleRangeRequest?: boolean;
readonly cancellationToken: CancellationToken;
onProgress?: (progress: ProgressInfo) => void;
}
export declare abstract class DifferentialDownloader {
protected readonly blockAwareFileInfo: BlockMapDataHolder;
readonly httpExecutor: HttpExecutor<any>;
readonly options: DifferentialDownloaderOptions;
fileMetadataBuffer: Buffer | null;
private readonly logger;
constructor(blockAwareFileInfo: BlockMapDataHolder, httpExecutor: HttpExecutor<any>, options: DifferentialDownloaderOptions);
createRequestOptions(): RequestOptions;
protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any>;
private downloadFile;
private doDownloadFile;
protected readRemoteBytes(start: number, endInclusive: number): Promise<Buffer>;
private request;
}

View file

@ -0,0 +1,261 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DifferentialDownloader = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const fs_extra_1 = require("fs-extra");
const fs_1 = require("fs");
const DataSplitter_1 = require("./DataSplitter");
const url_1 = require("url");
const downloadPlanBuilder_1 = require("./downloadPlanBuilder");
const multipleRangeDownloader_1 = require("./multipleRangeDownloader");
const ProgressDifferentialDownloadCallbackTransform_1 = require("./ProgressDifferentialDownloadCallbackTransform");
class DifferentialDownloader {
// noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected
constructor(blockAwareFileInfo, httpExecutor, options) {
this.blockAwareFileInfo = blockAwareFileInfo;
this.httpExecutor = httpExecutor;
this.options = options;
this.fileMetadataBuffer = null;
this.logger = options.logger;
}
createRequestOptions() {
const result = {
headers: {
...this.options.requestHeaders,
accept: "*/*",
},
};
builder_util_runtime_1.configureRequestUrl(this.options.newUrl, result);
// user-agent, cache-control and other common options
builder_util_runtime_1.configureRequestOptions(result);
return result;
}
doDownload(oldBlockMap, newBlockMap) {
// we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it
if (oldBlockMap.version !== newBlockMap.version) {
throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`);
}
const logger = this.logger;
const operations = downloadPlanBuilder_1.computeOperations(oldBlockMap, newBlockMap, logger);
if (logger.debug != null) {
logger.debug(JSON.stringify(operations, null, 2));
}
let downloadSize = 0;
let copySize = 0;
for (const operation of operations) {
const length = operation.end - operation.start;
if (operation.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) {
downloadSize += length;
}
else {
copySize += length;
}
}
const newSize = this.blockAwareFileInfo.size;
if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {
throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`);
}
logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`);
return this.downloadFile(operations);
}
downloadFile(tasks) {
const fdList = [];
const closeFiles = () => {
return Promise.all(fdList.map(openedFile => {
return fs_extra_1.close(openedFile.descriptor).catch(e => {
this.logger.error(`cannot close file "${openedFile.path}": ${e}`);
});
}));
};
return this.doDownloadFile(tasks, fdList)
.then(closeFiles)
.catch(e => {
// then must be after catch here (since then always throws error)
return closeFiles()
.catch(closeFilesError => {
// closeFiles never throw error, but just to be sure
try {
this.logger.error(`cannot close files: ${closeFilesError}`);
}
catch (errorOnLog) {
try {
console.error(errorOnLog);
}
catch (ignored) {
// ok, give up and ignore error
}
}
throw e;
})
.then(() => {
throw e;
});
});
}
async doDownloadFile(tasks, fdList) {
const oldFileFd = await fs_extra_1.open(this.options.oldFile, "r");
fdList.push({ descriptor: oldFileFd, path: this.options.oldFile });
const newFileFd = await fs_extra_1.open(this.options.newFile, "w");
fdList.push({ descriptor: newFileFd, path: this.options.newFile });
const fileOut = fs_1.createWriteStream(this.options.newFile, { fd: newFileFd });
await new Promise((resolve, reject) => {
const streams = [];
// Create our download info transformer if we have one
let downloadInfoTransform = undefined;
if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {
// TODO: Does not support multiple ranges (someone feel free to PR this!)
const expectedByteCounts = [];
let grandTotalBytes = 0;
for (const task of tasks) {
if (task.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) {
expectedByteCounts.push(task.end - task.start);
grandTotalBytes += task.end - task.start;
}
}
const progressDifferentialDownloadInfo = {
expectedByteCounts: expectedByteCounts,
grandTotal: grandTotalBytes,
};
downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform_1.ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress);
streams.push(downloadInfoTransform);
}
const digestTransform = new builder_util_runtime_1.DigestTransform(this.blockAwareFileInfo.sha512);
// to simply debug, do manual validation to allow file to be fully written
digestTransform.isValidateOnEnd = false;
streams.push(digestTransform);
// noinspection JSArrowFunctionCanBeReplacedWithShorthand
fileOut.on("finish", () => {
;
fileOut.close(() => {
// remove from fd list because closed successfully
fdList.splice(1, 1);
try {
digestTransform.validate();
}
catch (e) {
reject(e);
return;
}
resolve(undefined);
});
});
streams.push(fileOut);
let lastStream = null;
for (const stream of streams) {
stream.on("error", reject);
if (lastStream == null) {
lastStream = stream;
}
else {
lastStream = lastStream.pipe(stream);
}
}
const firstStream = streams[0];
let w;
if (this.options.isUseMultipleRangeRequest) {
w = multipleRangeDownloader_1.executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject);
w(0);
return;
}
let downloadOperationCount = 0;
let actualUrl = null;
this.logger.info(`Differential download: ${this.options.newUrl}`);
const requestOptions = this.createRequestOptions();
requestOptions.redirect = "manual";
w = (index) => {
var _a, _b;
if (index >= tasks.length) {
if (this.fileMetadataBuffer != null) {
firstStream.write(this.fileMetadataBuffer);
}
firstStream.end();
return;
}
const operation = tasks[index++];
if (operation.kind === downloadPlanBuilder_1.OperationKind.COPY) {
// We are copying, let's not send status updates to the UI
if (downloadInfoTransform) {
downloadInfoTransform.beginFileCopy();
}
DataSplitter_1.copyData(operation, firstStream, oldFileFd, reject, () => w(index));
return;
}
const range = `bytes=${operation.start}-${operation.end - 1}`;
requestOptions.headers.range = range;
(_b = (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `download range: ${range}`);
// We are starting to download
if (downloadInfoTransform) {
downloadInfoTransform.beginRangeDownload();
}
const request = this.httpExecutor.createRequest(requestOptions, response => {
// Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
if (response.statusCode >= 400) {
reject(builder_util_runtime_1.createHttpError(response));
}
response.pipe(firstStream, {
end: false,
});
response.once("end", () => {
// Pass on that we are downloading a segment
if (downloadInfoTransform) {
downloadInfoTransform.endRangeDownload();
}
if (++downloadOperationCount === 100) {
downloadOperationCount = 0;
setTimeout(() => w(index), 1000);
}
else {
w(index);
}
});
});
request.on("redirect", (statusCode, method, redirectUrl) => {
this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`);
actualUrl = redirectUrl;
builder_util_runtime_1.configureRequestUrl(new url_1.URL(actualUrl), requestOptions);
request.followRedirect();
});
this.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
request.end();
};
w(0);
});
}
async readRemoteBytes(start, endInclusive) {
const buffer = Buffer.allocUnsafe(endInclusive + 1 - start);
const requestOptions = this.createRequestOptions();
requestOptions.headers.range = `bytes=${start}-${endInclusive}`;
let position = 0;
await this.request(requestOptions, chunk => {
chunk.copy(buffer, position);
position += chunk.length;
});
if (position !== buffer.length) {
throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`);
}
return buffer;
}
request(requestOptions, dataHandler) {
return new Promise((resolve, reject) => {
const request = this.httpExecutor.createRequest(requestOptions, response => {
if (!multipleRangeDownloader_1.checkIsRangesSupported(response, reject)) {
return;
}
response.on("data", dataHandler);
response.on("end", () => resolve());
});
this.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
request.end();
});
}
}
exports.DifferentialDownloader = DifferentialDownloader;
function formatBytes(value, symbol = " KB") {
return new Intl.NumberFormat("en").format((value / 1024).toFixed(2)) + symbol;
}
// safety
function removeQuery(url) {
const index = url.indexOf("?");
return index < 0 ? url : url.substring(0, index);
}
//# sourceMappingURL=DifferentialDownloader.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,4 @@
import { DifferentialDownloader } from "./DifferentialDownloader";
export declare class FileWithEmbeddedBlockMapDifferentialDownloader extends DifferentialDownloader {
download(): Promise<void>;
}

View file

@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileWithEmbeddedBlockMapDifferentialDownloader = void 0;
const fs_extra_1 = require("fs-extra");
const DifferentialDownloader_1 = require("./DifferentialDownloader");
const zlib_1 = require("zlib");
class FileWithEmbeddedBlockMapDifferentialDownloader extends DifferentialDownloader_1.DifferentialDownloader {
async download() {
const packageInfo = this.blockAwareFileInfo;
const fileSize = packageInfo.size;
const offset = fileSize - (packageInfo.blockMapSize + 4);
this.fileMetadataBuffer = await this.readRemoteBytes(offset, fileSize - 1);
const newBlockMap = readBlockMap(this.fileMetadataBuffer.slice(0, this.fileMetadataBuffer.length - 4));
await this.doDownload(await readEmbeddedBlockMapData(this.options.oldFile), newBlockMap);
}
}
exports.FileWithEmbeddedBlockMapDifferentialDownloader = FileWithEmbeddedBlockMapDifferentialDownloader;
function readBlockMap(data) {
return JSON.parse(zlib_1.inflateRawSync(data).toString());
}
async function readEmbeddedBlockMapData(file) {
const fd = await fs_extra_1.open(file, "r");
try {
const fileSize = (await fs_extra_1.fstat(fd)).size;
const sizeBuffer = Buffer.allocUnsafe(4);
await fs_extra_1.read(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length);
const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0));
await fs_extra_1.read(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length);
await fs_extra_1.close(fd);
return readBlockMap(dataBuffer);
}
catch (e) {
await fs_extra_1.close(fd);
throw e;
}
}
//# sourceMappingURL=FileWithEmbeddedBlockMapDifferentialDownloader.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"FileWithEmbeddedBlockMapDifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader.ts"],"names":[],"mappings":";;;AACA,uCAAmD;AACnD,qEAAiE;AACjE,+BAAqC;AAErC,MAAa,8CAA+C,SAAQ,+CAAsB;IACxF,KAAK,CAAC,QAAQ;QACZ,MAAM,WAAW,GAAG,IAAI,CAAC,kBAAkB,CAAA;QAC3C,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAK,CAAA;QAClC,MAAM,MAAM,GAAG,QAAQ,GAAG,CAAC,WAAW,CAAC,YAAa,GAAG,CAAC,CAAC,CAAA;QACzD,IAAI,CAAC,kBAAkB,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAA;QAC1E,MAAM,WAAW,GAAG,YAAY,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,kBAAkB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAA;QACtG,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC,CAAA;IAC1F,CAAC;CACF;AATD,wGASC;AAED,SAAS,YAAY,CAAC,IAAY;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,qBAAc,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;AACpD,CAAC;AAED,KAAK,UAAU,wBAAwB,CAAC,IAAY;IAClD,MAAM,EAAE,GAAG,MAAM,eAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAChC,IAAI;QACF,MAAM,QAAQ,GAAG,CAAC,MAAM,gBAAK,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;QACvC,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;QACxC,MAAM,eAAI,CAAC,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;QAE9E,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;QACjE,MAAM,eAAI,CAAC,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;QAClG,MAAM,gBAAK,CAAC,EAAE,CAAC,CAAA;QAEf,OAAO,YAAY,CAAC,UAAU,CAAC,CAAA;KAChC;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,gBAAK,CAAC,EAAE,CAAC,CAAA;QACf,MAAM,CAAC,CAAA;KACR;AACH,CAAC","sourcesContent":["import { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, fstat, open, read } from \"fs-extra\"\nimport { DifferentialDownloader } from \"./DifferentialDownloader\"\nimport { inflateRawSync } from \"zlib\"\n\nexport class FileWithEmbeddedBlockMapDifferentialDownloader extends DifferentialDownloader {\n async download(): Promise<void> {\n const packageInfo = this.blockAwareFileInfo\n const fileSize = packageInfo.size!\n const offset = fileSize - (packageInfo.blockMapSize! + 4)\n this.fileMetadataBuffer = await this.readRemoteBytes(offset, fileSize - 1)\n const newBlockMap = readBlockMap(this.fileMetadataBuffer.slice(0, this.fileMetadataBuffer.length - 4))\n await this.doDownload(await readEmbeddedBlockMapData(this.options.oldFile), newBlockMap)\n }\n}\n\nfunction readBlockMap(data: Buffer): BlockMap {\n return JSON.parse(inflateRawSync(data).toString())\n}\n\nasync function readEmbeddedBlockMapData(file: string): Promise<BlockMap> {\n const fd = await open(file, \"r\")\n try {\n const fileSize = (await fstat(fd)).size\n const sizeBuffer = Buffer.allocUnsafe(4)\n await read(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length)\n\n const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0))\n await read(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length)\n await close(fd)\n\n return readBlockMap(dataBuffer)\n } catch (e) {\n await close(fd)\n throw e\n }\n}\n"]}

View file

@ -0,0 +1,5 @@
import { BlockMap } from "builder-util-runtime/out/blockMapApi";
import { DifferentialDownloader } from "./DifferentialDownloader";
export declare class GenericDifferentialDownloader extends DifferentialDownloader {
download(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any>;
}

View file

@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenericDifferentialDownloader = void 0;
const DifferentialDownloader_1 = require("./DifferentialDownloader");
class GenericDifferentialDownloader extends DifferentialDownloader_1.DifferentialDownloader {
download(oldBlockMap, newBlockMap) {
return this.doDownload(oldBlockMap, newBlockMap);
}
}
exports.GenericDifferentialDownloader = GenericDifferentialDownloader;
//# sourceMappingURL=GenericDifferentialDownloader.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"GenericDifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/GenericDifferentialDownloader.ts"],"names":[],"mappings":";;;AACA,qEAAiE;AAEjE,MAAa,6BAA8B,SAAQ,+CAAsB;IACvE,QAAQ,CAAC,WAAqB,EAAE,WAAqB;QACnD,OAAO,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,WAAW,CAAC,CAAA;IAClD,CAAC;CACF;AAJD,sEAIC","sourcesContent":["import { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { DifferentialDownloader } from \"./DifferentialDownloader\"\n\nexport class GenericDifferentialDownloader extends DifferentialDownloader {\n download(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any> {\n return this.doDownload(oldBlockMap, newBlockMap)\n }\n}\n"]}

View file

@ -0,0 +1,32 @@
/// <reference types="node" />
import { Transform } from "stream";
import { CancellationToken } from "builder-util-runtime";
export interface ProgressInfo {
total: number;
delta: number;
transferred: number;
percent: number;
bytesPerSecond: number;
}
export interface ProgressDifferentialDownloadInfo {
expectedByteCounts: Array<number>;
grandTotal: number;
}
export declare class ProgressDifferentialDownloadCallbackTransform extends Transform {
private readonly progressDifferentialDownloadInfo;
private readonly cancellationToken;
private readonly onProgress;
private start;
private transferred;
private delta;
private expectedBytes;
private index;
private operationType;
private nextUpdate;
constructor(progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo, cancellationToken: CancellationToken, onProgress: (info: ProgressInfo) => any);
_transform(chunk: any, encoding: string, callback: any): void;
beginFileCopy(): void;
beginRangeDownload(): void;
endRangeDownload(): void;
_flush(callback: any): void;
}

View file

@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProgressDifferentialDownloadCallbackTransform = void 0;
const stream_1 = require("stream");
var OperationKind;
(function (OperationKind) {
OperationKind[OperationKind["COPY"] = 0] = "COPY";
OperationKind[OperationKind["DOWNLOAD"] = 1] = "DOWNLOAD";
})(OperationKind || (OperationKind = {}));
class ProgressDifferentialDownloadCallbackTransform extends stream_1.Transform {
constructor(progressDifferentialDownloadInfo, cancellationToken, onProgress) {
super();
this.progressDifferentialDownloadInfo = progressDifferentialDownloadInfo;
this.cancellationToken = cancellationToken;
this.onProgress = onProgress;
this.start = Date.now();
this.transferred = 0;
this.delta = 0;
this.expectedBytes = 0;
this.index = 0;
this.operationType = OperationKind.COPY;
this.nextUpdate = this.start + 1000;
}
_transform(chunk, encoding, callback) {
if (this.cancellationToken.cancelled) {
callback(new Error("cancelled"), null);
return;
}
// Don't send progress update when copying from disk
if (this.operationType == OperationKind.COPY) {
callback(null, chunk);
return;
}
this.transferred += chunk.length;
this.delta += chunk.length;
const now = Date.now();
if (now >= this.nextUpdate &&
this.transferred !== this.expectedBytes /* will be emitted by endRangeDownload() */ &&
this.transferred !== this.progressDifferentialDownloadInfo.grandTotal /* will be emitted on _flush */) {
this.nextUpdate = now + 1000;
this.onProgress({
total: this.progressDifferentialDownloadInfo.grandTotal,
delta: this.delta,
transferred: this.transferred,
percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100,
bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)),
});
this.delta = 0;
}
callback(null, chunk);
}
beginFileCopy() {
this.operationType = OperationKind.COPY;
}
beginRangeDownload() {
this.operationType = OperationKind.DOWNLOAD;
this.expectedBytes += this.progressDifferentialDownloadInfo.expectedByteCounts[this.index++];
}
endRangeDownload() {
// _flush() will doour final 100%
if (this.transferred !== this.progressDifferentialDownloadInfo.grandTotal) {
this.onProgress({
total: this.progressDifferentialDownloadInfo.grandTotal,
delta: this.delta,
transferred: this.transferred,
percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100,
bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),
});
}
}
// Called when we are 100% done with the connection/download
_flush(callback) {
if (this.cancellationToken.cancelled) {
callback(new Error("cancelled"));
return;
}
this.onProgress({
total: this.progressDifferentialDownloadInfo.grandTotal,
delta: this.delta,
transferred: this.transferred,
percent: 100,
bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),
});
this.delta = 0;
this.transferred = 0;
callback(null);
}
}
exports.ProgressDifferentialDownloadCallbackTransform = ProgressDifferentialDownloadCallbackTransform;
//# sourceMappingURL=ProgressDifferentialDownloadCallbackTransform.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,12 @@
import { BlockMap } from "builder-util-runtime/out/blockMapApi";
import { Logger } from "../main";
export declare enum OperationKind {
COPY = 0,
DOWNLOAD = 1
}
export interface Operation {
kind: OperationKind;
start: number;
end: number;
}
export declare function computeOperations(oldBlockMap: BlockMap, newBlockMap: BlockMap, logger: Logger): Array<Operation>;

View file

@ -0,0 +1,114 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeOperations = exports.OperationKind = void 0;
var OperationKind;
(function (OperationKind) {
OperationKind[OperationKind["COPY"] = 0] = "COPY";
OperationKind[OperationKind["DOWNLOAD"] = 1] = "DOWNLOAD";
})(OperationKind = exports.OperationKind || (exports.OperationKind = {}));
function computeOperations(oldBlockMap, newBlockMap, logger) {
const nameToOldBlocks = buildBlockFileMap(oldBlockMap.files);
const nameToNewBlocks = buildBlockFileMap(newBlockMap.files);
let lastOperation = null;
// for now only one file is supported in block map
const blockMapFile = newBlockMap.files[0];
const operations = [];
const name = blockMapFile.name;
const oldEntry = nameToOldBlocks.get(name);
if (oldEntry == null) {
// new file (unrealistic case for now, because in any case both blockmap contain the only file named as "file")
throw new Error(`no file ${name} in old blockmap`);
}
const newFile = nameToNewBlocks.get(name);
let changedBlockCount = 0;
const { checksumToOffset: checksumToOldOffset, checksumToOldSize } = buildChecksumMap(nameToOldBlocks.get(name), oldEntry.offset, logger);
let newOffset = blockMapFile.offset;
for (let i = 0; i < newFile.checksums.length; newOffset += newFile.sizes[i], i++) {
const blockSize = newFile.sizes[i];
const checksum = newFile.checksums[i];
let oldOffset = checksumToOldOffset.get(checksum);
if (oldOffset != null && checksumToOldSize.get(checksum) !== blockSize) {
logger.warn(`Checksum ("${checksum}") matches, but size differs (old: ${checksumToOldSize.get(checksum)}, new: ${blockSize})`);
oldOffset = undefined;
}
if (oldOffset === undefined) {
// download data from new file
changedBlockCount++;
if (lastOperation != null && lastOperation.kind === OperationKind.DOWNLOAD && lastOperation.end === newOffset) {
lastOperation.end += blockSize;
}
else {
lastOperation = {
kind: OperationKind.DOWNLOAD,
start: newOffset,
end: newOffset + blockSize,
// oldBlocks: null,
};
validateAndAdd(lastOperation, operations, checksum, i);
}
}
else {
// reuse data from old file
if (lastOperation != null && lastOperation.kind === OperationKind.COPY && lastOperation.end === oldOffset) {
lastOperation.end += blockSize;
// lastOperation.oldBlocks!!.push(checksum)
}
else {
lastOperation = {
kind: OperationKind.COPY,
start: oldOffset,
end: oldOffset + blockSize,
// oldBlocks: [checksum]
};
validateAndAdd(lastOperation, operations, checksum, i);
}
}
}
if (changedBlockCount > 0) {
logger.info(`File${blockMapFile.name === "file" ? "" : " " + blockMapFile.name} has ${changedBlockCount} changed blocks`);
}
return operations;
}
exports.computeOperations = computeOperations;
const isValidateOperationRange = process.env["DIFFERENTIAL_DOWNLOAD_PLAN_BUILDER_VALIDATE_RANGES"] === "true";
function validateAndAdd(operation, operations, checksum, index) {
if (isValidateOperationRange && operations.length !== 0) {
const lastOperation = operations[operations.length - 1];
if (lastOperation.kind === operation.kind && operation.start < lastOperation.end && operation.start > lastOperation.start) {
const min = [lastOperation.start, lastOperation.end, operation.start, operation.end].reduce((p, v) => (p < v ? p : v));
throw new Error(`operation (block index: ${index}, checksum: ${checksum}, kind: ${OperationKind[operation.kind]}) overlaps previous operation (checksum: ${checksum}):\n` +
`abs: ${lastOperation.start} until ${lastOperation.end} and ${operation.start} until ${operation.end}\n` +
`rel: ${lastOperation.start - min} until ${lastOperation.end - min} and ${operation.start - min} until ${operation.end - min}`);
}
}
operations.push(operation);
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function buildChecksumMap(file, fileOffset, logger) {
const checksumToOffset = new Map();
const checksumToSize = new Map();
let offset = fileOffset;
for (let i = 0; i < file.checksums.length; i++) {
const checksum = file.checksums[i];
const size = file.sizes[i];
const existing = checksumToSize.get(checksum);
if (existing === undefined) {
checksumToOffset.set(checksum, offset);
checksumToSize.set(checksum, size);
}
else if (logger.debug != null) {
const sizeExplanation = existing === size ? "(same size)" : `(size: ${existing}, this size: ${size})`;
logger.debug(`${checksum} duplicated in blockmap ${sizeExplanation}, it doesn't lead to broken differential downloader, just corresponding block will be skipped)`);
}
offset += size;
}
return { checksumToOffset, checksumToOldSize: checksumToSize };
}
function buildBlockFileMap(list) {
const result = new Map();
for (const item of list) {
result.set(item.name, item);
}
return result;
}
//# sourceMappingURL=downloadPlanBuilder.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,7 @@
/// <reference types="node" />
import { IncomingMessage } from "http";
import { Writable } from "stream";
import { DifferentialDownloader } from "./DifferentialDownloader";
import { Operation } from "./downloadPlanBuilder";
export declare function executeTasksUsingMultipleRangeRequests(differentialDownloader: DifferentialDownloader, tasks: Array<Operation>, out: Writable, oldFileFd: number, reject: (error: Error) => void): (taskOffset: number) => void;
export declare function checkIsRangesSupported(response: IncomingMessage, reject: (error: Error) => void): boolean;

View file

@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkIsRangesSupported = exports.executeTasksUsingMultipleRangeRequests = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const DataSplitter_1 = require("./DataSplitter");
const downloadPlanBuilder_1 = require("./downloadPlanBuilder");
function executeTasksUsingMultipleRangeRequests(differentialDownloader, tasks, out, oldFileFd, reject) {
const w = (taskOffset) => {
if (taskOffset >= tasks.length) {
if (differentialDownloader.fileMetadataBuffer != null) {
out.write(differentialDownloader.fileMetadataBuffer);
}
out.end();
return;
}
const nextOffset = taskOffset + 1000;
doExecuteTasks(differentialDownloader, {
tasks,
start: taskOffset,
end: Math.min(tasks.length, nextOffset),
oldFileFd,
}, out, () => w(nextOffset), reject);
};
return w;
}
exports.executeTasksUsingMultipleRangeRequests = executeTasksUsingMultipleRangeRequests;
function doExecuteTasks(differentialDownloader, options, out, resolve, reject) {
let ranges = "bytes=";
let partCount = 0;
const partIndexToTaskIndex = new Map();
const partIndexToLength = [];
for (let i = options.start; i < options.end; i++) {
const task = options.tasks[i];
if (task.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) {
ranges += `${task.start}-${task.end - 1}, `;
partIndexToTaskIndex.set(partCount, i);
partCount++;
partIndexToLength.push(task.end - task.start);
}
}
if (partCount <= 1) {
// the only remote range - copy
const w = (index) => {
if (index >= options.end) {
resolve();
return;
}
const task = options.tasks[index++];
if (task.kind === downloadPlanBuilder_1.OperationKind.COPY) {
DataSplitter_1.copyData(task, out, options.oldFileFd, reject, () => w(index));
}
else {
const requestOptions = differentialDownloader.createRequestOptions();
requestOptions.headers.Range = `bytes=${task.start}-${task.end - 1}`;
const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => {
if (!checkIsRangesSupported(response, reject)) {
return;
}
response.pipe(out, {
end: false,
});
response.once("end", () => w(index));
});
differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
request.end();
}
};
w(options.start);
return;
}
const requestOptions = differentialDownloader.createRequestOptions();
requestOptions.headers.Range = ranges.substring(0, ranges.length - 2);
const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => {
if (!checkIsRangesSupported(response, reject)) {
return;
}
const contentType = builder_util_runtime_1.safeGetHeader(response, "content-type");
const m = /^multipart\/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i.exec(contentType);
if (m == null) {
reject(new Error(`Content-Type "multipart/byteranges" is expected, but got "${contentType}"`));
return;
}
const dicer = new DataSplitter_1.DataSplitter(out, options, partIndexToTaskIndex, m[1] || m[2], partIndexToLength, resolve);
dicer.on("error", reject);
response.pipe(dicer);
response.on("end", () => {
setTimeout(() => {
request.abort();
reject(new Error("Response ends without calling any handlers"));
}, 10000);
});
});
differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
request.end();
}
function checkIsRangesSupported(response, reject) {
// Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
if (response.statusCode >= 400) {
reject(builder_util_runtime_1.createHttpError(response));
return false;
}
if (response.statusCode !== 206) {
const acceptRanges = builder_util_runtime_1.safeGetHeader(response, "accept-ranges");
if (acceptRanges == null || acceptRanges === "none") {
reject(new Error(`Server doesn't support Accept-Ranges (response code ${response.statusCode})`));
return false;
}
}
return true;
}
exports.checkIsRangesSupported = checkIsRangesSupported;
//# sourceMappingURL=multipleRangeDownloader.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,17 @@
/// <reference types="node" />
import { DownloadOptions, HttpExecutor } from "builder-util-runtime";
import { AuthInfo } from "electron";
import { RequestOptions } from "http";
import Session = Electron.Session;
import ClientRequest = Electron.ClientRequest;
export declare type LoginCallback = (username: string, password: string) => void;
export declare const NET_SESSION_NAME = "electron-updater";
export declare function getNetSession(): Session;
export declare class ElectronHttpExecutor extends HttpExecutor<Electron.ClientRequest> {
private readonly proxyLoginCallback?;
private cachedSession;
constructor(proxyLoginCallback?: ((authInfo: AuthInfo, callback: LoginCallback) => void) | undefined);
download(url: URL, destination: string, options: DownloadOptions): Promise<string>;
createRequest(options: any, callback: (response: any) => void): Electron.ClientRequest;
protected addRedirectHandlers(request: ClientRequest, options: RequestOptions, reject: (error: Error) => void, redirectCount: number, handler: (options: RequestOptions) => void): void;
}

View file

@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ElectronHttpExecutor = exports.getNetSession = exports.NET_SESSION_NAME = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
exports.NET_SESSION_NAME = "electron-updater";
function getNetSession() {
return require("electron").session.fromPartition(exports.NET_SESSION_NAME, {
cache: false,
});
}
exports.getNetSession = getNetSession;
class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor {
constructor(proxyLoginCallback) {
super();
this.proxyLoginCallback = proxyLoginCallback;
this.cachedSession = null;
}
async download(url, destination, options) {
return await options.cancellationToken.createPromise((resolve, reject, onCancel) => {
const requestOptions = {
headers: options.headers || undefined,
redirect: "manual",
};
builder_util_runtime_1.configureRequestUrl(url, requestOptions);
builder_util_runtime_1.configureRequestOptions(requestOptions);
this.doDownload(requestOptions, {
destination,
options,
onCancel,
callback: error => {
if (error == null) {
resolve(destination);
}
else {
reject(error);
}
},
responseHandler: null,
}, 0);
});
}
createRequest(options, callback) {
// fix (node 7+) for making electron updater work when using AWS private buckets, check if headers contain Host property
if (options.headers && options.headers.Host) {
// set host value from headers.Host
options.host = options.headers.Host;
// remove header property 'Host', if not removed causes net::ERR_INVALID_ARGUMENT exception
delete options.headers.Host;
}
// differential downloader can call this method very often, so, better to cache session
if (this.cachedSession == null) {
this.cachedSession = getNetSession();
}
const request = require("electron").net.request({
...options,
session: this.cachedSession,
});
request.on("response", callback);
if (this.proxyLoginCallback != null) {
request.on("login", this.proxyLoginCallback);
}
return request;
}
addRedirectHandlers(request, options, reject, redirectCount, handler) {
request.on("redirect", (statusCode, method, redirectUrl) => {
// no way to modify request options, abort old and make a new one
// https://github.com/electron/electron/issues/11505
request.abort();
if (redirectCount > this.maxRedirects) {
reject(this.createMaxRedirectError());
}
else {
handler(builder_util_runtime_1.HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options));
}
});
}
}
exports.ElectronHttpExecutor = ElectronHttpExecutor;
//# sourceMappingURL=electronHttpExecutor.js.map

File diff suppressed because one or more lines are too long

49
electron/node_modules/electron-updater/out/main.d.ts generated vendored Normal file
View file

@ -0,0 +1,49 @@
/// <reference types="node" />
import { CancellationToken, PackageFileInfo, ProgressInfo, UpdateFileInfo, UpdateInfo } from "builder-util-runtime";
import { EventEmitter } from "events";
import { URL } from "url";
import { AppUpdater } from "./AppUpdater";
import { LoginCallback } from "./electronHttpExecutor";
export { AppUpdater, NoOpLogger } from "./AppUpdater";
export { CancellationToken, PackageFileInfo, ProgressInfo, UpdateFileInfo, UpdateInfo };
export { Provider } from "./providers/Provider";
export { AppImageUpdater } from "./AppImageUpdater";
export { MacUpdater } from "./MacUpdater";
export { NsisUpdater } from "./NsisUpdater";
export declare const autoUpdater: AppUpdater;
export interface ResolvedUpdateFileInfo {
readonly url: URL;
readonly info: UpdateFileInfo;
packageInfo?: PackageFileInfo;
}
export interface UpdateCheckResult {
readonly updateInfo: UpdateInfo;
readonly downloadPromise?: Promise<Array<string>> | null;
readonly cancellationToken?: CancellationToken;
/** @deprecated */
readonly versionInfo: UpdateInfo;
}
export declare type UpdaterEvents = "login" | "checking-for-update" | "update-available" | "update-not-available" | "update-cancelled" | "download-progress" | "update-downloaded" | "error";
export declare const DOWNLOAD_PROGRESS = "download-progress";
export declare const UPDATE_DOWNLOADED = "update-downloaded";
export declare type LoginHandler = (authInfo: any, callback: LoginCallback) => void;
export declare class UpdaterSignal {
private emitter;
constructor(emitter: EventEmitter);
/**
* Emitted when an authenticating proxy is [asking for user credentials](https://github.com/electron/electron/blob/master/docs/api/client-request.md#event-login).
*/
login(handler: LoginHandler): void;
progress(handler: (info: ProgressInfo) => void): void;
updateDownloaded(handler: (info: UpdateDownloadedEvent) => void): void;
updateCancelled(handler: (info: UpdateInfo) => void): void;
}
export interface UpdateDownloadedEvent extends UpdateInfo {
downloadedFile: string;
}
export interface Logger {
info(message?: any): void;
warn(message?: any): void;
error(message?: any): void;
debug?(message: string): void;
}

73
electron/node_modules/electron-updater/out/main.js generated vendored Normal file
View file

@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdaterSignal = exports.UPDATE_DOWNLOADED = exports.DOWNLOAD_PROGRESS = exports.NsisUpdater = exports.MacUpdater = exports.AppImageUpdater = exports.Provider = exports.CancellationToken = exports.NoOpLogger = exports.AppUpdater = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return builder_util_runtime_1.CancellationToken; } });
var AppUpdater_1 = require("./AppUpdater");
Object.defineProperty(exports, "AppUpdater", { enumerable: true, get: function () { return AppUpdater_1.AppUpdater; } });
Object.defineProperty(exports, "NoOpLogger", { enumerable: true, get: function () { return AppUpdater_1.NoOpLogger; } });
var Provider_1 = require("./providers/Provider");
Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return Provider_1.Provider; } });
var AppImageUpdater_1 = require("./AppImageUpdater");
Object.defineProperty(exports, "AppImageUpdater", { enumerable: true, get: function () { return AppImageUpdater_1.AppImageUpdater; } });
var MacUpdater_1 = require("./MacUpdater");
Object.defineProperty(exports, "MacUpdater", { enumerable: true, get: function () { return MacUpdater_1.MacUpdater; } });
var NsisUpdater_1 = require("./NsisUpdater");
Object.defineProperty(exports, "NsisUpdater", { enumerable: true, get: function () { return NsisUpdater_1.NsisUpdater; } });
// autoUpdater to mimic electron bundled autoUpdater
let _autoUpdater;
function doLoadAutoUpdater() {
// tslint:disable:prefer-conditional-expression
if (process.platform === "win32") {
_autoUpdater = new (require("./NsisUpdater").NsisUpdater)();
}
else if (process.platform === "darwin") {
_autoUpdater = new (require("./MacUpdater").MacUpdater)();
}
else {
_autoUpdater = new (require("./AppImageUpdater").AppImageUpdater)();
}
return _autoUpdater;
}
Object.defineProperty(exports, "autoUpdater", {
enumerable: true,
get: () => {
return _autoUpdater || doLoadAutoUpdater();
},
});
exports.DOWNLOAD_PROGRESS = "download-progress";
exports.UPDATE_DOWNLOADED = "update-downloaded";
class UpdaterSignal {
constructor(emitter) {
this.emitter = emitter;
}
/**
* Emitted when an authenticating proxy is [asking for user credentials](https://github.com/electron/electron/blob/master/docs/api/client-request.md#event-login).
*/
login(handler) {
addHandler(this.emitter, "login", handler);
}
progress(handler) {
addHandler(this.emitter, exports.DOWNLOAD_PROGRESS, handler);
}
updateDownloaded(handler) {
addHandler(this.emitter, exports.UPDATE_DOWNLOADED, handler);
}
updateCancelled(handler) {
addHandler(this.emitter, "update-cancelled", handler);
}
}
exports.UpdaterSignal = UpdaterSignal;
const isLogEvent = false;
function addHandler(emitter, event, handler) {
if (isLogEvent) {
emitter.on(event, (...args) => {
console.log("%s %s", event, args);
handler(...args);
});
}
else {
emitter.on(event, handler);
}
}
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,5 @@
import { AllPublishOptions, PublishConfiguration } from "builder-util-runtime";
import { AppUpdater } from "./AppUpdater";
import { Provider, ProviderRuntimeOptions } from "./providers/Provider";
export declare function isUrlProbablySupportMultiRangeRequests(url: string): boolean;
export declare function createClient(data: PublishConfiguration | AllPublishOptions, updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions): Provider<any>;

View file

@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClient = exports.isUrlProbablySupportMultiRangeRequests = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const BitbucketProvider_1 = require("./providers/BitbucketProvider");
const GenericProvider_1 = require("./providers/GenericProvider");
const GitHubProvider_1 = require("./providers/GitHubProvider");
const KeygenProvider_1 = require("./providers/KeygenProvider");
const PrivateGitHubProvider_1 = require("./providers/PrivateGitHubProvider");
function isUrlProbablySupportMultiRangeRequests(url) {
return !url.includes("s3.amazonaws.com");
}
exports.isUrlProbablySupportMultiRangeRequests = isUrlProbablySupportMultiRangeRequests;
function createClient(data, updater, runtimeOptions) {
// noinspection SuspiciousTypeOfGuard
if (typeof data === "string") {
throw builder_util_runtime_1.newError("Please pass PublishConfiguration object", "ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION");
}
const provider = data.provider;
switch (provider) {
case "github": {
const githubOptions = data;
const token = (githubOptions.private ? process.env["GH_TOKEN"] || process.env["GITHUB_TOKEN"] : null) || githubOptions.token;
if (token == null) {
return new GitHubProvider_1.GitHubProvider(githubOptions, updater, runtimeOptions);
}
else {
return new PrivateGitHubProvider_1.PrivateGitHubProvider(githubOptions, updater, token, runtimeOptions);
}
}
case "bitbucket":
return new BitbucketProvider_1.BitbucketProvider(data, updater, runtimeOptions);
case "keygen":
return new KeygenProvider_1.KeygenProvider(data, updater, runtimeOptions);
case "s3":
case "spaces":
return new GenericProvider_1.GenericProvider({
provider: "generic",
url: builder_util_runtime_1.getS3LikeProviderBaseUrl(data),
channel: data.channel || null,
}, updater, {
...runtimeOptions,
// https://github.com/minio/minio/issues/5285#issuecomment-350428955
isUseMultipleRangeRequest: false,
});
case "generic": {
const options = data;
return new GenericProvider_1.GenericProvider(options, updater, {
...runtimeOptions,
isUseMultipleRangeRequest: options.useMultipleRangeRequest !== false && isUrlProbablySupportMultiRangeRequests(options.url),
});
}
case "custom": {
const options = data;
const constructor = options.updateProvider;
if (!constructor) {
throw builder_util_runtime_1.newError("Custom provider not specified", "ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION");
}
return new constructor(options, updater, runtimeOptions);
}
default:
throw builder_util_runtime_1.newError(`Unsupported provider: ${provider}`, "ERR_UPDATER_UNSUPPORTED_PROVIDER");
}
}
exports.createClient = createClient;
//# sourceMappingURL=providerFactory.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,14 @@
import { BitbucketOptions, UpdateInfo } from "builder-util-runtime";
import { AppUpdater } from "../AppUpdater";
import { ResolvedUpdateFileInfo } from "../main";
import { Provider, ProviderRuntimeOptions } from "./Provider";
export declare class BitbucketProvider extends Provider<UpdateInfo> {
private readonly configuration;
private readonly updater;
private readonly baseUrl;
constructor(configuration: BitbucketOptions, updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions);
private get channel();
getLatestVersion(): Promise<UpdateInfo>;
resolveFiles(updateInfo: UpdateInfo): Array<ResolvedUpdateFileInfo>;
toString(): string;
}

View file

@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BitbucketProvider = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const util_1 = require("../util");
const Provider_1 = require("./Provider");
class BitbucketProvider extends Provider_1.Provider {
constructor(configuration, updater, runtimeOptions) {
super({
...runtimeOptions,
isUseMultipleRangeRequest: false,
});
this.configuration = configuration;
this.updater = updater;
const { owner, slug } = configuration;
this.baseUrl = util_1.newBaseUrl(`https://api.bitbucket.org/2.0/repositories/${owner}/${slug}/downloads`);
}
get channel() {
return this.updater.channel || this.configuration.channel || "latest";
}
async getLatestVersion() {
const cancellationToken = new builder_util_runtime_1.CancellationToken();
const channelFile = util_1.getChannelFilename(this.getCustomChannelName(this.channel));
const channelUrl = util_1.newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery);
try {
const updateInfo = await this.httpRequest(channelUrl, undefined, cancellationToken);
return Provider_1.parseUpdateInfo(updateInfo, channelFile, channelUrl);
}
catch (e) {
throw builder_util_runtime_1.newError(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND");
}
}
resolveFiles(updateInfo) {
return Provider_1.resolveFiles(updateInfo, this.baseUrl);
}
toString() {
const { owner, slug } = this.configuration;
return `Bitbucket (owner: ${owner}, slug: ${slug}, channel: ${this.channel})`;
}
}
exports.BitbucketProvider = BitbucketProvider;
//# sourceMappingURL=BitbucketProvider.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"BitbucketProvider.js","sourceRoot":"","sources":["../../src/providers/BitbucketProvider.ts"],"names":[],"mappings":";;;AAAA,+DAAgG;AAGhG,kCAAwE;AACxE,yCAA4F;AAE5F,MAAa,iBAAkB,SAAQ,mBAAoB;IAGzD,YAA6B,aAA+B,EAAmB,OAAmB,EAAE,cAAsC;QACxI,KAAK,CAAC;YACJ,GAAG,cAAc;YACjB,yBAAyB,EAAE,KAAK;SACjC,CAAC,CAAA;QAJyB,kBAAa,GAAb,aAAa,CAAkB;QAAmB,YAAO,GAAP,OAAO,CAAY;QAKhG,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,aAAa,CAAA;QACrC,IAAI,CAAC,OAAO,GAAG,iBAAU,CAAC,8CAA8C,KAAK,IAAI,IAAI,YAAY,CAAC,CAAA;IACpG,CAAC;IAED,IAAY,OAAO;QACjB,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,IAAI,QAAQ,CAAA;IACvE,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,iBAAiB,GAAG,IAAI,wCAAiB,EAAE,CAAA;QACjD,MAAM,WAAW,GAAG,yBAAkB,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAC/E,MAAM,UAAU,GAAG,qBAAc,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QAC5F,IAAI;YACF,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;YACnF,OAAO,0BAAe,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,CAAA;SAC5D;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,+BAAQ,CAAC,oCAAoC,IAAI,CAAC,QAAQ,EAAE,mCAAmC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,sCAAsC,CAAC,CAAA;SACrK;IACH,CAAC;IAED,YAAY,CAAC,UAAsB;QACjC,OAAO,uBAAY,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/C,CAAC;IAED,QAAQ;QACN,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,aAAa,CAAA;QAC1C,OAAO,qBAAqB,KAAK,WAAW,IAAI,cAAc,IAAI,CAAC,OAAO,GAAG,CAAA;IAC/E,CAAC;CACF;AApCD,8CAoCC","sourcesContent":["import { CancellationToken, BitbucketOptions, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../main\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nexport class BitbucketProvider extends Provider<UpdateInfo> {\n private readonly baseUrl: URL\n\n constructor(private readonly configuration: BitbucketOptions, private readonly updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions) {\n super({\n ...runtimeOptions,\n isUseMultipleRangeRequest: false,\n })\n const { owner, slug } = configuration\n this.baseUrl = newBaseUrl(`https://api.bitbucket.org/2.0/repositories/${owner}/${slug}/downloads`)\n }\n\n private get channel(): string {\n return this.updater.channel || this.configuration.channel || \"latest\"\n }\n\n async getLatestVersion(): Promise<UpdateInfo> {\n const cancellationToken = new CancellationToken()\n const channelFile = getChannelFilename(this.getCustomChannelName(this.channel))\n const channelUrl = newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery)\n try {\n const updateInfo = await this.httpRequest(channelUrl, undefined, cancellationToken)\n return parseUpdateInfo(updateInfo, channelFile, channelUrl)\n } catch (e) {\n throw newError(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n }\n\n resolveFiles(updateInfo: UpdateInfo): Array<ResolvedUpdateFileInfo> {\n return resolveFiles(updateInfo, this.baseUrl)\n }\n\n toString() {\n const { owner, slug } = this.configuration\n return `Bitbucket (owner: ${owner}, slug: ${slug}, channel: ${this.channel})`\n }\n}\n"]}

View file

@ -0,0 +1,13 @@
import { GenericServerOptions, UpdateInfo } from "builder-util-runtime";
import { AppUpdater } from "../AppUpdater";
import { ResolvedUpdateFileInfo } from "../main";
import { Provider, ProviderRuntimeOptions } from "./Provider";
export declare class GenericProvider extends Provider<UpdateInfo> {
private readonly configuration;
private readonly updater;
private readonly baseUrl;
constructor(configuration: GenericServerOptions, updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions);
private get channel();
getLatestVersion(): Promise<UpdateInfo>;
resolveFiles(updateInfo: UpdateInfo): Array<ResolvedUpdateFileInfo>;
}

View file

@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenericProvider = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const util_1 = require("../util");
const Provider_1 = require("./Provider");
class GenericProvider extends Provider_1.Provider {
constructor(configuration, updater, runtimeOptions) {
super(runtimeOptions);
this.configuration = configuration;
this.updater = updater;
this.baseUrl = util_1.newBaseUrl(this.configuration.url);
}
get channel() {
const result = this.updater.channel || this.configuration.channel;
return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result);
}
async getLatestVersion() {
const channelFile = util_1.getChannelFilename(this.channel);
const channelUrl = util_1.newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery);
for (let attemptNumber = 0;; attemptNumber++) {
try {
return Provider_1.parseUpdateInfo(await this.httpRequest(channelUrl), channelFile, channelUrl);
}
catch (e) {
if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) {
throw builder_util_runtime_1.newError(`Cannot find channel "${channelFile}" update info: ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND");
}
else if (e.code === "ECONNREFUSED") {
if (attemptNumber < 3) {
await new Promise((resolve, reject) => {
try {
setTimeout(resolve, 1000 * attemptNumber);
}
catch (e) {
reject(e);
}
});
continue;
}
}
throw e;
}
}
}
resolveFiles(updateInfo) {
return Provider_1.resolveFiles(updateInfo, this.baseUrl);
}
}
exports.GenericProvider = GenericProvider;
//# sourceMappingURL=GenericProvider.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"GenericProvider.js","sourceRoot":"","sources":["../../src/providers/GenericProvider.ts"],"names":[],"mappings":";;;AAAA,+DAA4F;AAG5F,kCAAwE;AACxE,yCAA4F;AAE5F,MAAa,eAAgB,SAAQ,mBAAoB;IAGvD,YAA6B,aAAmC,EAAmB,OAAmB,EAAE,cAAsC;QAC5I,KAAK,CAAC,cAAc,CAAC,CAAA;QADM,kBAAa,GAAb,aAAa,CAAsB;QAAmB,YAAO,GAAP,OAAO,CAAY;QAFrF,YAAO,GAAG,iBAAU,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;IAI7D,CAAC;IAED,IAAY,OAAO;QACjB,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,CAAA;QACjE,OAAO,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAA;IAC1F,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,WAAW,GAAG,yBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QACpD,MAAM,UAAU,GAAG,qBAAc,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QAC5F,KAAK,IAAI,aAAa,GAAG,CAAC,GAAI,aAAa,EAAE,EAAE;YAC7C,IAAI;gBACF,OAAO,0BAAe,CAAC,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,WAAW,EAAE,UAAU,CAAC,CAAA;aACpF;YAAC,OAAO,CAAC,EAAE;gBACV,IAAI,CAAC,YAAY,gCAAS,IAAI,CAAC,CAAC,UAAU,KAAK,GAAG,EAAE;oBAClD,MAAM,+BAAQ,CAAC,wBAAwB,WAAW,kBAAkB,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,oCAAoC,CAAC,CAAA;iBAClI;qBAAM,IAAI,CAAC,CAAC,IAAI,KAAK,cAAc,EAAE;oBACpC,IAAI,aAAa,GAAG,CAAC,EAAE;wBACrB,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;4BACpC,IAAI;gCACF,UAAU,CAAC,OAAO,EAAE,IAAI,GAAG,aAAa,CAAC,CAAA;6BAC1C;4BAAC,OAAO,CAAC,EAAE;gCACV,MAAM,CAAC,CAAC,CAAC,CAAA;6BACV;wBACH,CAAC,CAAC,CAAA;wBACF,SAAQ;qBACT;iBACF;gBACD,MAAM,CAAC,CAAA;aACR;SACF;IACH,CAAC;IAED,YAAY,CAAC,UAAsB;QACjC,OAAO,uBAAY,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/C,CAAC;CACF;AAzCD,0CAyCC","sourcesContent":["import { GenericServerOptions, HttpError, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../main\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nexport class GenericProvider extends Provider<UpdateInfo> {\n private readonly baseUrl = newBaseUrl(this.configuration.url)\n\n constructor(private readonly configuration: GenericServerOptions, private readonly updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions) {\n super(runtimeOptions)\n }\n\n private get channel(): string {\n const result = this.updater.channel || this.configuration.channel\n return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result)\n }\n\n async getLatestVersion(): Promise<UpdateInfo> {\n const channelFile = getChannelFilename(this.channel)\n const channelUrl = newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery)\n for (let attemptNumber = 0; ; attemptNumber++) {\n try {\n return parseUpdateInfo(await this.httpRequest(channelUrl), channelFile, channelUrl)\n } catch (e) {\n if (e instanceof HttpError && e.statusCode === 404) {\n throw newError(`Cannot find channel \"${channelFile}\" update info: ${e.stack || e.message}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n } else if (e.code === \"ECONNREFUSED\") {\n if (attemptNumber < 3) {\n await new Promise((resolve, reject) => {\n try {\n setTimeout(resolve, 1000 * attemptNumber)\n } catch (e) {\n reject(e)\n }\n })\n continue\n }\n }\n throw e\n }\n }\n }\n\n resolveFiles(updateInfo: UpdateInfo): Array<ResolvedUpdateFileInfo> {\n return resolveFiles(updateInfo, this.baseUrl)\n }\n}\n"]}

View file

@ -0,0 +1,29 @@
/// <reference types="node" />
import { GithubOptions, ReleaseNoteInfo, UpdateInfo, XElement } from "builder-util-runtime";
import * as semver from "semver";
import { URL } from "url";
import { AppUpdater } from "../AppUpdater";
import { ResolvedUpdateFileInfo } from "../main";
import { Provider, ProviderRuntimeOptions } from "./Provider";
interface GithubUpdateInfo extends UpdateInfo {
tag: string;
}
export declare abstract class BaseGitHubProvider<T extends UpdateInfo> extends Provider<T> {
protected readonly options: GithubOptions;
protected readonly baseUrl: URL;
protected readonly baseApiUrl: URL;
protected constructor(options: GithubOptions, defaultHost: string, runtimeOptions: ProviderRuntimeOptions);
protected computeGithubBasePath(result: string): string;
}
export declare class GitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
protected readonly options: GithubOptions;
private readonly updater;
constructor(options: GithubOptions, updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions);
getLatestVersion(): Promise<GithubUpdateInfo>;
private getLatestTagName;
private get basePath();
resolveFiles(updateInfo: GithubUpdateInfo): Array<ResolvedUpdateFileInfo>;
private getBaseDownloadPath;
}
export declare function computeReleaseNotes(currentVersion: semver.SemVer, isFullChangelog: boolean, feed: XElement, latestRelease: any): string | Array<ReleaseNoteInfo> | null;
export {};

View file

@ -0,0 +1,191 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeReleaseNotes = exports.GitHubProvider = exports.BaseGitHubProvider = void 0;
const builder_util_runtime_1 = require("builder-util-runtime");
const semver = require("semver");
const url_1 = require("url");
const util_1 = require("../util");
const Provider_1 = require("./Provider");
const hrefRegExp = /\/tag\/([^/]+)$/;
class BaseGitHubProvider extends Provider_1.Provider {
constructor(options, defaultHost, runtimeOptions) {
super({
...runtimeOptions,
/* because GitHib uses S3 */
isUseMultipleRangeRequest: false,
});
this.options = options;
this.baseUrl = util_1.newBaseUrl(builder_util_runtime_1.githubUrl(options, defaultHost));
const apiHost = defaultHost === "github.com" ? "api.github.com" : defaultHost;
this.baseApiUrl = util_1.newBaseUrl(builder_util_runtime_1.githubUrl(options, apiHost));
}
computeGithubBasePath(result) {
// https://github.com/electron-userland/electron-builder/issues/1903#issuecomment-320881211
const host = this.options.host;
return host && !["github.com", "api.github.com"].includes(host) ? `/api/v3${result}` : result;
}
}
exports.BaseGitHubProvider = BaseGitHubProvider;
class GitHubProvider extends BaseGitHubProvider {
constructor(options, updater, runtimeOptions) {
super(options, "github.com", runtimeOptions);
this.options = options;
this.updater = updater;
}
async getLatestVersion() {
var _a, _b, _c, _d;
const cancellationToken = new builder_util_runtime_1.CancellationToken();
const feedXml = (await this.httpRequest(util_1.newUrlFromBase(`${this.basePath}.atom`, this.baseUrl), {
accept: "application/xml, application/atom+xml, text/xml, */*",
}, cancellationToken));
const feed = builder_util_runtime_1.parseXml(feedXml);
// noinspection TypeScriptValidateJSTypes
let latestRelease = feed.element("entry", false, `No published versions on GitHub`);
let tag = null;
try {
if (this.updater.allowPrerelease) {
const currentChannel = ((_a = this.updater) === null || _a === void 0 ? void 0 : _a.channel) || ((_b = semver.prerelease(this.updater.currentVersion)) === null || _b === void 0 ? void 0 : _b[0]) || null;
if (currentChannel === null) {
// noinspection TypeScriptValidateJSTypes
tag = hrefRegExp.exec(latestRelease.element("link").attribute("href"))[1];
}
else {
for (const element of feed.getElements("entry")) {
// noinspection TypeScriptValidateJSTypes
const hrefElement = hrefRegExp.exec(element.element("link").attribute("href"));
// If this is null then something is wrong and skip this release
if (hrefElement === null)
continue;
// This Release's Tag
const hrefTag = hrefElement[1];
//Get Channel from this release's tag
const hrefChannel = ((_c = semver.prerelease(hrefTag)) === null || _c === void 0 ? void 0 : _c[0]) || null;
const shouldFetchVersion = !currentChannel || ["alpha", "beta"].includes(currentChannel);
const isCustomChannel = !["alpha", "beta"].includes(String(hrefChannel));
// Allow moving from alpha to beta but not down
const channelMismatch = currentChannel === "beta" && hrefChannel === "alpha";
if (shouldFetchVersion && !isCustomChannel && !channelMismatch) {
tag = hrefTag;
break;
}
const isNextPreRelease = hrefChannel && hrefChannel === currentChannel;
if (isNextPreRelease) {
tag = hrefTag;
break;
}
}
}
}
else {
tag = await this.getLatestTagName(cancellationToken);
for (const element of feed.getElements("entry")) {
// noinspection TypeScriptValidateJSTypes
if (hrefRegExp.exec(element.element("link").attribute("href"))[1] === tag) {
latestRelease = element;
break;
}
}
}
}
catch (e) {
throw builder_util_runtime_1.newError(`Cannot parse releases feed: ${e.stack || e.message},\nXML:\n${feedXml}`, "ERR_UPDATER_INVALID_RELEASE_FEED");
}
if (tag == null) {
throw builder_util_runtime_1.newError(`No published versions on GitHub`, "ERR_UPDATER_NO_PUBLISHED_VERSIONS");
}
let rawData;
let channelFile = "";
let channelFileUrl = "";
const fetchData = async (channelName) => {
channelFile = util_1.getChannelFilename(channelName);
channelFileUrl = util_1.newUrlFromBase(this.getBaseDownloadPath(String(tag), channelFile), this.baseUrl);
const requestOptions = this.createRequestOptions(channelFileUrl);
try {
return (await this.executor.request(requestOptions, cancellationToken));
}
catch (e) {
if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) {
throw builder_util_runtime_1.newError(`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND");
}
throw e;
}
};
try {
const channel = this.updater.allowPrerelease ? this.getCustomChannelName(String(((_d = semver.prerelease(tag)) === null || _d === void 0 ? void 0 : _d[0]) || "latest")) : this.getDefaultChannelName();
rawData = await fetchData(channel);
}
catch (e) {
if (this.updater.allowPrerelease) {
// Allow fallback to `latest.yml`
rawData = await fetchData(this.getDefaultChannelName());
}
else {
throw e;
}
}
const result = Provider_1.parseUpdateInfo(rawData, channelFile, channelFileUrl);
if (result.releaseName == null) {
result.releaseName = latestRelease.elementValueOrEmpty("title");
}
if (result.releaseNotes == null) {
result.releaseNotes = computeReleaseNotes(this.updater.currentVersion, this.updater.fullChangelog, feed, latestRelease);
}
return {
tag: tag,
...result,
};
}
async getLatestTagName(cancellationToken) {
const options = this.options;
// do not use API for GitHub to avoid limit, only for custom host or GitHub Enterprise
const url = options.host == null || options.host === "github.com"
? util_1.newUrlFromBase(`${this.basePath}/latest`, this.baseUrl)
: new url_1.URL(`${this.computeGithubBasePath(`/repos/${options.owner}/${options.repo}/releases`)}/latest`, this.baseApiUrl);
try {
const rawData = await this.httpRequest(url, { Accept: "application/json" }, cancellationToken);
if (rawData == null) {
return null;
}
const releaseInfo = JSON.parse(rawData);
return releaseInfo.tag_name;
}
catch (e) {
throw builder_util_runtime_1.newError(`Unable to find latest version on GitHub (${url}), please ensure a production release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND");
}
}
get basePath() {
return `/${this.options.owner}/${this.options.repo}/releases`;
}
resolveFiles(updateInfo) {
// still replace space to - due to backward compatibility
return Provider_1.resolveFiles(updateInfo, this.baseUrl, p => this.getBaseDownloadPath(updateInfo.tag, p.replace(/ /g, "-")));
}
getBaseDownloadPath(tag, fileName) {
return `${this.basePath}/download/${tag}/${fileName}`;
}
}
exports.GitHubProvider = GitHubProvider;
function getNoteValue(parent) {
const result = parent.elementValueOrEmpty("content");
// GitHub reports empty notes as <content>No content.</content>
return result === "No content." ? "" : result;
}
function computeReleaseNotes(currentVersion, isFullChangelog, feed, latestRelease) {
if (!isFullChangelog) {
return getNoteValue(latestRelease);
}
const releaseNotes = [];
for (const release of feed.getElements("entry")) {
// noinspection TypeScriptValidateJSTypes
const versionRelease = /\/tag\/v?([^/]+)$/.exec(release.element("link").attribute("href"))[1];
if (semver.lt(currentVersion, versionRelease)) {
releaseNotes.push({
version: versionRelease,
note: getNoteValue(release),
});
}
}
return releaseNotes.sort((a, b) => semver.rcompare(a.version, b.version));
}
exports.computeReleaseNotes = computeReleaseNotes;
//# sourceMappingURL=GitHubProvider.js.map

Some files were not shown because too many files have changed in this diff Show more