This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

1
node_modules/metro-cache/node_modules/.bin/rimraf generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rimraf/bin.js

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
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,47 @@
# jest-serializer
Module for serializing and deserializing object into memory and disk. By default, the `v8` implementations are used, but if not present, it defaults to `JSON` implementation. Both serializers have the advantage of being able to serialize `Map`, `Set`, `undefined`, `NaN`, etc, although the JSON one does it through a replacer/reviver.
## Install
```sh
$ yarn add jest-serializer
```
## API
Three kinds of API groups are exposed:
### In-memory serialization: `serialize` and `deserialize`
This set of functions take or return a `Buffer`. All the process happens in memory. This is useful when willing to transfer over HTTP, TCP or via UNIX pipes.
```javascript
import {serialize, deserialize} from 'jest-serializer';
const myObject = {
foo: 'bar',
baz: [0, true, '2', [], {}],
};
const buffer = serialize(myObject);
const myCopyObject = deserialize(buffer);
```
### Synchronous persistent filesystem: `readFileSync` and `writeFileSync`
This set of functions allow to send to disk a serialization result and retrieve it back, in a synchronous way. It mimics the `fs` API so it looks familiar.
```javascript
import {readFileSync, writeFileSync} from 'jest-serializer';
const myObject = {
foo: 'bar',
baz: [0, true, '2', [], {}],
};
const myFile = '/tmp/obj';
writeFileSync(myFile, myObject);
const myCopyObject = readFileSync(myFile);
```

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference path="../v8.d.ts" />
/// <reference types="node" />
declare type Path = string;
export declare function deserialize(buffer: Buffer): any;
export declare function serialize(content: unknown): Buffer;
export declare function readFileSync(filePath: Path): any;
export declare function writeFileSync(filePath: Path, content: any): void;
declare const _default: {
deserialize: typeof deserialize;
readFileSync: typeof readFileSync;
serialize: typeof serialize;
writeFileSync: typeof writeFileSync;
};
export default _default;
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;;AAOH,aAAK,IAAI,GAAG,MAAM,CAAC;AAuGnB,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,CAI/C;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAIlD;AAID,wBAAgB,YAAY,CAAC,QAAQ,EAAE,IAAI,GAAG,GAAG,CAIhD;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,QAIzD;;;;;;;AAED,wBAKE"}

View File

@ -0,0 +1,206 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.deserialize = deserialize;
exports.serialize = serialize;
exports.readFileSync = readFileSync;
exports.writeFileSync = writeFileSync;
exports.default = void 0;
function _fs() {
const data = _interopRequireDefault(require('fs'));
_fs = function _fs() {
return data;
};
return data;
}
function _v() {
const data = _interopRequireDefault(require('v8'));
_v = function _v() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// TODO: Remove this
/// <reference path="../v8.d.ts" />
// JSON and V8 serializers are both stable when it comes to compatibility. The
// current JSON specification is well defined in RFC 8259, and V8 ensures that
// the versions are compatible by encoding the serialization version in the own
// generated buffer.
const JS_TYPE = '__$t__';
const JS_VALUE = '__$v__';
const JS_VF = '__$f__';
function replacer(_key, value) {
// NaN cannot be in a switch statement, because NaN !== NaN.
if (Number.isNaN(value)) {
return {
[JS_TYPE]: 'n'
};
}
switch (value) {
case undefined:
return {
[JS_TYPE]: 'u'
};
case +Infinity:
return {
[JS_TYPE]: '+'
};
case -Infinity:
return {
[JS_TYPE]: '-'
};
}
switch (value && value.constructor) {
case Date:
return {
[JS_TYPE]: 'd',
[JS_VALUE]: value.getTime()
};
case RegExp:
return {
[JS_TYPE]: 'r',
[JS_VALUE]: value.source,
[JS_VF]: value.flags
};
case Set:
return {
[JS_TYPE]: 's',
[JS_VALUE]: Array.from(value)
};
case Map:
return {
[JS_TYPE]: 'm',
[JS_VALUE]: Array.from(value)
};
case Buffer:
return {
[JS_TYPE]: 'b',
[JS_VALUE]: value.toString('latin1')
};
}
return value;
}
function reviver(_key, value) {
if (!value || (typeof value !== 'object' && !value.hasOwnProperty(JS_TYPE))) {
return value;
}
switch (value[JS_TYPE]) {
case 'u':
return undefined;
case 'n':
return NaN;
case '+':
return +Infinity;
case '-':
return -Infinity;
case 'd':
return new Date(value[JS_VALUE]);
case 'r':
return new RegExp(value[JS_VALUE], value[JS_VF]);
case 's':
return new Set(value[JS_VALUE]);
case 'm':
return new Map(value[JS_VALUE]);
case 'b':
return Buffer.from(value[JS_VALUE], 'latin1');
}
return value;
}
function jsonStringify(content) {
// Not pretty, but the ES JSON spec says that "toJSON" will be called before
// getting into your replacer, so we have to remove them beforehand. See
// https://www.ecma-international.org/ecma-262/#sec-serializejsonproperty
// section 2.b for more information.
const dateToJSON = Date.prototype.toJSON;
const bufferToJSON = Buffer.prototype.toJSON;
/* eslint-disable no-extend-native */
try {
// @ts-ignore intentional removal of "toJSON" property.
Date.prototype.toJSON = undefined; // @ts-ignore intentional removal of "toJSON" property.
Buffer.prototype.toJSON = undefined;
return JSON.stringify(content, replacer);
} finally {
Date.prototype.toJSON = dateToJSON;
Buffer.prototype.toJSON = bufferToJSON;
}
/* eslint-enable no-extend-native */
}
function jsonParse(content) {
return JSON.parse(content, reviver);
} // In memory functions.
function deserialize(buffer) {
return _v().default.deserialize
? _v().default.deserialize(buffer)
: jsonParse(buffer.toString('utf8'));
}
function serialize(content) {
return _v().default.serialize
? _v().default.serialize(content)
: Buffer.from(jsonStringify(content));
} // Synchronous filesystem functions.
function readFileSync(filePath) {
return _v().default.deserialize
? _v().default.deserialize(_fs().default.readFileSync(filePath))
: jsonParse(_fs().default.readFileSync(filePath, 'utf8'));
}
function writeFileSync(filePath, content) {
return _v().default.serialize
? _fs().default.writeFileSync(filePath, _v().default.serialize(content))
: _fs().default.writeFileSync(filePath, jsonStringify(content), 'utf8');
}
var _default = {
deserialize,
readFileSync,
serialize,
writeFileSync
};
exports.default = _default;

View File

@ -0,0 +1,19 @@
{
"name": "jest-serializer",
"version": "24.9.0",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-serializer"
},
"engines": {
"node": ">= 6"
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"publishConfig": {
"access": "public"
},
"gitHead": "9ad0f4bc6b8bdd94989804226c28c9960d9da7d1"
}

View File

@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare module 'v8' {
function serialize(value: unknown): Buffer;
function deserialize(value: Buffer): unknown;
}

15
node_modules/metro-cache/node_modules/rimraf/LICENSE generated vendored Normal file
View File

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

101
node_modules/metro-cache/node_modules/rimraf/README.md generated vendored Normal file
View File

@ -0,0 +1,101 @@
[![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies)
The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node.
Install with `npm install rimraf`, or just drop rimraf.js somewhere.
## API
`rimraf(f, [opts], callback)`
The first parameter will be interpreted as a globbing pattern for files. If you
want to disable globbing you can do so with `opts.disableGlob` (defaults to
`false`). This might be handy, for instance, if you have filenames that contain
globbing wildcard characters.
The callback will be called with an error if there is one. Certain
errors are handled for you:
* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of
`opts.maxBusyTries` times before giving up, adding 100ms of wait
between each attempt. The default `maxBusyTries` is 3.
* `ENOENT` - If the file doesn't exist, rimraf will return
successfully, since your desired outcome is already the case.
* `EMFILE` - Since `readdir` requires opening a file descriptor, it's
possible to hit `EMFILE` if too many file descriptors are in use.
In the sync case, there's nothing to be done for this. But in the
async case, rimraf will gradually back off with timeouts up to
`opts.emfileWait` ms, which defaults to 1000.
## options
* unlink, chmod, stat, lstat, rmdir, readdir,
unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync
In order to use a custom file system library, you can override
specific fs functions on the options object.
If any of these functions are present on the options object, then
the supplied function will be used instead of the default fs
method.
Sync methods are only relevant for `rimraf.sync()`, of course.
For example:
```javascript
var myCustomFS = require('some-custom-fs')
rimraf('some-thing', myCustomFS, callback)
```
* maxBusyTries
If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered
on Windows systems, then rimraf will retry with a linear backoff
wait of 100ms longer on each try. The default maxBusyTries is 3.
Only relevant for async usage.
* emfileWait
If an `EMFILE` error is encountered, then rimraf will retry
repeatedly with a linear backoff of 1ms longer on each try, until
the timeout counter hits this max. The default limit is 1000.
If you repeatedly encounter `EMFILE` errors, then consider using
[graceful-fs](http://npm.im/graceful-fs) in your program.
Only relevant for async usage.
* glob
Set to `false` to disable [glob](http://npm.im/glob) pattern
matching.
Set to an object to pass options to the glob module. The default
glob options are `{ nosort: true, silent: true }`.
Glob version 6 is used in this module.
Relevant for both sync and async usage.
* disableGlob
Set to any non-falsey value to disable globbing entirely.
(Equivalent to setting `glob: false`.)
## rimraf.sync
It can remove stuff synchronously, too. But that's not so good. Use
the async API. It's better.
## CLI
If installed with `npm install rimraf -g` it can be used as a global
command `rimraf <path> [<path> ...]` which is useful for cross platform support.
## mkdirp
If you need to create a directory recursively, check out
[mkdirp](https://github.com/substack/node-mkdirp).

50
node_modules/metro-cache/node_modules/rimraf/bin.js generated vendored Executable file
View File

@ -0,0 +1,50 @@
#!/usr/bin/env node
var rimraf = require('./')
var help = false
var dashdash = false
var noglob = false
var args = process.argv.slice(2).filter(function(arg) {
if (dashdash)
return !!arg
else if (arg === '--')
dashdash = true
else if (arg === '--no-glob' || arg === '-G')
noglob = true
else if (arg === '--glob' || arg === '-g')
noglob = false
else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/))
help = true
else
return !!arg
})
if (help || args.length === 0) {
// If they didn't ask for help, then this is not a "success"
var log = help ? console.log : console.error
log('Usage: rimraf <path> [<path> ...]')
log('')
log(' Deletes all files and folders at "path" recursively.')
log('')
log('Options:')
log('')
log(' -h, --help Display this usage info')
log(' -G, --no-glob Do not expand glob patterns in arguments')
log(' -g, --glob Expand glob patterns in arguments (default)')
process.exit(help ? 0 : 1)
} else
go(0)
function go (n) {
if (n >= args.length)
return
var options = {}
if (noglob)
options = { glob: false }
rimraf(args[n], options, function (er) {
if (er)
throw er
go(n+1)
})
}

View File

@ -0,0 +1,29 @@
{
"name": "rimraf",
"version": "2.7.1",
"main": "rimraf.js",
"description": "A deep deletion module for node (like `rm -rf`)",
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"license": "ISC",
"repository": "git://github.com/isaacs/rimraf.git",
"scripts": {
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags",
"test": "tap test/*.js"
},
"bin": "./bin.js",
"dependencies": {
"glob": "^7.1.3"
},
"files": [
"LICENSE",
"README.md",
"bin.js",
"rimraf.js"
],
"devDependencies": {
"mkdirp": "^0.5.1",
"tap": "^12.1.1"
}
}

372
node_modules/metro-cache/node_modules/rimraf/rimraf.js generated vendored Normal file
View File

@ -0,0 +1,372 @@
module.exports = rimraf
rimraf.sync = rimrafSync
var assert = require("assert")
var path = require("path")
var fs = require("fs")
var glob = undefined
try {
glob = require("glob")
} catch (_err) {
// treat glob as optional.
}
var _0666 = parseInt('666', 8)
var defaultGlobOpts = {
nosort: true,
silent: true
}
// for EMFILE handling
var timeout = 0
var isWindows = (process.platform === "win32")
function defaults (options) {
var methods = [
'unlink',
'chmod',
'stat',
'lstat',
'rmdir',
'readdir'
]
methods.forEach(function(m) {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
options.maxBusyTries = options.maxBusyTries || 3
options.emfileWait = options.emfileWait || 1000
if (options.glob === false) {
options.disableGlob = true
}
if (options.disableGlob !== true && glob === undefined) {
throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
}
options.disableGlob = options.disableGlob || false
options.glob = options.glob || defaultGlobOpts
}
function rimraf (p, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p, 'rimraf: missing path')
assert.equal(typeof p, 'string', 'rimraf: path should be a string')
assert.equal(typeof cb, 'function', 'rimraf: callback function required')
assert(options, 'rimraf: invalid options argument provided')
assert.equal(typeof options, 'object', 'rimraf: options should be object')
defaults(options)
var busyTries = 0
var errState = null
var n = 0
if (options.disableGlob || !glob.hasMagic(p))
return afterGlob(null, [p])
options.lstat(p, function (er, stat) {
if (!er)
return afterGlob(null, [p])
glob(p, options.glob, afterGlob)
})
function next (er) {
errState = errState || er
if (--n === 0)
cb(errState)
}
function afterGlob (er, results) {
if (er)
return cb(er)
n = results.length
if (n === 0)
return cb()
results.forEach(function (p) {
rimraf_(p, options, function CB (er) {
if (er) {
if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
busyTries < options.maxBusyTries) {
busyTries ++
var time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(function () {
rimraf_(p, options, CB)
}, time)
}
// this one won't happen if graceful-fs is used.
if (er.code === "EMFILE" && timeout < options.emfileWait) {
return setTimeout(function () {
rimraf_(p, options, CB)
}, timeout ++)
}
// already gone
if (er.code === "ENOENT") er = null
}
timeout = 0
next(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, function (er, st) {
if (er && er.code === "ENOENT")
return cb(null)
// Windows can EPERM on stat. Life is suffering.
if (er && er.code === "EPERM" && isWindows)
fixWinEPERM(p, options, er, cb)
if (st && st.isDirectory())
return rmdir(p, options, er, cb)
options.unlink(p, function (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')
if (er)
assert(er instanceof Error)
options.chmod(p, _0666, function (er2) {
if (er2)
cb(er2.code === "ENOENT" ? null : er)
else
options.stat(p, function(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) {
assert(p)
assert(options)
if (er)
assert(er instanceof Error)
try {
options.chmodSync(p, _0666)
} catch (er2) {
if (er2.code === "ENOENT")
return
else
throw er
}
try {
var 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)
if (originalEr)
assert(originalEr instanceof Error)
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, function (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, function (er, files) {
if (er)
return cb(er)
var n = files.length
if (n === 0)
return options.rmdir(p, cb)
var errState
files.forEach(function (f) {
rimraf(path.join(p, f), options, function (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) {
options = options || {}
defaults(options)
assert(p, 'rimraf: missing path')
assert.equal(typeof p, 'string', 'rimraf: path should be a string')
assert(options, 'rimraf: missing options')
assert.equal(typeof options, 'object', 'rimraf: options should be object')
var results
if (options.disableGlob || !glob.hasMagic(p)) {
results = [p]
} else {
try {
options.lstatSync(p)
results = [p]
} catch (er) {
results = glob.sync(p, options.glob)
}
}
if (!results.length)
return
for (var i = 0; i < results.length; i++) {
var p = results[i]
try {
var 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
if (er.code === "EPERM")
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
if (er.code !== "EISDIR")
throw er
rmdirSync(p, options, er)
}
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "ENOTDIR")
throw originalEr
if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
rmkidsSync(p, options)
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(function (f) {
rimrafSync(path.join(p, f), options)
})
// 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.
var retries = isWindows ? 100 : 1
var i = 0
do {
var threw = true
try {
var ret = options.rmdirSync(p, options)
threw = false
return ret
} finally {
if (++i < retries && threw)
continue
}
} while (true)
}

24
node_modules/metro-cache/package.json generated vendored Normal file
View File

@ -0,0 +1,24 @@
{
"version": "0.59.0",
"name": "metro-cache",
"description": "<22> Cache layers for Metro",
"main": "src/index.js",
"repository": {
"type": "git",
"url": "git@github.com:facebook/metro.git"
},
"scripts": {
"prepare-release": "test -d build && rm -rf src.real && mv src src.real && mv build src",
"cleanup-release": "test ! -e build && mv src build && mv src.real src"
},
"dependencies": {
"jest-serializer": "^24.9.0",
"metro-core": "0.59.0",
"mkdirp": "^0.5.1",
"rimraf": "^2.5.4"
},
"devDependencies": {
"metro-memory-fs": "0.59.0"
},
"license": "MIT"
}

135
node_modules/metro-cache/src/Cache.js generated vendored Normal file
View File

@ -0,0 +1,135 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this,
args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
const _require = require("metro-core"),
Logger = _require.Logger;
/**
* Main cache class. Receives an array of cache instances, and sequentially
* traverses them to return a previously stored value. It also ensures setting
* the value in all instances.
*
* All get/set operations are logged via Metro's logger.
*/
class Cache {
constructor(stores) {
this._hits = new WeakMap();
this._stores = stores;
}
get(key) {
var _this = this;
return _asyncToGenerator(function*() {
const stores = _this._stores;
const length = stores.length;
for (let i = 0; i < length; i++) {
const store = stores[i];
const name = store.constructor.name + "::" + key.toString("hex");
let value = null;
const logStart = Logger.log(
Logger.createActionStartEntry({
action_name: "Cache get",
log_entry_label: name
})
);
try {
const valueOrPromise = store.get(key);
if (valueOrPromise && typeof valueOrPromise.then === "function") {
value = yield valueOrPromise;
} else {
value = valueOrPromise;
}
} finally {
Logger.log(Logger.createActionEndEntry(logStart));
Logger.log(
Logger.createEntry({
action_name: "Cache " + (value == null ? "miss" : "hit"),
log_entry_label: name
})
);
if (value != null) {
_this._hits.set(key, store);
return value;
}
}
}
return null;
})();
}
set(key, value) {
const stores = this._stores;
const stop = this._hits.get(key);
const length = stores.length;
const promises = [];
for (let i = 0; i < length && stores[i] !== stop; i++) {
const store = stores[i];
const name = store.constructor.name + "::" + key.toString("hex");
Logger.log(
Logger.createEntry({
action_name: "Cache set",
log_entry_label: name
})
);
promises.push(stores[i].set(key, value));
}
Promise.all(promises).catch(err => {
process.nextTick(() => {
throw err;
});
});
}
}
module.exports = Cache;

107
node_modules/metro-cache/src/Cache.js.flow generated vendored Normal file
View File

@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const {Logger} = require('metro-core');
import type {CacheStore} from 'metro-cache';
/**
* Main cache class. Receives an array of cache instances, and sequentially
* traverses them to return a previously stored value. It also ensures setting
* the value in all instances.
*
* All get/set operations are logged via Metro's logger.
*/
class Cache<T> {
_stores: $ReadOnlyArray<CacheStore<T>>;
_hits: WeakMap<Buffer, CacheStore<T>>;
constructor(stores: $ReadOnlyArray<CacheStore<T>>) {
this._hits = new WeakMap();
this._stores = stores;
}
async get(key: Buffer): Promise<?T> {
const stores = this._stores;
const length = stores.length;
for (let i = 0; i < length; i++) {
const store = stores[i];
const name = store.constructor.name + '::' + key.toString('hex');
let value = null;
const logStart = Logger.log(
Logger.createActionStartEntry({
action_name: 'Cache get',
log_entry_label: name,
}),
);
try {
const valueOrPromise = store.get(key);
if (valueOrPromise && typeof valueOrPromise.then === 'function') {
value = await valueOrPromise;
} else {
value = valueOrPromise;
}
} finally {
Logger.log(Logger.createActionEndEntry(logStart));
Logger.log(
Logger.createEntry({
action_name: 'Cache ' + (value == null ? 'miss' : 'hit'),
log_entry_label: name,
}),
);
if (value != null) {
this._hits.set(key, store);
return value;
}
}
}
return null;
}
set(key: Buffer, value: T): void {
const stores = this._stores;
const stop = this._hits.get(key);
const length = stores.length;
const promises = [];
for (let i = 0; i < length && stores[i] !== stop; i++) {
const store = stores[i];
const name = store.constructor.name + '::' + key.toString('hex');
Logger.log(
Logger.createEntry({
action_name: 'Cache set',
log_entry_label: name,
}),
);
promises.push(stores[i].set(key, value));
}
Promise.all(promises).catch(err => {
process.nextTick(() => {
throw err;
});
});
}
}
module.exports = Cache;

26
node_modules/metro-cache/src/index.js generated vendored Normal file
View File

@ -0,0 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const AutoCleanFileStore = require("./stores/AutoCleanFileStore");
const Cache = require("./Cache");
const FileStore = require("./stores/FileStore");
const HttpStore = require("./stores/HttpStore");
const stableHash = require("./stableHash");
module.exports.AutoCleanFileStore = AutoCleanFileStore;
module.exports.Cache = Cache;
module.exports.FileStore = FileStore;
module.exports.HttpStore = HttpStore;
module.exports.stableHash = stableHash;

29
node_modules/metro-cache/src/index.js.flow generated vendored Normal file
View File

@ -0,0 +1,29 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const AutoCleanFileStore = require('./stores/AutoCleanFileStore');
const Cache = require('./Cache');
const FileStore = require('./stores/FileStore');
const HttpStore = require('./stores/HttpStore');
const stableHash = require('./stableHash');
export type {Options as FileOptions} from './stores/FileStore';
export type {Options as HttpOptions} from './stores/HttpStore';
export type {CacheStore} from './types.flow';
module.exports.AutoCleanFileStore = AutoCleanFileStore;
module.exports.Cache = Cache;
module.exports.FileStore = FileStore;
module.exports.HttpStore = HttpStore;
module.exports.stableHash = stableHash;

28
node_modules/metro-cache/src/stableHash.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const canonicalize = require("metro-core/src/canonicalize");
const crypto = require("crypto");
function stableHash(value) {
return (
crypto
.createHash("md4")
/* $FlowFixMe(>=0.95.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.95 was deployed. To see the error, delete this
* comment and run Flow. */
.update(JSON.stringify(value, canonicalize))
.digest("buffer")
);
}
module.exports = stableHash;

28
node_modules/metro-cache/src/stableHash.js.flow generated vendored Normal file
View File

@ -0,0 +1,28 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const canonicalize = require('metro-core/src/canonicalize');
const crypto = require('crypto');
function stableHash(value: mixed): Buffer {
return (
crypto
.createHash('md4')
/* $FlowFixMe(>=0.95.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.95 was deployed. To see the error, delete this
* comment and run Flow. */
.update(JSON.stringify(value, canonicalize))
.digest('buffer')
);
}
module.exports = stableHash;

View File

@ -0,0 +1,90 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*
*/
"use strict";
const FileStore = require("./FileStore");
const fs = require("fs");
const path = require("path");
// List all files in a directory in Node.js recursively in a synchronous fashion
const walkSync = function(dir, filelist) {
const files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
const fullPath = path.join(dir, file);
const stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
filelist = walkSync(fullPath + path.sep, filelist);
} else {
filelist.push({
path: fullPath,
stats
});
}
});
return filelist;
};
function get(property, defaultValue) {
if (property == null) {
return defaultValue;
}
return property;
}
/**
* A FileStore that cleans itself up in a given interval
*/
class AutoCleanFileStore extends FileStore {
constructor(opts) {
super({
root: opts.root
});
this._intervalMs = get(opts.intervalMs, 10 * 60 * 1000); // 10 minutes
this._cleanupThresholdMs = get(
opts.cleanupThresholdMs,
3 * 24 * 60 * 60 * 1000 // 3 days
);
this._scheduleCleanup();
}
_scheduleCleanup() {
setTimeout(this._doCleanup.bind(this), this._intervalMs);
}
_doCleanup() {
const files = walkSync(this._root, []);
let warned = false;
files.forEach(file => {
if (file.stats.mtimeMs < Date.now() - this._cleanupThresholdMs) {
try {
fs.unlinkSync(file.path);
} catch (e) {
if (!warned) {
console.warn(
"Problem cleaning up cache for " + file.path + ": " + e.message
);
warned = true;
}
}
}
});
this._scheduleCleanup();
}
}
module.exports = AutoCleanFileStore;

View File

@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const FileStore = require('./FileStore');
const fs = require('fs');
const path = require('path');
import type {Options} from './FileStore';
type CleanOptions = {
...Options,
intervalMs?: number,
cleanupThresholdMs?: number,
...
};
type FileList = {
path: string,
stats: fs.Stats,
...
};
// List all files in a directory in Node.js recursively in a synchronous fashion
const walkSync = function(
dir: string,
filelist: Array<FileList>,
): Array<FileList> {
const files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
const fullPath = path.join(dir, file);
const stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
filelist = walkSync(fullPath + path.sep, filelist);
} else {
filelist.push({path: fullPath, stats});
}
});
return filelist;
};
function get<T>(property: ?T, defaultValue: T): T {
if (property == null) {
return defaultValue;
}
return property;
}
/**
* A FileStore that cleans itself up in a given interval
*/
class AutoCleanFileStore<T> extends FileStore<T> {
_intervalMs: number;
_cleanupThresholdMs: number;
_root: string;
constructor(opts: CleanOptions) {
super({root: opts.root});
this._intervalMs = get(opts.intervalMs, 10 * 60 * 1000); // 10 minutes
this._cleanupThresholdMs = get(
opts.cleanupThresholdMs,
3 * 24 * 60 * 60 * 1000, // 3 days
);
this._scheduleCleanup();
}
_scheduleCleanup() {
setTimeout(this._doCleanup.bind(this), this._intervalMs);
}
_doCleanup() {
const files = walkSync(this._root, []);
let warned = false;
files.forEach(file => {
if (file.stats.mtimeMs < Date.now() - this._cleanupThresholdMs) {
try {
fs.unlinkSync(file.path);
} catch (e) {
if (!warned) {
console.warn(
'Problem cleaning up cache for ' + file.path + ': ' + e.message,
);
warned = true;
}
}
}
});
this._scheduleCleanup();
}
}
module.exports = AutoCleanFileStore;

105
node_modules/metro-cache/src/stores/FileStore.js generated vendored Normal file
View File

@ -0,0 +1,105 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*
*/
"use strict";
const fs = require("fs");
const mkdirp = require("mkdirp");
const path = require("path");
const rimraf = require("rimraf");
const NULL_BYTE = 0x00;
const NULL_BYTE_BUFFER = Buffer.from([NULL_BYTE]);
class FileStore {
constructor(options) {
this._root = options.root;
this._createDirs();
}
get(key) {
try {
const data = fs.readFileSync(this._getFilePath(key));
if (data[0] === NULL_BYTE) {
return data.slice(1);
} else {
return JSON.parse(data.toString("utf8"));
}
} catch (err) {
if (err.code === "ENOENT" || err instanceof SyntaxError) {
return null;
}
throw err;
}
}
set(key, value) {
const filePath = this._getFilePath(key);
try {
this._set(filePath, value);
} catch (err) {
if (err.code === "ENOENT") {
mkdirp.sync(path.dirname(filePath));
this._set(filePath, value);
} else {
throw err;
}
}
}
_set(filePath, value) {
if (value instanceof Buffer) {
const fd = fs.openSync(filePath, "w");
fs.writeSync(fd, NULL_BYTE_BUFFER);
fs.writeSync(fd, value);
fs.closeSync(fd);
} else {
/* $FlowFixMe(>=0.95.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.95 was deployed. To see the error, delete
* this comment and run Flow. */
fs.writeFileSync(filePath, JSON.stringify(value));
}
}
clear() {
this._removeDirs();
this._createDirs();
}
_getFilePath(key) {
return path.join(
this._root,
key.slice(0, 1).toString("hex"),
key.slice(1).toString("hex")
);
}
_createDirs() {
for (let i = 0; i < 256; i++) {
mkdirp.sync(path.join(this._root, ("0" + i.toString(16)).slice(-2)));
}
}
_removeDirs() {
for (let i = 0; i < 256; i++) {
rimraf.sync(path.join(this._root, ("0" + i.toString(16)).slice(-2)));
}
}
}
module.exports = FileStore;

107
node_modules/metro-cache/src/stores/FileStore.js.flow generated vendored Normal file
View File

@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');
const rimraf = require('rimraf');
const NULL_BYTE = 0x00;
const NULL_BYTE_BUFFER = Buffer.from([NULL_BYTE]);
export type Options = {|
root: string,
|};
class FileStore<T> {
_root: string;
constructor(options: Options) {
this._root = options.root;
this._createDirs();
}
get(key: Buffer): ?T {
try {
const data = fs.readFileSync(this._getFilePath(key));
if (data[0] === NULL_BYTE) {
return (data.slice(1): any);
} else {
return JSON.parse(data.toString('utf8'));
}
} catch (err) {
if (err.code === 'ENOENT' || err instanceof SyntaxError) {
return null;
}
throw err;
}
}
set(key: Buffer, value: T): void {
const filePath = this._getFilePath(key);
try {
this._set(filePath, value);
} catch (err) {
if (err.code === 'ENOENT') {
mkdirp.sync(path.dirname(filePath));
this._set(filePath, value);
} else {
throw err;
}
}
}
_set(filePath: string, value: T): void {
if (value instanceof Buffer) {
const fd = fs.openSync(filePath, 'w');
fs.writeSync(fd, NULL_BYTE_BUFFER);
fs.writeSync(fd, value);
fs.closeSync(fd);
} else {
/* $FlowFixMe(>=0.95.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.95 was deployed. To see the error, delete
* this comment and run Flow. */
fs.writeFileSync(filePath, JSON.stringify(value));
}
}
clear() {
this._removeDirs();
this._createDirs();
}
_getFilePath(key: Buffer): string {
return path.join(
this._root,
key.slice(0, 1).toString('hex'),
key.slice(1).toString('hex'),
);
}
_createDirs() {
for (let i = 0; i < 256; i++) {
mkdirp.sync(path.join(this._root, ('0' + i.toString(16)).slice(-2)));
}
}
_removeDirs() {
for (let i = 0; i < 256; i++) {
rimraf.sync(path.join(this._root, ('0' + i.toString(16)).slice(-2)));
}
}
}
module.exports = FileStore;

19
node_modules/metro-cache/src/stores/HttpError.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* strict
*/
"use strict";
class HttpError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
module.exports = HttpError;

23
node_modules/metro-cache/src/stores/HttpError.js.flow generated vendored Normal file
View File

@ -0,0 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict
*/
'use strict';
class HttpError extends Error {
code: number;
constructor(message: string, code: number) {
super(message);
this.code = code;
}
}
module.exports = HttpError;

188
node_modules/metro-cache/src/stores/HttpStore.js generated vendored Normal file
View File

@ -0,0 +1,188 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*
*/
"use strict";
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const HttpError = require("./HttpError");
const NetworkError = require("./NetworkError");
const http = require("http");
const https = require("https");
const url = require("url");
const zlib = require("zlib");
const ZLIB_OPTIONS = {
level: 9
};
const NULL_BYTE = 0x00;
const NULL_BYTE_BUFFER = Buffer.from([NULL_BYTE]);
class HttpStore {
constructor(options) {
const uri = url.parse(options.endpoint);
const module = uri.protocol === "http:" ? http : https;
const agentConfig = {
family: options.family,
keepAlive: true,
keepAliveMsecs: options.timeout || 5000,
maxSockets: 64,
maxFreeSockets: 64
};
if (options.key != null) {
// $FlowFixMe `key` is missing in the Flow definition
agentConfig.key = options.key;
}
if (options.cert != null) {
// $FlowFixMe `cert` is missing in the Flow definition
agentConfig.cert = options.cert;
}
if (options.ca != null) {
// $FlowFixMe `ca` is missing in the Flow definition
agentConfig.ca = options.ca;
}
if (!uri.hostname || !uri.pathname) {
throw new TypeError("Invalid endpoint: " + options.endpoint);
}
this._module = module;
this._timeout = options.timeout || 5000;
this._host = uri.hostname;
this._path = uri.pathname;
this._port = +uri.port;
this._getAgent = new module.Agent(agentConfig);
this._setAgent = new module.Agent(agentConfig);
}
get(key) {
return new Promise((resolve, reject) => {
const options = {
agent: this._getAgent,
host: this._host,
method: "GET",
path: this._path + "/" + key.toString("hex"),
port: this._port,
timeout: this._timeout
};
/* $FlowFixMe(>=0.101.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.101 was deployed. To see the error, delete
* this comment and run Flow. */
const req = this._module.request(options, res => {
const code = res.statusCode;
const data = [];
if (code === 404) {
res.resume();
resolve(null);
return;
} else if (code !== 200) {
res.resume();
reject(new HttpError("HTTP error: " + code, code));
return;
}
const gunzipped = res.pipe(zlib.createGunzip());
gunzipped.on("data", chunk => {
data.push(chunk);
});
gunzipped.on("error", err => {
reject(err);
});
gunzipped.on("end", () => {
try {
const buffer = Buffer.concat(data);
if (buffer.length > 0 && buffer[0] === NULL_BYTE) {
resolve(buffer.slice(1));
} else {
resolve(JSON.parse(buffer.toString("utf8")));
}
} catch (err) {
reject(err);
}
});
res.on("error", err => gunzipped.emit("error", err));
});
req.on("error", err => {
reject(new NetworkError(err.message, err.code));
});
req.end();
});
}
set(key, value) {
return new Promise((resolve, reject) => {
const gzip = zlib.createGzip(ZLIB_OPTIONS);
const options = {
agent: this._setAgent,
host: this._host,
method: "PUT",
path: this._path + "/" + key.toString("hex"),
port: this._port,
timeout: this._timeout
};
/* $FlowFixMe(>=0.101.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.101 was deployed. To see the error, delete
* this comment and run Flow. */
const req = this._module.request(options, res => {
res.on("error", err => {
reject(err);
});
res.on("end", () => {
resolve();
}); // Consume all the data from the response without processing it.
res.resume();
});
gzip.pipe(req);
if (value instanceof Buffer) {
gzip.write(NULL_BYTE_BUFFER);
gzip.end(value);
} else {
gzip.end(JSON.stringify(value) || "null");
}
});
}
clear() {
// Not implemented.
}
}
_defineProperty(HttpStore, "HttpError", HttpError);
_defineProperty(HttpStore, "NetworkError", NetworkError);
module.exports = HttpStore;

206
node_modules/metro-cache/src/stores/HttpStore.js.flow generated vendored Normal file
View File

@ -0,0 +1,206 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const HttpError = require('./HttpError');
const NetworkError = require('./NetworkError');
const http = require('http');
const https = require('https');
const url = require('url');
const zlib = require('zlib');
import type {Agent as HttpAgent} from 'http';
import type {Agent as HttpsAgent} from 'https';
export type Options = {|
endpoint: string,
family?: 4 | 6,
timeout?: number,
key?: string | $ReadOnlyArray<string> | Buffer | $ReadOnlyArray<Buffer>,
cert?: string | $ReadOnlyArray<string> | Buffer | $ReadOnlyArray<Buffer>,
ca?: string | $ReadOnlyArray<string> | Buffer | $ReadOnlyArray<Buffer>,
|};
const ZLIB_OPTIONS = {
level: 9,
};
const NULL_BYTE = 0x00;
const NULL_BYTE_BUFFER = Buffer.from([NULL_BYTE]);
class HttpStore<T> {
static HttpError: typeof HttpError = HttpError;
static NetworkError: typeof NetworkError = NetworkError;
_module: typeof http | typeof https;
_timeout: number;
_host: string;
_port: number;
_path: string;
_getAgent: HttpAgent | HttpsAgent;
_setAgent: HttpAgent | HttpsAgent;
constructor(options: Options) {
const uri = url.parse(options.endpoint);
const module = uri.protocol === 'http:' ? http : https;
const agentConfig: http$agentOptions = {
family: options.family,
keepAlive: true,
keepAliveMsecs: options.timeout || 5000,
maxSockets: 64,
maxFreeSockets: 64,
};
if (options.key != null) {
// $FlowFixMe `key` is missing in the Flow definition
agentConfig.key = options.key;
}
if (options.cert != null) {
// $FlowFixMe `cert` is missing in the Flow definition
agentConfig.cert = options.cert;
}
if (options.ca != null) {
// $FlowFixMe `ca` is missing in the Flow definition
agentConfig.ca = options.ca;
}
if (!uri.hostname || !uri.pathname) {
throw new TypeError('Invalid endpoint: ' + options.endpoint);
}
this._module = module;
this._timeout = options.timeout || 5000;
this._host = uri.hostname;
this._path = uri.pathname;
this._port = +uri.port;
this._getAgent = new module.Agent(agentConfig);
this._setAgent = new module.Agent(agentConfig);
}
get(key: Buffer): Promise<?T> {
return new Promise((resolve, reject) => {
const options = {
agent: this._getAgent,
host: this._host,
method: 'GET',
path: this._path + '/' + key.toString('hex'),
port: this._port,
timeout: this._timeout,
};
/* $FlowFixMe(>=0.101.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.101 was deployed. To see the error, delete
* this comment and run Flow. */
const req = this._module.request(options, res => {
const code = res.statusCode;
const data = [];
if (code === 404) {
res.resume();
resolve(null);
return;
} else if (code !== 200) {
res.resume();
reject(new HttpError('HTTP error: ' + code, code));
return;
}
const gunzipped = res.pipe(zlib.createGunzip());
gunzipped.on('data', chunk => {
data.push(chunk);
});
gunzipped.on('error', err => {
reject(err);
});
gunzipped.on('end', () => {
try {
const buffer = Buffer.concat(data);
if (buffer.length > 0 && buffer[0] === NULL_BYTE) {
resolve((buffer.slice(1): any));
} else {
resolve(JSON.parse(buffer.toString('utf8')));
}
} catch (err) {
reject(err);
}
});
res.on('error', err => gunzipped.emit('error', err));
});
req.on('error', err => {
reject(new NetworkError(err.message, err.code));
});
req.end();
});
}
set(key: Buffer, value: T): Promise<void> {
return new Promise((resolve, reject) => {
const gzip = zlib.createGzip(ZLIB_OPTIONS);
const options = {
agent: this._setAgent,
host: this._host,
method: 'PUT',
path: this._path + '/' + key.toString('hex'),
port: this._port,
timeout: this._timeout,
};
/* $FlowFixMe(>=0.101.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.101 was deployed. To see the error, delete
* this comment and run Flow. */
const req = this._module.request(options, res => {
res.on('error', err => {
reject(err);
});
res.on('end', () => {
resolve();
});
// Consume all the data from the response without processing it.
res.resume();
});
gzip.pipe(req);
if (value instanceof Buffer) {
gzip.write(NULL_BYTE_BUFFER);
gzip.end(value);
} else {
gzip.end(JSON.stringify(value) || 'null');
}
});
}
clear() {
// Not implemented.
}
}
module.exports = HttpStore;

19
node_modules/metro-cache/src/stores/NetworkError.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* strict
*/
"use strict";
class NetworkError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
module.exports = NetworkError;

View File

@ -0,0 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict
*/
'use strict';
class NetworkError extends Error {
code: string;
constructor(message: string, code: string) {
super(message);
this.code = code;
}
}
module.exports = NetworkError;

10
node_modules/metro-cache/src/types.flow.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";

18
node_modules/metro-cache/src/types.flow.js.flow generated vendored Normal file
View File

@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
export type CacheStore<T> = {
get(key: Buffer): ?T | Promise<?T>,
set(key: Buffer, value: T): void | Promise<void>,
clear(): void | Promise<void>,
...
};