진주성

add .env and helper modified, finished file

Showing 141 changed files with 4721 additions and 9 deletions
TOKEN = sGB5EZq14+Lu4sc6Gt6NJ1Sx/rDtE1BsTyfZeNX42XVVjcgX1kk6/Uj1H40IQ1X3y8MzJLvKGifhioNCJLWQkWH2i95EtNDQyGn7Iqu6MnQRE7pg/z7klGgswS9974s0EKX90FcCfAIndNSYAG+d5gdB04t89/1O/w1cDnyilFU=
domain = 2016100990.oss2021.tk
var express = require('express');
const path = require('path');
const request = require('request');
require("dotenv").config({ path: path.resolve(__dirname, "../.env") });
//console.log(path)
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const PUSH_TARGET_URL = 'https://api.line.me/v2/bot/message/push'
const TOKEN = "OVIxKODBqM8Pn2dpFtFeSLsDbBvApfTu88rh8wFGOzfvgvPjmBH0A4XKii97VxIDO9shYyTix4qGq32vwvL895Rbss5VSVEiU/XG5lOdyTLgECkSQKOdObSetZwcVHbGmzZJ+0Cz5vZrB5KuImOwrwdB04t89/1O/w1cDnyilFU="
const TOKEN = process.env.TOKEN
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "2017103989.oss2021.tk"
const domain = process.env.domain
const sslport = 23023;
const bodyParser = require('body-parser');
var app = express();
......@@ -240,7 +242,7 @@ function printhelp(replyToken, message){
"messages":[
{
"type":"text",
"text":"사용자 : 주가 도움말\n챗봇: 종목명을 알려주세요.\n사용자: 종목명 입력 (ex 삼성전자)\n챗봇 : 현재가 거래량 전일대비 수익률"
"text":"'주가' 라고 입력하고 종목명을 입력해주세요. \n 현재가, 거래량, 전일대비 상승/하락률을 알려드릴게요!"
}
]
}
......@@ -261,7 +263,7 @@ function printhelp(replyToken, message){
"messages":[
{
"type":"text",
"text":"사용자 : 비중 추천\n챗봇 : 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자: 종목명 입력\n챗봇: 시작할 날짜를 입력해주세요\n사용자 : 종목명 입력 (ex 삼성전자, LG전자 ...)\n챗봇: 전략을 선택해주세요. (gmv, ms , rp)\n사용자: gmv, ms, rp 중 입력\n챗봇 : 케이스에 맞게 함수 실행 후 비중 출력"
"text":"'비중 추천'이라고 입력해주세요. \n 포트폴리오에 넣을 종목과 전략, 시작 날짜를 선택하면 비중을 추천해줄게요!"
}
]
}
......@@ -282,7 +284,7 @@ function printhelp(replyToken, message){
"messages":[
{
"type":"text",
"text":"사용자 : 백테스트\n챗봇: 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자: 종목명 입력\n챗봇: 시작할 날짜를 입력해주세요\n사용자: 입력\n챗봇: 전략을 선택해주세요 (gmv, ms , rp)\n사용자: gmv,ms,rp 중 입력\n챗봇: 함수 실행 후 그래프 출력"
"text":" '백테스트' 라고 입력해주세요. \n 포트폴리오에 넣을 종목과 전략, 시작 날짜를 선택하면 포트폴리오 수익률을 보여줄게요!"
}
]
}
......@@ -427,8 +429,8 @@ function optimizer(userid, sdate) {
},
{
"type":"image",
"originalContentUrl": "https://2017103989.oss2021.tk:23023/simages/test.png",
"previewImageUrl": "https://2017103989.oss2021.tk:23023/simages/test.png"
"originalContentUrl": "https://" + domain+ ":23023/simages/test.png",
"previewImageUrl": "https://" + domain+ ":23023/simages/test.png"
}
]
}
......
......@@ -37,7 +37,7 @@ def basicinform(input):
ror = round(ror, 4)
ror = ror * 100
value = ''
value = "1현재가: " + str(price) + "원\n거래: " + str(volume) + "건\n전일대비: " + str(ror) + "%"
value = "1현재가: " + str(price) + "원\n거래: " + str(volume) + "건\n전일대비: " + str(ror) + "%"
# value = {
# "현재가": price,
# "거래랑": volume,
......
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [10.0.0](https://github.com/motdotla/dotenv/compare/v9.0.2...v10.0.0) (2021-05-20)
### Added
- Add generic support to parse function
- Allow for import "dotenv/config.js"
- Add support to resolve home directory in path via ~
## [9.0.2](https://github.com/motdotla/dotenv/compare/v9.0.1...v9.0.2) (2021-05-10)
### Changed
- Support windows newlines with debug mode
## [9.0.1](https://github.com/motdotla/dotenv/compare/v9.0.0...v9.0.1) (2021-05-08)
### Changed
- Updates to README
## [9.0.0](https://github.com/motdotla/dotenv/compare/v8.6.0...v9.0.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8
## [8.6.0](https://github.com/motdotla/dotenv/compare/v8.5.1...v8.6.0) (2021-05-05)
### Added
- define package.json in exports
## [8.5.1](https://github.com/motdotla/dotenv/compare/v8.5.0...v8.5.1) (2021-05-05)
### Changed
- updated dev dependencies via npm audit
## [8.5.0](https://github.com/motdotla/dotenv/compare/v8.4.0...v8.5.0) (2021-05-05)
### Added
- allow for `import "dotenv/config"`
## [8.4.0](https://github.com/motdotla/dotenv/compare/v8.3.0...v8.4.0) (2021-05-05)
### Changed
- point to exact types file to work with VS Code
## [8.3.0](https://github.com/motdotla/dotenv/compare/v8.2.0...v8.3.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8 (mistake to be released as minor bump. later bumped to 9.0.0. see above.)
## [8.2.0](https://github.com/motdotla/dotenv/compare/v8.1.0...v8.2.0) (2019-10-16)
### Added
- TypeScript types
## [8.1.0](https://github.com/motdotla/dotenv/compare/v8.0.0...v8.1.0) (2019-08-18)
### Changed
- _Breaking:_ drop support for Node v6 ([#392](https://github.com/motdotla/dotenv/issues/392))
# [8.0.0](https://github.com/motdotla/dotenv/compare/v7.0.0...v8.0.0) (2019-05-02)
### Changed
- _Breaking:_ drop support for Node v6 ([#302](https://github.com/motdotla/dotenv/issues/392))
## [7.0.0] - 2019-03-12
### Fixed
- Fix removing unbalanced quotes ([#376](https://github.com/motdotla/dotenv/pull/376))
### Removed
- Removed `load` alias for `config` for consistency throughout code and documentation.
## [6.2.0] - 2018-12-03
### Added
- Support preload configuration via environment variables ([#351](https://github.com/motdotla/dotenv/issues/351))
## [6.1.0] - 2018-10-08
### Added
- `debug` option for `config` and `parse` methods will turn on logging
## [6.0.0] - 2018-06-02
### Changed
- _Breaking:_ drop support for Node v4 ([#304](https://github.com/motdotla/dotenv/pull/304))
## [5.0.0] - 2018-01-29
### Added
- Testing against Node v8 and v9
- Documentation on trim behavior of values
- Documentation on how to use with `import`
### Changed
- _Breaking_: default `path` is now `path.resolve(process.cwd(), '.env')`
- _Breaking_: does not write over keys already in `process.env` if the key has a falsy value
- using `const` and `let` instead of `var`
### Removed
- Testing against Node v7
## [4.0.0] - 2016-12-23
### Changed
- Return Object with parsed content or error instead of false ([#165](https://github.com/motdotla/dotenv/pull/165)).
### Removed
- `verbose` option removed in favor of returning result.
## [3.0.0] - 2016-12-20
### Added
- `verbose` option will log any error messages. Off by default.
- parses email addresses correctly
- allow importing config method directly in ES6
### Changed
- Suppress error messages by default ([#154](https://github.com/motdotla/dotenv/pull/154))
- Ignoring more files for NPM to make package download smaller
### Fixed
- False positive test due to case-sensitive variable ([#124](https://github.com/motdotla/dotenv/pull/124))
### Removed
- `silent` option removed in favor of `verbose`
## [2.0.0] - 2016-01-20
### Added
- CHANGELOG to ["make it easier for users and contributors to see precisely what notable changes have been made between each release"](http://keepachangelog.com/). Linked to from README
- LICENSE to be more explicit about what was defined in `package.json`. Linked to from README
- Testing nodejs v4 on travis-ci
- added examples of how to use dotenv in different ways
- return parsed object on success rather than boolean true
### Changed
- README has shorter description not referencing ruby gem since we don't have or want feature parity
### Removed
- Variable expansion and escaping so environment variables are encouraged to be fully orthogonal
## [1.2.0] - 2015-06-20
### Added
- Preload hook to require dotenv without including it in your code
### Changed
- clarified license to be "BSD-2-Clause" in `package.json`
### Fixed
- retain spaces in string vars
## [1.1.0] - 2015-03-31
### Added
- Silent option to silence `console.log` when `.env` missing
## [1.0.0] - 2015-03-13
### Removed
- support for multiple `.env` files. should always use one `.env` file for the current environment
[7.0.0]: https://github.com/motdotla/dotenv/compare/v6.2.0...v7.0.0
[6.2.0]: https://github.com/motdotla/dotenv/compare/v6.1.0...v6.2.0
[6.1.0]: https://github.com/motdotla/dotenv/compare/v6.0.0...v6.1.0
[6.0.0]: https://github.com/motdotla/dotenv/compare/v5.0.0...v6.0.0
[5.0.0]: https://github.com/motdotla/dotenv/compare/v4.0.0...v5.0.0
[4.0.0]: https://github.com/motdotla/dotenv/compare/v3.0.0...v4.0.0
[3.0.0]: https://github.com/motdotla/dotenv/compare/v2.0.0...v3.0.0
[2.0.0]: https://github.com/motdotla/dotenv/compare/v1.2.0...v2.0.0
[1.2.0]: https://github.com/motdotla/dotenv/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/motdotla/dotenv/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/motdotla/dotenv/compare/v0.4.0...v1.0.0
Copyright (c) 2015, Scott Motte
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<p align="center">
<strong>Announcement 📣</strong><br/>From the makers that brought you Dotenv, introducing <a href="https://sync.dotenv.org">Dotenv Sync</a>.<br/>Sync your .env files between machines, environments, and team members.<br/><a href="https://sync.dotenv.org">Join the early access list. 🕶</a>
</p>
# dotenv
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" />
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](http://12factor.net/config) methodology.
[![BuildStatus](https://img.shields.io/travis/motdotla/dotenv/master.svg?style=flat-square)](https://travis-ci.org/motdotla/dotenv)
[![Build status](https://ci.appveyor.com/api/projects/status/github/motdotla/dotenv?svg=true)](https://ci.appveyor.com/project/motdotla/dotenv/branch/master)
[![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
[![Coverage Status](https://img.shields.io/coveralls/motdotla/dotenv/master.svg?style=flat-square)](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration)
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
## Install
```bash
# with npm
npm install dotenv
# or with Yarn
yarn add dotenv
```
## Usage
As early as possible in your application, require and configure dotenv.
```javascript
require('dotenv').config()
```
Create a `.env` file in the root directory of your project. Add
environment-specific variables on new lines in the form of `NAME=VALUE`.
For example:
```dosini
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
```
`process.env` now has the keys and values you defined in your `.env` file.
```javascript
const db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
```
### Preload
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#cli_r_require_module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using `import` instead of `require`.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
## Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
You can additionally, pass options to `config`.
### Options
#### Path
Default: `path.resolve(process.cwd(), '.env')`
You may specify a custom path if your file containing environment variables is located elsewhere.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
#### Encoding
Default: `utf8`
You may specify the encoding of your file containing environment variables.
```js
require('dotenv').config({ encoding: 'latin1' })
```
#### Debug
Default: `false`
You may turn on logging to help debug why certain keys or values are not being set as you expect.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
## Parse
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
### Options
#### Debug
Default: `false`
You may turn on logging to help debug why certain keys or values are not being set as you expect.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form
```
### Rules
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
## FAQ
### Should I commit my `.env` file?
No. We **strongly** recommend against committing your `.env` file to version
control. It should only include environment-specific values such as database
passwords or API keys. Your production database should have a different
password than your development database.
### Should I have multiple `.env` files?
No. We **strongly** recommend against having a "main" `.env` file and an "environment" `.env` file like `.env.test`. Your config should vary between deploys, and you should not be sharing values between environments.
> In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
>
> – [The Twelve-Factor App](http://12factor.net/config)
### What happens to environment variables that were already set?
We will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all `.env` configurations with a machine-specific environment, although it is not recommended.
If you want to override `process.env` you can do something like this:
```javascript
const fs = require('fs')
const dotenv = require('dotenv')
const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
for (const k in envConfig) {
process.env[k] = envConfig[k]
}
```
### Can I customize/write plugins for dotenv?
For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing
the parsed `.env` file. This gives you everything you need to continue
setting values on `process.env`. For example:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
### What about variable expansion?
Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
### How do I use dotenv with `import`?
ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`.
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code:
`errorReporter.js`:
```js
import { Client } from 'best-error-reporting-service'
export const client = new Client(process.env.BEST_API_KEY)
```
`index.js`:
```js
import dotenv from 'dotenv'
import errorReporter from './errorReporter'
dotenv.config()
errorReporter.client.report(new Error('faq example'))
```
`client` will not be configured correctly because it was constructed before `dotenv.config()` was executed. There are (at least) 3 ways to make this work.
1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Import `dotenv/config` instead of `dotenv` (_Note: you do not need to call `dotenv.config()` and must pass options via the command line or environment variables with this approach_)
3. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
## Contributing Guide
See [CONTRIBUTING.md](CONTRIBUTING.md)
## Change Log
See [CHANGELOG.md](CHANGELOG.md)
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
/* @flow */
(function () {
require('./lib/main').config(
Object.assign(
{},
require('./lib/env-options'),
require('./lib/cli-options')(process.argv)
)
)
})()
/* @flow */
const re = /^dotenv_config_(encoding|path|debug)=(.+)$/
module.exports = function optionMatcher (args /*: Array<string> */) {
return args.reduce(function (acc, cur) {
const matches = cur.match(re)
if (matches) {
acc[matches[1]] = matches[2]
}
return acc
}, {})
}
/* @flow */
// ../config.js accepts options via environment variables
const options = {}
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG
}
module.exports = options
/* @flow */
/*::
type DotenvParseOptions = {
debug?: boolean
}
// keys and values from src
type DotenvParseOutput = { [string]: string }
type DotenvConfigOptions = {
path?: string, // path to .env file
encoding?: string, // encoding of .env file
debug?: string // turn on logging for debugging purposes
}
type DotenvConfigOutput = {
parsed?: DotenvParseOutput,
error?: Error
}
*/
const fs = require('fs')
const path = require('path')
const os = require('os')
function log (message /*: string */) {
console.log(`[dotenv][DEBUG] ${message}`)
}
const NEWLINE = '\n'
const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
const RE_NEWLINES = /\\n/g
const NEWLINES_MATCH = /\r\n|\n|\r/
// Parses src into an Object
function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
const debug = Boolean(options && options.debug)
const obj = {}
// convert Buffers before splitting into lines and processing
src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(RE_INI_KEY_VAL)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
// default undefined or missing values to empty string
let val = (keyValueArr[2] || '')
const end = val.length - 1
const isDoubleQuoted = val[0] === '"' && val[end] === '"'
const isSingleQuoted = val[0] === "'" && val[end] === "'"
// if single or double quoted, remove quotes
if (isSingleQuoted || isDoubleQuoted) {
val = val.substring(1, end)
// if double quoted, expand newlines
if (isDoubleQuoted) {
val = val.replace(RE_NEWLINES, NEWLINE)
}
} else {
// remove surrounding whitespace
val = val.trim()
}
obj[key] = val
} else if (debug) {
log(`did not match key and value when parsing line ${idx + 1}: ${line}`)
}
})
return obj
}
function resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}
// Populates process.env from .env file
function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
let dotenvPath = path.resolve(process.cwd(), '.env')
let encoding /*: string */ = 'utf8'
let debug = false
if (options) {
if (options.path != null) {
dotenvPath = resolveHome(options.path)
}
if (options.encoding != null) {
encoding = options.encoding
}
if (options.debug != null) {
debug = true
}
}
try {
// specifying an encoding returns a string instead of a buffer
const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug })
Object.keys(parsed).forEach(function (key) {
if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
process.env[key] = parsed[key]
} else if (debug) {
log(`"${key}" is already defined in \`process.env\` and will not be overwritten`)
}
})
return { parsed }
} catch (e) {
return { error: e }
}
}
module.exports.config = config
module.exports.parse = parse
{
"_from": "dotenv",
"_id": "dotenv@10.0.0",
"_inBundle": false,
"_integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==",
"_location": "/dotenv",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "dotenv",
"name": "dotenv",
"escapedName": "dotenv",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
"_shasum": "3d4227b8fb95f81096cdd2b66653fb2c7085ba81",
"_spec": "dotenv",
"_where": "/home/ubuntu/stock_chatbot/server",
"bugs": {
"url": "https://github.com/motdotla/dotenv/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Loads environment variables from .env file",
"devDependencies": {
"decache": "^4.5.1",
"dtslint": "^0.9.8",
"flow-bin": "^0.109.0",
"sinon": "^7.5.0",
"standard": "^13.1.0",
"standard-markdown": "^5.1.0",
"standard-version": "^7.0.0",
"tap": "^14.7.0"
},
"engines": {
"node": ">=10"
},
"exports": {
".": "./lib/main.js",
"./config": "./config.js",
"./config.js": "./config.js",
"./package.json": "./package.json"
},
"homepage": "https://github.com/motdotla/dotenv#readme",
"keywords": [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
"license": "BSD-2-Clause",
"main": "lib/main.js",
"name": "dotenv",
"repository": {
"type": "git",
"url": "git://github.com/motdotla/dotenv.git"
},
"scripts": {
"dtslint": "dtslint types",
"flow": "flow",
"lint": "standard",
"postlint": "standard-markdown",
"prerelease": "npm test",
"pretest": "npm run lint && npm run dtslint",
"release": "standard-version",
"test": "tap tests/*.js --100"
},
"standard": {
"ignore": [
"flow-typed/"
]
},
"types": "types/index.d.ts",
"version": "10.0.0"
}
// TypeScript Version: 3.0
/// <reference types="node" />
export interface DotenvParseOptions {
/**
* You may turn on logging to help debug why certain keys or values are not being set as you expect.
*/
debug?: boolean;
}
export interface DotenvParseOutput {
[name: string]: string;
}
/**
* Parses a string or buffer in the .env file format into an object.
*
* @param src - contents to be parsed
* @param options - additional options
* @returns an object with keys and values based on `src`
*/
export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
src: string | Buffer,
options?: DotenvParseOptions
): T;
export interface DotenvConfigOptions {
/**
* You may specify a custom path if your file containing environment variables is located elsewhere.
*/
path?: string;
/**
* You may specify the encoding of your file containing environment variables.
*/
encoding?: string;
/**
* You may turn on logging to help debug why certain keys or values are not being set as you expect.
*/
debug?: boolean;
}
export interface DotenvConfigOutput {
error?: Error;
parsed?: DotenvParseOutput;
}
/**
* Loads `.env` file contents into {@link https://nodejs.org/api/process.html#process_process_env `process.env`}.
* Example: 'KEY=value' becomes { parsed: { KEY: 'value' } }
*
* @param options - controls behavior
* @returns an object with a `parsed` key if successful or `error` key if an error occurred
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/** @deprecated since v7.0.0 Use config instead. */
export const load: typeof config;
import { config, parse } from "dotenv";
const env = config();
const dbUrl: string | null =
env.error || !env.parsed ? null : env.parsed["BASIC"];
config({
path: ".env-example",
encoding: "utf8",
debug: true
});
const parsed = parse("NODE_ENV=production\nDB_HOST=a.b.c");
const dbHost: string = parsed["DB_HOST"];
const parsedFromBuffer = parse(new Buffer("JUSTICE=league\n"), {
debug: true
});
const justice: string = parsedFromBuffer["JUSTICE"];
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"dotenv": ["."]
}
}
}
{
"extends": "dtslint/dtslint.json",
"rules": {
"strict-export-declare-modifiers": false
}
}
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
[CHANGELOG.md]
indent_style = space
indent_size = 2
[*.json]
max_line_length = off
[Makefile]
max_line_length = off
{
"root": true,
"extends": "@ljharb",
"rules": {
"func-name-matching": 0,
"indent": [2, 4],
"max-nested-callbacks": [2, 3],
"max-params": [2, 3],
"max-statements": [2, 20],
"no-new-func": [1],
"strict": [0]
}
}
{
"es3": true,
"additionalRules": [],
"requireSemicolons": true,
"disallowMultipleSpaces": true,
"disallowIdentifierNames": [],
"requireCurlyBraces": {
"allExcept": [],
"keywords": ["if", "else", "for", "while", "do", "try", "catch"]
},
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
"disallowSpaceAfterKeywords": [],
"disallowSpaceBeforeComma": true,
"disallowSpaceAfterComma": false,
"disallowSpaceBeforeSemicolon": true,
"disallowNodeTypes": [
"DebuggerStatement",
"ForInStatement",
"LabeledStatement",
"SwitchCase",
"SwitchStatement",
"WithStatement"
],
"requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
"requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
"requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
"requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
"requireSpaceBetweenArguments": true,
"disallowSpacesInsideParentheses": true,
"disallowSpacesInsideArrayBrackets": true,
"disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
"disallowSpaceAfterObjectKeys": true,
"requireCommaBeforeLineBreak": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"requireSpaceAfterPrefixUnaryOperators": [],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"requireSpaceBeforePostfixUnaryOperators": [],
"disallowSpaceBeforeBinaryOperators": [],
"requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"disallowSpaceAfterBinaryOperators": [],
"disallowImplicitTypeConversion": ["binary", "string"],
"disallowKeywords": ["with", "eval"],
"requireKeywordsOnNewLine": [],
"disallowKeywordsOnNewLine": ["else"],
"requireLineFeedAtFileEnd": true,
"disallowTrailingWhitespace": true,
"disallowTrailingComma": true,
"excludeFiles": ["node_modules/**", "vendor/**"],
"disallowMultipleLineStrings": true,
"requireDotNotation": { "allExcept": ["keywords"] },
"requireParenthesesAroundIIFE": true,
"validateLineBreaks": "LF",
"validateQuoteMarks": {
"escape": true,
"mark": "'"
},
"disallowOperatorBeforeLineBreak": [],
"requireSpaceBeforeKeywords": [
"do",
"for",
"if",
"else",
"switch",
"case",
"try",
"catch",
"finally",
"while",
"with",
"return"
],
"validateAlignedFunctionParameters": {
"lineBreakAfterOpeningBraces": true,
"lineBreakBeforeClosingBraces": true
},
"requirePaddingNewLinesBeforeExport": true,
"validateNewlineAfterArrayElements": {
"maximum": 8
},
"requirePaddingNewLinesAfterUseStrict": true,
"disallowArrowFunctions": true,
"disallowMultiLineTernary": true,
"validateOrderInObjectKeys": "asc-insensitive",
"disallowIdenticalDestructuringNames": true,
"disallowNestedTernaries": { "maxLevel": 1 },
"requireSpaceAfterComma": { "allExcept": ["trailing"] },
"requireAlignedMultilineParams": false,
"requireSpacesInGenerator": {
"afterStar": true
},
"disallowSpacesInGenerator": {
"beforeStar": true
},
"disallowVar": false,
"requireArrayDestructuring": false,
"requireEnhancedObjectLiterals": false,
"requireObjectDestructuring": false,
"requireEarlyReturn": false,
"requireCapitalizedConstructorsNew": {
"allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
},
"requireImportAlphabetized": false,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"disallowSpacesInsideTemplateStringPlaceholders": true,
"disallowArrayDestructuringReturn": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"disallowUnusedVariables": true,
"requireSpacesInsideImportedObjectBraces": true,
"requireUseStrict": true
}
# gitignore
.DS_Store
.monitor
.*.swp
.nodemonignore
releases
*.log
*.err
fleet.json
public/browserify
bin/*.json
.bin
build
compile
.lock-wscript
coverage
node_modules
# Only apps should have lockfiles
npm-shrinkwrap.json
package-lock.json
yarn.lock
language: node_js
os:
- linux
node_js:
- "8.4"
- "7.10"
- "6.11"
- "5.12"
- "4.8"
- "iojs-v3.3"
- "iojs-v2.5"
- "iojs-v1.8"
- "0.12"
- "0.10"
- "0.8"
before_install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi'
- 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi'
install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
script:
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
- 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
- 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
sudo: false
env:
- TEST=true
matrix:
fast_finish: true
include:
- node_js: "node"
env: PRETEST=true
- node_js: "4"
env: COVERAGE=true
- node_js: "8.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v3.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v2.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "iojs-v1.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.4"
env: TEST=true ALLOW_FAILURE=true
allow_failures:
- os: osx
- env: TEST=true ALLOW_FAILURE=true
Copyright (c) 2013 Raynos.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# function-bind
<!--
[![build status][travis-svg]][travis-url]
[![NPM version][npm-badge-svg]][npm-url]
[![Coverage Status][5]][6]
[![gemnasium Dependency Status][7]][8]
[![Dependency status][deps-svg]][deps-url]
[![Dev Dependency status][dev-deps-svg]][dev-deps-url]
-->
<!-- [![browser support][11]][12] -->
Implementation of function.prototype.bind
## Example
I mainly do this for unit tests I run on phantomjs.
PhantomJS does not have Function.prototype.bind :(
```js
Function.prototype.bind = require("function-bind")
```
## Installation
`npm install function-bind`
## Contributors
- Raynos
## MIT Licenced
[travis-svg]: https://travis-ci.org/Raynos/function-bind.svg
[travis-url]: https://travis-ci.org/Raynos/function-bind
[npm-badge-svg]: https://badge.fury.io/js/function-bind.svg
[npm-url]: https://npmjs.org/package/function-bind
[5]: https://coveralls.io/repos/Raynos/function-bind/badge.png
[6]: https://coveralls.io/r/Raynos/function-bind
[7]: https://gemnasium.com/Raynos/function-bind.png
[8]: https://gemnasium.com/Raynos/function-bind
[deps-svg]: https://david-dm.org/Raynos/function-bind.svg
[deps-url]: https://david-dm.org/Raynos/function-bind
[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg
[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies
[11]: https://ci.testling.com/Raynos/function-bind.png
[12]: https://ci.testling.com/Raynos/function-bind
'use strict';
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
'use strict';
var implementation = require('./implementation');
module.exports = Function.prototype.bind || implementation;
{
"_from": "function-bind@^1.1.1",
"_id": "function-bind@1.1.1",
"_inBundle": false,
"_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
"_location": "/function-bind",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "function-bind@^1.1.1",
"name": "function-bind",
"escapedName": "function-bind",
"rawSpec": "^1.1.1",
"saveSpec": null,
"fetchSpec": "^1.1.1"
},
"_requiredBy": [
"/has"
],
"_resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d",
"_spec": "function-bind@^1.1.1",
"_where": "/home/ubuntu/stock_chatbot/server/node_modules/has",
"author": {
"name": "Raynos",
"email": "raynos2@gmail.com"
},
"bugs": {
"url": "https://github.com/Raynos/function-bind/issues",
"email": "raynos2@gmail.com"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Raynos"
},
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"dependencies": {},
"deprecated": false,
"description": "Implementation of Function.prototype.bind",
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"covert": "^1.1.0",
"eslint": "^4.5.0",
"jscs": "^3.0.7",
"tape": "^4.8.0"
},
"homepage": "https://github.com/Raynos/function-bind",
"keywords": [
"function",
"bind",
"shim",
"es5"
],
"license": "MIT",
"main": "index",
"name": "function-bind",
"repository": {
"type": "git",
"url": "git://github.com/Raynos/function-bind.git"
},
"scripts": {
"coverage": "covert test/*.js",
"eslint": "eslint *.js */*.js",
"jscs": "jscs *.js */*.js",
"lint": "npm run jscs && npm run eslint",
"posttest": "npm run coverage -- --quiet",
"pretest": "npm run lint",
"test": "npm run tests-only",
"tests-only": "node test"
},
"testling": {
"files": "test/index.js",
"browsers": [
"ie/8..latest",
"firefox/16..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "1.1.1"
}
{
"rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"max-statements-per-line": [2, { "max": 2 }],
"no-invalid-this": 0,
"no-magic-numbers": 0,
}
}
// jscs:disable requireUseStrict
var test = require('tape');
var functionBind = require('../implementation');
var getCurrentContext = function () { return this; };
test('functionBind is a function', function (t) {
t.equal(typeof functionBind, 'function');
t.end();
});
test('non-functions', function (t) {
var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g];
t.plan(nonFunctions.length);
for (var i = 0; i < nonFunctions.length; ++i) {
try { functionBind.call(nonFunctions[i]); } catch (ex) {
t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i]));
}
}
t.end();
});
test('without a context', function (t) {
t.test('binds properly', function (st) {
var args, context;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
})
};
namespace.func(1, 2, 3);
st.deepEqual(args, [1, 2, 3]);
st.equal(context, getCurrentContext.call());
st.end();
});
t.test('binds properly, and still supplies bound arguments', function (st) {
var args, context;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, undefined, 1, 2, 3)
};
namespace.func(4, 5, 6);
st.deepEqual(args, [1, 2, 3, 4, 5, 6]);
st.equal(context, getCurrentContext.call());
st.end();
});
t.test('returns properly', function (st) {
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, null)
};
var context = namespace.func(1, 2, 3);
st.equal(context, getCurrentContext.call(), 'returned context is namespaced context');
st.deepEqual(args, [1, 2, 3], 'passed arguments are correct');
st.end();
});
t.test('returns properly with bound arguments', function (st) {
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, null, 1, 2, 3)
};
var context = namespace.func(4, 5, 6);
st.equal(context, getCurrentContext.call(), 'returned context is namespaced context');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct');
st.end();
});
t.test('called as a constructor', function (st) {
var thunkify = function (value) {
return function () { return value; };
};
st.test('returns object value', function (sst) {
var expectedReturnValue = [1, 2, 3];
var Constructor = functionBind.call(thunkify(expectedReturnValue), null);
var result = new Constructor();
sst.equal(result, expectedReturnValue);
sst.end();
});
st.test('does not return primitive value', function (sst) {
var Constructor = functionBind.call(thunkify(42), null);
var result = new Constructor();
sst.notEqual(result, 42);
sst.end();
});
st.test('object from bound constructor is instance of original and bound constructor', function (sst) {
var A = function (x) {
this.name = x || 'A';
};
var B = functionBind.call(A, null, 'B');
var result = new B();
sst.ok(result instanceof B, 'result is instance of bound constructor');
sst.ok(result instanceof A, 'result is instance of original constructor');
sst.end();
});
st.end();
});
t.end();
});
test('with a context', function (t) {
t.test('with no bound arguments', function (st) {
var args, context;
var boundContext = {};
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, boundContext)
};
namespace.func(1, 2, 3);
st.equal(context, boundContext, 'binds a context properly');
st.deepEqual(args, [1, 2, 3], 'supplies passed arguments');
st.end();
});
t.test('with bound arguments', function (st) {
var args, context;
var boundContext = {};
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
context = this;
}, boundContext, 1, 2, 3)
};
namespace.func(4, 5, 6);
st.equal(context, boundContext, 'binds a context properly');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments');
st.end();
});
t.test('returns properly', function (st) {
var boundContext = {};
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, boundContext)
};
var context = namespace.func(1, 2, 3);
st.equal(context, boundContext, 'returned context is bound context');
st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context');
st.deepEqual(args, [1, 2, 3], 'passed arguments are correct');
st.end();
});
t.test('returns properly with bound arguments', function (st) {
var boundContext = {};
var args;
var namespace = {
func: functionBind.call(function () {
args = Array.prototype.slice.call(arguments);
return this;
}, boundContext, 1, 2, 3)
};
var context = namespace.func(4, 5, 6);
st.equal(context, boundContext, 'returned context is bound context');
st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context');
st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct');
st.end();
});
t.test('passes the correct arguments when called as a constructor', function (st) {
var expected = { name: 'Correct' };
var namespace = {
Func: functionBind.call(function (arg) {
return arg;
}, { name: 'Incorrect' })
};
var returned = new namespace.Func(expected);
st.equal(returned, expected, 'returns the right arg when called as a constructor');
st.end();
});
t.test('has the new instance\'s context when called as a constructor', function (st) {
var actualContext;
var expectedContext = { foo: 'bar' };
var namespace = {
Func: functionBind.call(function () {
actualContext = this;
}, expectedContext)
};
var result = new namespace.Func();
st.equal(result instanceof namespace.Func, true);
st.notEqual(actualContext, expectedContext);
st.end();
});
t.end();
});
test('bound function length', function (t) {
t.test('sets a correct length without thisArg', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; });
st.equal(subject.length, 3);
st.equal(subject(1, 2, 3), 6);
st.end();
});
t.test('sets a correct length with thisArg', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {});
st.equal(subject.length, 3);
st.equal(subject(1, 2, 3), 6);
st.end();
});
t.test('sets a correct length without thisArg and first argument', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1);
st.equal(subject.length, 2);
st.equal(subject(2, 3), 6);
st.end();
});
t.test('sets a correct length with thisArg and first argument', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1);
st.equal(subject.length, 2);
st.equal(subject(2, 3), 6);
st.end();
});
t.test('sets a correct length without thisArg and too many arguments', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4);
st.equal(subject.length, 0);
st.equal(subject(), 6);
st.end();
});
t.test('sets a correct length with thisArg and too many arguments', function (st) {
var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4);
st.equal(subject.length, 0);
st.equal(subject(), 6);
st.end();
});
});
Copyright (c) 2013 Thiago de Arruda
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.
# has
> Object.prototype.hasOwnProperty.call shortcut
## Installation
```sh
npm install --save has
```
## Usage
```js
var has = require('has');
has({}, 'hasOwnProperty'); // false
has(Object.prototype, 'hasOwnProperty'); // true
```
{
"_from": "has@^1.0.3",
"_id": "has@1.0.3",
"_inBundle": false,
"_integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"_location": "/has",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "has@^1.0.3",
"name": "has",
"escapedName": "has",
"rawSpec": "^1.0.3",
"saveSpec": null,
"fetchSpec": "^1.0.3"
},
"_requiredBy": [
"/is-core-module"
],
"_resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"_shasum": "722d7cbfc1f6aa8241f16dd814e011e1f41e8796",
"_spec": "has@^1.0.3",
"_where": "/home/ubuntu/stock_chatbot/server/node_modules/is-core-module",
"author": {
"name": "Thiago de Arruda",
"email": "tpadilha84@gmail.com"
},
"bugs": {
"url": "https://github.com/tarruda/has/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"dependencies": {
"function-bind": "^1.1.1"
},
"deprecated": false,
"description": "Object.prototype.hasOwnProperty.call shortcut",
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"eslint": "^4.19.1",
"tape": "^4.9.0"
},
"engines": {
"node": ">= 0.4.0"
},
"homepage": "https://github.com/tarruda/has",
"license": "MIT",
"licenses": [
{
"type": "MIT",
"url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT"
}
],
"main": "./src",
"name": "has",
"repository": {
"type": "git",
"url": "git://github.com/tarruda/has.git"
},
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "tape test"
},
"version": "1.0.3"
}
'use strict';
var bind = require('function-bind');
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
'use strict';
var test = require('tape');
var has = require('../');
test('has', function (t) {
t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"');
t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"');
t.end();
});
{
"extends": "@ljharb",
"root": true,
"rules": {
"func-style": 1,
"operator-linebreak": [2, "before"],
},
"overrides": [
{
"files": "test/**",
"rules": {
"global-require": 0,
"max-lines-per-function": 0,
"no-negated-condition": 0,
},
},
],
}
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"exclude": [
"coverage",
"test"
]
}
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v2.4.0](https://github.com/inspect-js/is-core-module/compare/v2.3.0...v2.4.0) - 2021-05-09
### Commits
- [readme] add actions and codecov badges [`82b7faa`](https://github.com/inspect-js/is-core-module/commit/82b7faa12b56dbe47fbea67e1a5b9e447027ba40)
- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`8096868`](https://github.com/inspect-js/is-core-module/commit/8096868c024a161ccd4d44110b136763e92eace8)
- [Dev Deps] update `eslint` [`6726824`](https://github.com/inspect-js/is-core-module/commit/67268249b88230018c510f6532a8046d7326346f)
- [New] add `diagnostics_channel` to node `^14.17` [`86c6563`](https://github.com/inspect-js/is-core-module/commit/86c65634201b8ff9b3e48a9a782594579c7f5c3c)
- [meta] fix prepublish script [`697a01e`](https://github.com/inspect-js/is-core-module/commit/697a01e3c9c0be074066520954f30fb28532ec57)
## [v2.3.0](https://github.com/inspect-js/is-core-module/compare/v2.2.0...v2.3.0) - 2021-04-24
### Commits
- [meta] do not publish github action workflow files [`060d4bb`](https://github.com/inspect-js/is-core-module/commit/060d4bb971a29451c19ff336eb56bee27f9fa95a)
- [New] add support for `node:` prefix, in node 16+ [`7341223`](https://github.com/inspect-js/is-core-module/commit/73412230a769f6e81c05eea50b6520cebf54ed2f)
- [actions] use `node/install` instead of `node/run`; use `codecov` action [`016269a`](https://github.com/inspect-js/is-core-module/commit/016269abae9f6657a5254adfbb813f09a05067f9)
- [patch] remove unneeded `.0` in version ranges [`cb466a6`](https://github.com/inspect-js/is-core-module/commit/cb466a6d89e52b8389e5c12715efcd550c41cea3)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`c9f9c39`](https://github.com/inspect-js/is-core-module/commit/c9f9c396ace60ef81906f98059c064e6452473ed)
- [actions] update workflows [`3ee4a89`](https://github.com/inspect-js/is-core-module/commit/3ee4a89fd5a02fccd43882d905448ea6a98e9a3c)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`dee4fed`](https://github.com/inspect-js/is-core-module/commit/dee4fed79690c1d43a22f7fa9426abebdc6d727f)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`7d046ba`](https://github.com/inspect-js/is-core-module/commit/7d046ba07ae8c9292e43652694ca808d7b309de8)
- [meta] use `prepublishOnly` script for npm 7+ [`149e677`](https://github.com/inspect-js/is-core-module/commit/149e6771a5ede6d097e71785b467a9c4b4977cc7)
- [readme] remove travis badge [`903b51d`](https://github.com/inspect-js/is-core-module/commit/903b51d6b69b98abeabfbc3695c345b02646f19c)
## [v2.2.0](https://github.com/inspect-js/is-core-module/compare/v2.1.0...v2.2.0) - 2020-11-26
### Commits
- [Tests] migrate tests to Github Actions [`c919f57`](https://github.com/inspect-js/is-core-module/commit/c919f573c0a92d10a0acad0b650b5aecb033d426)
- [patch] `core.json`: %s/ /\t/g [`db3f685`](https://github.com/inspect-js/is-core-module/commit/db3f68581f53e73cc09cd675955eb1bdd6a5a39b)
- [Tests] run `nyc` on all tests [`b2f925f`](https://github.com/inspect-js/is-core-module/commit/b2f925f8866f210ef441f39fcc8cc42692ab89b1)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`; add `safe-publish-latest` [`89f02a2`](https://github.com/inspect-js/is-core-module/commit/89f02a2b4162246dea303a6ee31bb9a550b05c72)
- [New] add `path/posix`, `path/win32`, `util/types` [`77f94f1`](https://github.com/inspect-js/is-core-module/commit/77f94f1e90ffd7c0be2a3f1aa8574ebf7fd981b3)
## [v2.1.0](https://github.com/inspect-js/is-core-module/compare/v2.0.0...v2.1.0) - 2020-11-04
### Commits
- [Dev Deps] update `eslint` [`5e0034e`](https://github.com/inspect-js/is-core-module/commit/5e0034eae57c09c8f1bd769f502486a00f56c6e4)
- [New] Add `diagnostics_channel` [`c2d83d0`](https://github.com/inspect-js/is-core-module/commit/c2d83d0a0225a1a658945d9bab7036ea347d29ec)
## [v2.0.0](https://github.com/inspect-js/is-core-module/compare/v1.0.2...v2.0.0) - 2020-09-29
### Commits
- v2 implementation [`865aeb5`](https://github.com/inspect-js/is-core-module/commit/865aeb5ca0e90248a3dfff5d7622e4751fdeb9cd)
- Only apps should have lockfiles [`5a5e660`](https://github.com/inspect-js/is-core-module/commit/5a5e660d568e37eb44e17fb1ebb12a105205fc2b)
- Initial commit for v2 [`5a51524`](https://github.com/inspect-js/is-core-module/commit/5a51524e06f92adece5fbb138c69b7b9748a2348)
- Tests [`116eae4`](https://github.com/inspect-js/is-core-module/commit/116eae4fccd01bc72c1fd3cc4b7561c387afc496)
- [meta] add `auto-changelog` [`c24388b`](https://github.com/inspect-js/is-core-module/commit/c24388bee828d223040519d1f5b226ca35beee63)
- [actions] add "Automatic Rebase" and "require allow edits" actions [`34292db`](https://github.com/inspect-js/is-core-module/commit/34292dbcbadae0868aff03c22dbd8b7b8a11558a)
- [Tests] add `npm run lint` [`4f9eeee`](https://github.com/inspect-js/is-core-module/commit/4f9eeee7ddff10698bbf528620f4dc8d4fa3e697)
- [readme] fix travis badges, https all URLs [`e516a73`](https://github.com/inspect-js/is-core-module/commit/e516a73b0dccce20938c432b1ba512eae8eff9e9)
- [meta] create FUNDING.yml [`1aabebc`](https://github.com/inspect-js/is-core-module/commit/1aabebca98d01f8a04e46bc2e2520fa93cf21ac6)
- [Fix] `domain`: domain landed sometime &gt; v0.7.7 and &lt;= v0.7.12 [`2df7d37`](https://github.com/inspect-js/is-core-module/commit/2df7d37595d41b15eeada732b706b926c2771655)
- [Fix] `sys`: worked in 0.6, not 0.7, and 0.8+ [`a75c134`](https://github.com/inspect-js/is-core-module/commit/a75c134229e1e9441801f6b73f6a52489346eb65)
## [v1.0.2](https://github.com/inspect-js/is-core-module/compare/v1.0.1...v1.0.2) - 2014-09-28
### Commits
- simpler [`66fe90f`](https://github.com/inspect-js/is-core-module/commit/66fe90f9771581b9adc0c3900baa52c21b5baea2)
## [v1.0.1](https://github.com/inspect-js/is-core-module/compare/v1.0.0...v1.0.1) - 2014-09-28
### Commits
- remove stupid [`f21f906`](https://github.com/inspect-js/is-core-module/commit/f21f906f882c2bd656a5fc5ed6fbe48ddaffb2ac)
- update readme [`1eff0ec`](https://github.com/inspect-js/is-core-module/commit/1eff0ec69798d1ec65771552d1562911e90a8027)
## v1.0.0 - 2014-09-28
### Commits
- init [`48e5e76`](https://github.com/inspect-js/is-core-module/commit/48e5e76cac378fddb8c1f7d4055b8dfc943d6b96)
The MIT License (MIT)
Copyright (c) 2014 Dave Justice
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
# is-core-module <sup>[![Version Badge][2]][1]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version.
## Example
```js
var isCore = require('is-core-module');
var assert = require('assert');
assert(isCore('fs'));
assert(!isCore('butts'));
```
## Tests
Clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/is-core-module
[2]: https://versionbadg.es/inspect-js/is-core-module.svg
[5]: https://david-dm.org/inspect-js/is-core-module.svg
[6]: https://david-dm.org/inspect-js/is-core-module
[7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg
[8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies
[11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/is-core-module.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg
[downloads-url]: https://npm-stat.com/charts.html?package=is-core-module
[codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module
[actions-url]: https://github.com/inspect-js/is-core-module/actions
{
"assert": true,
"node:assert": ">= 16",
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
"async_hooks": ">= 8",
"node:async_hooks": ">= 16",
"buffer_ieee754": "< 0.9.7",
"buffer": true,
"node:buffer": ">= 16",
"child_process": true,
"node:child_process": ">= 16",
"cluster": true,
"node:cluster": ">= 16",
"console": true,
"node:console": ">= 16",
"constants": true,
"node:constants": ">= 16",
"crypto": true,
"node:crypto": ">= 16",
"_debug_agent": ">= 1 && < 8",
"_debugger": "< 8",
"dgram": true,
"node:dgram": ">= 16",
"diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": ">= 16",
"dns": true,
"node:dns": ">= 16",
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
"domain": ">= 0.7.12",
"node:domain": ">= 16",
"events": true,
"node:events": ">= 16",
"freelist": "< 6",
"fs": true,
"node:fs": ">= 16",
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": ">= 16",
"_http_agent": ">= 0.11.1",
"node:_http_agent": ">= 16",
"_http_client": ">= 0.11.1",
"node:_http_client": ">= 16",
"_http_common": ">= 0.11.1",
"node:_http_common": ">= 16",
"_http_incoming": ">= 0.11.1",
"node:_http_incoming": ">= 16",
"_http_outgoing": ">= 0.11.1",
"node:_http_outgoing": ">= 16",
"_http_server": ">= 0.11.1",
"node:_http_server": ">= 16",
"http": true,
"node:http": ">= 16",
"http2": ">= 8.8",
"node:http2": ">= 16",
"https": true,
"node:https": ">= 16",
"inspector": ">= 8",
"node:inspector": ">= 16",
"_linklist": "< 8",
"module": true,
"node:module": ">= 16",
"net": true,
"node:net": ">= 16",
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
"os": true,
"node:os": ">= 16",
"path": true,
"node:path": ">= 16",
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
"perf_hooks": ">= 8.5",
"node:perf_hooks": ">= 16",
"process": ">= 1",
"node:process": ">= 16",
"punycode": true,
"node:punycode": ">= 16",
"querystring": true,
"node:querystring": ">= 16",
"readline": true,
"node:readline": ">= 16",
"repl": true,
"node:repl": ">= 16",
"smalloc": ">= 0.11.5 && < 3",
"_stream_duplex": ">= 0.9.4",
"node:_stream_duplex": ">= 16",
"_stream_transform": ">= 0.9.4",
"node:_stream_transform": ">= 16",
"_stream_wrap": ">= 1.4.1",
"node:_stream_wrap": ">= 16",
"_stream_passthrough": ">= 0.9.4",
"node:_stream_passthrough": ">= 16",
"_stream_readable": ">= 0.9.4",
"node:_stream_readable": ">= 16",
"_stream_writable": ">= 0.9.4",
"node:_stream_writable": ">= 16",
"stream": true,
"node:stream": ">= 16",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"string_decoder": true,
"node:string_decoder": ">= 16",
"sys": [">= 0.6 && < 0.7", ">= 0.8"],
"node:sys": ">= 16",
"timers": true,
"node:timers": ">= 16",
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
"_tls_common": ">= 0.11.13",
"node:_tls_common": ">= 16",
"_tls_legacy": ">= 0.11.3 && < 10",
"_tls_wrap": ">= 0.11.3",
"node:_tls_wrap": ">= 16",
"tls": true,
"node:tls": ">= 16",
"trace_events": ">= 10",
"node:trace_events": ">= 16",
"tty": true,
"node:tty": ">= 16",
"url": true,
"node:url": ">= 16",
"util": true,
"node:util": ">= 16",
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8": ">= 1",
"node:v8": ">= 16",
"vm": true,
"node:vm": ">= 16",
"wasi": ">= 13.4 && < 13.5",
"worker_threads": ">= 11.7",
"node:worker_threads": ">= 16",
"zlib": true,
"node:zlib": ">= 16"
}
'use strict';
var has = require('has');
function specifierIncluded(current, specifier) {
var nodeParts = current.split('.');
var parts = specifier.split(' ');
var op = parts.length > 1 ? parts[0] : '=';
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
for (var i = 0; i < 3; ++i) {
var cur = parseInt(nodeParts[i] || 0, 10);
var ver = parseInt(versionParts[i] || 0, 10);
if (cur === ver) {
continue; // eslint-disable-line no-restricted-syntax, no-continue
}
if (op === '<') {
return cur < ver;
}
if (op === '>=') {
return cur >= ver;
}
return false;
}
return op === '>=';
}
function matchesRange(current, range) {
var specifiers = range.split(/ ?&& ?/);
if (specifiers.length === 0) {
return false;
}
for (var i = 0; i < specifiers.length; ++i) {
if (!specifierIncluded(current, specifiers[i])) {
return false;
}
}
return true;
}
function versionIncluded(nodeVersion, specifierValue) {
if (typeof specifierValue === 'boolean') {
return specifierValue;
}
var current = typeof nodeVersion === 'undefined'
? process.versions && process.versions.node && process.versions.node
: nodeVersion;
if (typeof current !== 'string') {
throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');
}
if (specifierValue && typeof specifierValue === 'object') {
for (var i = 0; i < specifierValue.length; ++i) {
if (matchesRange(current, specifierValue[i])) {
return true;
}
}
return false;
}
return matchesRange(current, specifierValue);
}
var data = require('./core.json');
module.exports = function isCore(x, nodeVersion) {
return has(data, x) && versionIncluded(nodeVersion, data[x]);
};
{
"_from": "is-core-module@^2.2.0",
"_id": "is-core-module@2.4.0",
"_inBundle": false,
"_integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==",
"_location": "/is-core-module",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "is-core-module@^2.2.0",
"name": "is-core-module",
"escapedName": "is-core-module",
"rawSpec": "^2.2.0",
"saveSpec": null,
"fetchSpec": "^2.2.0"
},
"_requiredBy": [
"/resolve"
],
"_resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz",
"_shasum": "8e9fc8e15027b011418026e98f0e6f4d86305cc1",
"_spec": "is-core-module@^2.2.0",
"_where": "/home/ubuntu/stock_chatbot/server/node_modules/resolve",
"author": {
"name": "Jordan Harband",
"email": "ljharb@gmail.com"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"bugs": {
"url": "https://github.com/inspect-js/is-core-module/issues"
},
"bundleDependencies": false,
"dependencies": {
"has": "^1.0.3"
},
"deprecated": false,
"description": "Is this specifier a node.js core module?",
"devDependencies": {
"@ljharb/eslint-config": "^17.6.0",
"aud": "^1.1.5",
"auto-changelog": "^2.2.1",
"eslint": "^7.26.0",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"semver": "^6.3.0",
"tape": "^5.2.2"
},
"exports": {
".": [
{
"default": "./index.js"
},
"./index.js"
],
"./package.json": "./package.json"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"homepage": "https://github.com/inspect-js/is-core-module",
"keywords": [
"core",
"modules",
"module",
"npm",
"node",
"dependencies"
],
"license": "MIT",
"main": "index.js",
"name": "is-core-module",
"repository": {
"type": "git",
"url": "git+https://github.com/inspect-js/is-core-module.git"
},
"scripts": {
"lint": "eslint .",
"posttest": "aud --production",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"",
"prepublish": "not-in-publish || npm run prepublishOnly",
"prepublishOnly": "safe-publish-latest",
"pretest": "npm run lint",
"test": "nyc npm run tests-only",
"tests-only": "tape 'test/**/*.js'",
"version": "auto-changelog && git add CHANGELOG.md"
},
"version": "2.4.0"
}
'use strict';
var test = require('tape');
var keys = require('object-keys');
var semver = require('semver');
var isCore = require('../');
var data = require('../core.json');
var supportsNodePrefix = semver.satisfies(process.versions.node, '>= 16');
test('core modules', function (t) {
t.test('isCore()', function (st) {
st.ok(isCore('fs'));
st.ok(isCore('net'));
st.ok(isCore('http'));
st.ok(!isCore('seq'));
st.ok(!isCore('../'));
st.ok(!isCore('toString'));
st.end();
});
t.test('core list', function (st) {
var cores = keys(data);
st.plan(cores.length);
for (var i = 0; i < cores.length; ++i) {
var mod = cores[i];
var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func
if (isCore(mod)) {
st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw');
} else {
st['throws'](requireFunc, mod + ' not supported; requiring throws');
}
}
st.end();
});
t.test('core via repl module', { skip: !data.repl }, function (st) {
var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle
if (!libs) {
st.skip('module.builtinModules does not exist');
} else {
for (var i = 0; i < libs.length; ++i) {
var mod = libs[i];
st.ok(data[mod], mod + ' is a core module');
st.doesNotThrow(
function () { require(mod); }, // eslint-disable-line no-loop-func
'requiring ' + mod + ' does not throw'
);
if (supportsNodePrefix) {
st.doesNotThrow(
function () { require('node:' + mod); }, // eslint-disable-line no-loop-func
'requiring node:' + mod + ' does not throw'
);
} else {
st['throws'](
function () { require('node:' + mod); }, // eslint-disable-line no-loop-func
'requiring node:' + mod + ' throws'
);
}
}
}
st.end();
});
t.test('core via builtinModules list', { skip: !data.module }, function (st) {
var libs = require('module').builtinModules;
if (!libs) {
st.skip('module.builtinModules does not exist');
} else {
var excludeList = [
'_debug_agent',
'v8/tools/tickprocessor-driver',
'v8/tools/SourceMap',
'v8/tools/tickprocessor',
'v8/tools/profile'
];
for (var i = 0; i < libs.length; ++i) {
var mod = libs[i];
if (excludeList.indexOf(mod) === -1) {
st.ok(data[mod], mod + ' is a core module');
st.doesNotThrow(
function () { require(mod); }, // eslint-disable-line no-loop-func
'requiring ' + mod + ' does not throw'
);
if (supportsNodePrefix) {
st.doesNotThrow(
function () { require('node:' + mod); }, // eslint-disable-line no-loop-func
'requiring node:' + mod + ' does not throw'
);
} else {
st['throws'](
function () { require('node:' + mod); }, // eslint-disable-line no-loop-func
'requiring node:' + mod + ' throws'
);
}
}
}
}
st.end();
});
t.end();
});
The MIT License (MIT)
Copyright (c) 2015 Javier Blanco
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.
# path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse)
> Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com).
## Install
```
$ npm install --save path-parse
```
## Usage
```js
var pathParse = require('path-parse');
pathParse('/home/user/dir/file.txt');
//=> {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
```
## API
See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs.
### pathParse(path)
### pathParse.posix(path)
The Posix specific version.
### pathParse.win32(path)
The Windows specific version.
## License
MIT © [Javier Blanco](http://jbgutierrez.info)
'use strict';
var isWindows = process.platform === 'win32';
// Regex to split a windows path into into [dir, root, basename, name, ext]
var splitWindowsRe =
/^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
var win32 = {};
function win32SplitPath(filename) {
return splitWindowsRe.exec(filename).slice(1);
}
win32.parse = function(pathString) {
if (typeof pathString !== 'string') {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
// Split a filename into [dir, root, basename, name, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
var posix = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
posix.parse = function(pathString) {
if (typeof pathString !== 'string') {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3],
};
};
if (isWindows)
module.exports = win32.parse;
else /* posix */
module.exports = posix.parse;
module.exports.posix = posix.parse;
module.exports.win32 = win32.parse;
{
"_from": "path-parse@^1.0.6",
"_id": "path-parse@1.0.7",
"_inBundle": false,
"_integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"_location": "/path-parse",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "path-parse@^1.0.6",
"name": "path-parse",
"escapedName": "path-parse",
"rawSpec": "^1.0.6",
"saveSpec": null,
"fetchSpec": "^1.0.6"
},
"_requiredBy": [
"/resolve"
],
"_resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"_shasum": "fbc114b60ca42b30d9daf5858e4bd68bbedb6735",
"_spec": "path-parse@^1.0.6",
"_where": "/home/ubuntu/stock_chatbot/server/node_modules/resolve",
"author": {
"name": "Javier Blanco",
"email": "http://jbgutierrez.info"
},
"bugs": {
"url": "https://github.com/jbgutierrez/path-parse/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Node.js path.parse() ponyfill",
"homepage": "https://github.com/jbgutierrez/path-parse#readme",
"keywords": [
"path",
"paths",
"file",
"dir",
"parse",
"built-in",
"util",
"utils",
"core",
"ponyfill",
"polyfill",
"shim"
],
"license": "MIT",
"main": "index.js",
"name": "path-parse",
"repository": {
"type": "git",
"url": "git+https://github.com/jbgutierrez/path-parse.git"
},
"scripts": {
"test": "node test.js"
},
"version": "1.0.7"
}
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 200
[*.js]
block_comment_start = /*
block_comment = *
block_comment_end = */
[*.yml]
indent_size = 1
[package.json]
indent_style = tab
[lib/core.json]
indent_style = tab
[CHANGELOG.md]
indent_style = space
indent_size = 2
[{*.json,Makefile}]
max_line_length = off
[test/{dotdot,resolver,module_dir,multirepo,node_path,pathfilter,precedence}/**/*]
indent_style = off
indent_size = off
max_line_length = off
insert_final_newline = off
{
"extends": "@ljharb",
"root": true,
"rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"indent": [2, 4],
"strict": 0,
"complexity": 0,
"consistent-return": 0,
"curly": 0,
"dot-notation": [2, { "allowKeywords": true }],
"func-name-matching": 0,
"func-style": 0,
"global-require": 0,
"id-length": [2, { "min": 1, "max": 30 }],
"max-lines-per-function": 0,
"max-nested-callbacks": 0,
"max-params": 0,
"max-statements-per-line": [2, { "max": 2 }],
"max-statements": 0,
"no-magic-numbers": 0,
"no-console": 0,
"no-shadow": 0,
"no-unused-vars": [2, { "vars": "all", "args": "none" }],
"no-use-before-define": 0,
"object-curly-newline": 0,
"operator-linebreak": [2, "before"],
"sort-keys": 0,
},
"overrides": [
{
"files": "test/resolver/nested_symlinks/mylib/*.js",
"rules": {
"no-throw-literal": 0,
},
},
],
}
MIT License
Copyright (c) 2012 James Halliday
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.
# Security
Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report.
version: 1.0.{build}
skip_branch_with_pr: true
build: off
environment:
matrix:
#- nodejs_version: "15"
- nodejs_version: "14"
- nodejs_version: "13"
- nodejs_version: "12"
- nodejs_version: "11"
- nodejs_version: "10"
- nodejs_version: "9"
- nodejs_version: "8"
- nodejs_version: "7"
- nodejs_version: "6"
- nodejs_version: "5"
- nodejs_version: "4"
- nodejs_version: "3"
- nodejs_version: "2"
- nodejs_version: "1"
- nodejs_version: "0.12"
- nodejs_version: "0.10"
- nodejs_version: "0.8"
- nodejs_version: "0.6"
matrix:
# fast_finish: true
allow_failures:
- nodejs_version: "5" # due to windows npm bug, registry-side
- nodejs_version: "0.8"
# platform: x86 # x64 has started failing on the registry side, around early November 2020
- nodejs_version: "0.6"
platform:
- x86
- x64
# Install scripts. (runs after repo cloning)
install:
# Fix symlinks in working copy (see https://github.com/appveyor/ci/issues/650#issuecomment-186592582) / https://github.com/charleskorn/batect/commit/d08986802ec43086902958c4ee7e57ff3e71dbef
- git config core.symlinks true
- git reset --hard
# Get the latest stable version of Node.js or io.js
- ps: if ($env:nodejs_version -ne '0.6') { Install-Product node $env:nodejs_version $env:platform }
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) $env:platform
- IF %nodejs_version% EQU 0.6 npm config set strict-ssl false && npm -g install npm@1.3
- IF %nodejs_version% EQU 0.8 npm config set strict-ssl false && npm -g install npm@1.4.28 && npm install -g npm@4.5
- IF %nodejs_version% EQU 1 npm -g install npm@2.9
- IF %nodejs_version% EQU 2 npm -g install npm@4
- IF %nodejs_version% EQU 3 npm -g install npm@4
- IF %nodejs_version% EQU 4 npm -g install npm@5.3
- IF %nodejs_version% EQU 5 npm -g install npm@5.3
- IF %nodejs_version% EQU 6 npm -g install npm@6.9
- IF %nodejs_version% EQU 7 npm -g install npm@6
- IF %nodejs_version% EQU 8 npm -g install npm@6
- IF %nodejs_version% EQU 9 npm -g install npm@6.9
- IF %nodejs_version% EQU 10 npm -g install npm@7
- IF %nodejs_version% EQU 11 npm -g install npm@7
- IF %nodejs_version% EQU 12 npm -g install npm@7
- IF %nodejs_version% EQU 13 npm -g install npm@7
- IF %nodejs_version% EQU 14 npm -g install npm@7
- IF %nodejs_version% EQU 15 npm -g install npm@7
- set PATH=%APPDATA%\npm;%PATH%
#- IF %nodejs_version% NEQ 0.6 AND %nodejs_version% NEQ 0.8 npm -g install npm
# install modules
- npm install
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm run tests-only
var resolve = require('../');
resolve('tap', { basedir: __dirname }, function (err, res) {
if (err) console.error(err);
else console.log(res);
});
var resolve = require('../');
var res = resolve.sync('tap', { basedir: __dirname });
console.log(res);
var async = require('./lib/async');
async.core = require('./lib/core');
async.isCore = require('./lib/is-core');
async.sync = require('./lib/sync');
module.exports = async;
This diff is collapsed. Click to expand it.
module.exports = function () {
// see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
var origPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) { return stack; };
var stack = (new Error()).stack;
Error.prepareStackTrace = origPrepareStackTrace;
return stack[2].getFileName();
};
var current = (process.versions && process.versions.node && process.versions.node.split('.')) || [];
function specifierIncluded(specifier) {
var parts = specifier.split(' ');
var op = parts.length > 1 ? parts[0] : '=';
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
for (var i = 0; i < 3; ++i) {
var cur = parseInt(current[i] || 0, 10);
var ver = parseInt(versionParts[i] || 0, 10);
if (cur === ver) {
continue; // eslint-disable-line no-restricted-syntax, no-continue
}
if (op === '<') {
return cur < ver;
} else if (op === '>=') {
return cur >= ver;
} else {
return false;
}
}
return op === '>=';
}
function matchesRange(range) {
var specifiers = range.split(/ ?&& ?/);
if (specifiers.length === 0) { return false; }
for (var i = 0; i < specifiers.length; ++i) {
if (!specifierIncluded(specifiers[i])) { return false; }
}
return true;
}
function versionIncluded(specifierValue) {
if (typeof specifierValue === 'boolean') { return specifierValue; }
if (specifierValue && typeof specifierValue === 'object') {
for (var i = 0; i < specifierValue.length; ++i) {
if (matchesRange(specifierValue[i])) { return true; }
}
return false;
}
return matchesRange(specifierValue);
}
var data = require('./core.json');
var core = {};
for (var mod in data) { // eslint-disable-line no-restricted-syntax
if (Object.prototype.hasOwnProperty.call(data, mod)) {
core[mod] = versionIncluded(data[mod]);
}
}
module.exports = core;
{
"assert": true,
"assert/strict": ">= 15",
"async_hooks": ">= 8",
"buffer_ieee754": "< 0.9.7",
"buffer": true,
"child_process": true,
"cluster": true,
"console": true,
"constants": true,
"crypto": true,
"_debug_agent": ">= 1 && < 8",
"_debugger": "< 8",
"dgram": true,
"diagnostics_channel": ">= 15.1",
"dns": true,
"dns/promises": ">= 15",
"domain": ">= 0.7.12",
"events": true,
"freelist": "< 6",
"fs": true,
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"_http_agent": ">= 0.11.1",
"_http_client": ">= 0.11.1",
"_http_common": ">= 0.11.1",
"_http_incoming": ">= 0.11.1",
"_http_outgoing": ">= 0.11.1",
"_http_server": ">= 0.11.1",
"http": true,
"http2": ">= 8.8",
"https": true,
"inspector": ">= 8.0.0",
"_linklist": "< 8",
"module": true,
"net": true,
"node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
"os": true,
"path": true,
"path/posix": ">= 15.3",
"path/win32": ">= 15.3",
"perf_hooks": ">= 8.5",
"process": ">= 1",
"punycode": true,
"querystring": true,
"readline": true,
"repl": true,
"smalloc": ">= 0.11.5 && < 3",
"_stream_duplex": ">= 0.9.4",
"_stream_transform": ">= 0.9.4",
"_stream_wrap": ">= 1.4.1",
"_stream_passthrough": ">= 0.9.4",
"_stream_readable": ">= 0.9.4",
"_stream_writable": ">= 0.9.4",
"stream": true,
"stream/promises": ">= 15",
"string_decoder": true,
"sys": [">= 0.6 && < 0.7", ">= 0.8"],
"timers": true,
"timers/promises": ">= 15",
"_tls_common": ">= 0.11.13",
"_tls_legacy": ">= 0.11.3 && < 10",
"_tls_wrap": ">= 0.11.3",
"tls": true,
"trace_events": ">= 10",
"tty": true,
"url": true,
"util": true,
"util/types": ">= 15.3",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8/tools/consarray": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8/tools/csvparser": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8/tools/logreader": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8/tools/profile_view": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8/tools/splaytree": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"],
"v8": ">= 1",
"vm": true,
"wasi": ">= 13.4 && < 13.5",
"worker_threads": ">= 11.7",
"zlib": true
}
var isCoreModule = require('is-core-module');
module.exports = function isCore(x) {
return isCoreModule(x);
};
var path = require('path');
var parse = path.parse || require('path-parse');
var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
var prefix = '/';
if ((/^([A-Za-z]:)/).test(absoluteStart)) {
prefix = '';
} else if ((/^\\\\/).test(absoluteStart)) {
prefix = '\\\\';
}
var paths = [absoluteStart];
var parsed = parse(absoluteStart);
while (parsed.dir !== paths[paths.length - 1]) {
paths.push(parsed.dir);
parsed = parse(parsed.dir);
}
return paths.reduce(function (dirs, aPath) {
return dirs.concat(modules.map(function (moduleDir) {
return path.resolve(prefix, aPath, moduleDir);
}));
}, []);
};
module.exports = function nodeModulesPaths(start, opts, request) {
var modules = opts && opts.moduleDirectory
? [].concat(opts.moduleDirectory)
: ['node_modules'];
if (opts && typeof opts.paths === 'function') {
return opts.paths(
request,
start,
function () { return getNodeModulesDirs(start, modules); },
opts
);
}
var dirs = getNodeModulesDirs(start, modules);
return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
};
module.exports = function (x, opts) {
/**
* This file is purposefully a passthrough. It's expected that third-party
* environments will override it at runtime in order to inject special logic
* into `resolve` (by manipulating the options). One such example is the PnP
* code path in Yarn.
*/
return opts || {};
};
var isCore = require('is-core-module');
var fs = require('fs');
var path = require('path');
var caller = require('./caller');
var nodeModulesPaths = require('./node-modules-paths');
var normalizeOptions = require('./normalize-options');
var realpathFS = fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
var defaultIsFile = function isFile(file) {
try {
var stat = fs.statSync(file);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isFile() || stat.isFIFO();
};
var defaultIsDir = function isDirectory(dir) {
try {
var stat = fs.statSync(dir);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isDirectory();
};
var defaultRealpathSync = function realpathSync(x) {
try {
return realpathFS(x);
} catch (realpathErr) {
if (realpathErr.code !== 'ENOENT') {
throw realpathErr;
}
}
return x;
};
var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {
if (opts && opts.preserveSymlinks === false) {
return realpathSync(x);
}
return x;
};
var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) {
var body = readFileSync(pkgfile);
try {
var pkg = JSON.parse(body);
return pkg;
} catch (jsonErr) {}
};
var getPackageCandidates = function getPackageCandidates(x, start, opts) {
var dirs = nodeModulesPaths(start, opts, x);
for (var i = 0; i < dirs.length; i++) {
dirs[i] = path.join(dirs[i], x);
}
return dirs;
};
module.exports = function resolveSync(x, options) {
if (typeof x !== 'string') {
throw new TypeError('Path must be a string.');
}
var opts = normalizeOptions(x, options);
var isFile = opts.isFile || defaultIsFile;
var readFileSync = opts.readFileSync || fs.readFileSync;
var isDirectory = opts.isDirectory || defaultIsDir;
var realpathSync = opts.realpathSync || defaultRealpathSync;
var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
if (opts.readFileSync && opts.readPackageSync) {
throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.');
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || ['.js'];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || [];
// ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts);
if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
var res = path.resolve(absoluteStart, x);
if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
var m = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m) return maybeRealpathSync(realpathSync, m, opts);
} else if (includeCoreModules && isCore(x)) {
return x;
} else {
var n = loadNodeModulesSync(x, absoluteStart);
if (n) return maybeRealpathSync(realpathSync, n, opts);
}
var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
function loadAsFileSync(x) {
var pkg = loadpkg(path.dirname(x));
if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
var rfile = path.relative(pkg.dir, x);
var r = opts.pathFilter(pkg.pkg, x, rfile);
if (r) {
x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
}
}
if (isFile(x)) {
return x;
}
for (var i = 0; i < extensions.length; i++) {
var file = x + extensions[i];
if (isFile(file)) {
return file;
}
}
}
function loadpkg(dir) {
if (dir === '' || dir === '/') return;
if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
return;
}
if ((/[/\\]node_modules[/\\]*$/).test(dir)) return;
var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');
if (!isFile(pkgfile)) {
return loadpkg(path.dirname(dir));
}
var pkg = readPackageSync(readFileSync, pkgfile);
if (pkg && opts.packageFilter) {
// v2 will pass pkgfile
pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment
}
return { pkg: pkg, dir: dir };
}
function loadAsDirectorySync(x) {
var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json');
if (isFile(pkgfile)) {
try {
var pkg = readPackageSync(readFileSync, pkgfile);
} catch (e) {}
if (pkg && opts.packageFilter) {
// v2 will pass pkgfile
pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment
}
if (pkg && pkg.main) {
if (typeof pkg.main !== 'string') {
var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
mainError.code = 'INVALID_PACKAGE_MAIN';
throw mainError;
}
if (pkg.main === '.' || pkg.main === './') {
pkg.main = 'index';
}
try {
var m = loadAsFileSync(path.resolve(x, pkg.main));
if (m) return m;
var n = loadAsDirectorySync(path.resolve(x, pkg.main));
if (n) return n;
} catch (e) {}
}
}
return loadAsFileSync(path.join(x, '/index'));
}
function loadNodeModulesSync(x, start) {
var thunk = function () { return getPackageCandidates(x, start, opts); };
var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
if (isDirectory(path.dirname(dir))) {
var m = loadAsFileSync(dir);
if (m) return m;
var n = loadAsDirectorySync(dir);
if (n) return n;
}
}
}
};
{
"_from": "resolve@^1.20.0",
"_id": "resolve@1.20.0",
"_inBundle": false,
"_integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==",
"_location": "/resolve",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "resolve@^1.20.0",
"name": "resolve",
"escapedName": "resolve",
"rawSpec": "^1.20.0",
"saveSpec": null,
"fetchSpec": "^1.20.0"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz",
"_shasum": "629a013fb3f70755d6f0b7935cc1c2c5378b1975",
"_spec": "resolve@^1.20.0",
"_where": "/home/ubuntu/stock_chatbot/server",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/browserify/resolve/issues"
},
"bundleDependencies": false,
"dependencies": {
"is-core-module": "^2.2.0",
"path-parse": "^1.0.6"
},
"deprecated": false,
"description": "resolve like require.resolve() on behalf of files asynchronously and synchronously",
"devDependencies": {
"@ljharb/eslint-config": "^17.5.1",
"array.prototype.map": "^1.0.3",
"aud": "^1.1.4",
"eclint": "^2.8.1",
"eslint": "^7.19.0",
"object-keys": "^1.1.1",
"safe-publish-latest": "^1.1.4",
"tap": "0.4.13",
"tape": "^5.1.1"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"homepage": "https://github.com/browserify/resolve#readme",
"keywords": [
"resolve",
"require",
"node",
"module"
],
"license": "MIT",
"main": "index.js",
"name": "resolve",
"repository": {
"type": "git",
"url": "git://github.com/browserify/resolve.git"
},
"scripts": {
"lint": "eslint --ext=js,mjs .",
"posttest": "npm run test:multirepo && aud --production",
"prelint": "eclint check '**/*'",
"prepublish": "safe-publish-latest && cp node_modules/is-core-module/core.json ./lib/ ||:",
"pretest": "npm run lint",
"pretests-only": "cd ./test/resolver/nested_symlinks && node mylib/sync && node mylib/async",
"test": "npm run --silent tests-only",
"test:multirepo": "cd ./test/resolver/multirepo && npm install && npm test",
"tests-only": "tape test/*.js"
},
"version": "1.20.0"
}
# resolve
implements the [node `require.resolve()`
algorithm](https://nodejs.org/api/modules.html#modules_all_together)
such that you can `require.resolve()` on behalf of a file asynchronously and
synchronously
[![build status](https://secure.travis-ci.org/browserify/resolve.png)](http://travis-ci.org/browserify/resolve)
# example
asynchronously resolve:
```js
var resolve = require('resolve');
resolve('tap', { basedir: __dirname }, function (err, res) {
if (err) console.error(err);
else console.log(res);
});
```
```
$ node example/async.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
```
synchronously resolve:
```js
var resolve = require('resolve');
var res = resolve.sync('tap', { basedir: __dirname });
console.log(res);
```
```
$ node example/sync.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
```
# methods
```js
var resolve = require('resolve');
```
For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values:
- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module
- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory
- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string)
## resolve(id, opts={}, cb)
Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`.
options are:
* opts.basedir - directory to begin resolving from
* opts.package - `package.json` data applicable to the module being loaded
* opts.extensions - array of file extensions to search in order
* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search
* opts.readFile - how to read files asynchronously
* opts.isFile - function to asynchronously test whether a file exists
* opts.isDirectory - function to asynchronously test whether a directory exists
* opts.realpath - function to asynchronously resolve a potential symlink to its real path
* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file
* readFile - the passed `opts.readFile` or `fs.readFile` if not specified
* pkgfile - path to package.json
* cb - callback
* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field
* pkg - package data
* pkgfile - path to package.json
* dir - directory for package.json
* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
* pkg - package data
* path - the path being resolved
* relativePath - the path relative from the package.json location
* returns - a relative path that will be joined from the package.json location
* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)
For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
* request - the import specifier being resolved
* start - lookup path
* getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
* opts - the resolution options
* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
* request - the import specifier being resolved
* start - lookup path
* getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
* opts - the resolution options
* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`
* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
**Note:** this property is currently `true` by default but it will be changed to
`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.
default `opts` values:
```js
{
paths: [],
basedir: __dirname,
extensions: ['.js'],
includeCoreModules: true,
readFile: fs.readFile,
isFile: function isFile(file, cb) {
fs.stat(file, function (err, stat) {
if (!err) {
return cb(null, stat.isFile() || stat.isFIFO());
}
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
return cb(err);
});
},
isDirectory: function isDirectory(dir, cb) {
fs.stat(dir, function (err, stat) {
if (!err) {
return cb(null, stat.isDirectory());
}
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
return cb(err);
});
},
realpath: function realpath(file, cb) {
var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
realpath(file, function (realPathErr, realPath) {
if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
else cb(null, realPathErr ? file : realPath);
});
},
readPackage: function defaultReadPackage(readFile, pkgfile, cb) {
readFile(pkgfile, function (readFileErr, body) {
if (readFileErr) cb(readFileErr);
else {
try {
var pkg = JSON.parse(body);
cb(null, pkg);
} catch (jsonErr) {
cb(null);
}
}
});
},
moduleDirectory: 'node_modules',
preserveSymlinks: true
}
```
## resolve.sync(id, opts)
Synchronously resolve the module path string `id`, returning the result and
throwing an error when `id` can't be resolved.
options are:
* opts.basedir - directory to begin resolving from
* opts.extensions - array of file extensions to search in order
* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search
* opts.readFileSync - how to read files synchronously
* opts.isFile - function to synchronously test whether a file exists
* opts.isDirectory - function to synchronously test whether a directory exists
* opts.realpathSync - function to synchronously resolve a potential symlink to its real path
* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file
* readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified
* pkgfile - path to package.json
* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field
* pkg - package data
* dir - directory for package.json (Note: the second argument will change to "pkgfile" in v2)
* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
* pkg - package data
* path - the path being resolved
* relativePath - the path relative from the package.json location
* returns - a relative path that will be joined from the package.json location
* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)
For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
* request - the import specifier being resolved
* start - lookup path
* getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
* opts - the resolution options
* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
* request - the import specifier being resolved
* start - lookup path
* getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
* opts - the resolution options
* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`
* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
**Note:** this property is currently `true` by default but it will be changed to
`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.
default `opts` values:
```js
{
paths: [],
basedir: __dirname,
extensions: ['.js'],
includeCoreModules: true,
readFileSync: fs.readFileSync,
isFile: function isFile(file) {
try {
var stat = fs.statSync(file);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isFile() || stat.isFIFO();
},
isDirectory: function isDirectory(dir) {
try {
var stat = fs.statSync(dir);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isDirectory();
},
realpathSync: function realpathSync(file) {
try {
var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
return realpath(file);
} catch (realPathErr) {
if (realPathErr.code !== 'ENOENT') {
throw realPathErr;
}
}
return file;
},
readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) {
var body = readFileSync(pkgfile);
try {
var pkg = JSON.parse(body);
return pkg;
} catch (jsonErr) {}
},
moduleDirectory: 'node_modules',
preserveSymlinks: true
}
```
# install
With [npm](https://npmjs.org) do:
```sh
npm install resolve
```
# license
MIT
{
"rules": {
"max-lines": 0
}
}
var test = require('tape');
var keys = require('object-keys');
var resolve = require('../');
test('core modules', function (t) {
t.test('isCore()', function (st) {
st.ok(resolve.isCore('fs'));
st.ok(resolve.isCore('net'));
st.ok(resolve.isCore('http'));
st.ok(!resolve.isCore('seq'));
st.ok(!resolve.isCore('../'));
st.ok(!resolve.isCore('toString'));
st.end();
});
t.test('core list', function (st) {
var cores = keys(resolve.core);
st.plan(cores.length);
for (var i = 0; i < cores.length; ++i) {
var mod = cores[i];
var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func
console.log(mod, resolve.core, resolve.core[mod]);
if (resolve.core[mod]) {
st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw');
} else {
st.throws(requireFunc, mod + ' not supported; requiring throws');
}
}
st.end();
});
t.test('core via repl module', { skip: !resolve.core.repl }, function (st) {
var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle
if (!libs) {
st.skip('module.builtinModules does not exist');
return st.end();
}
for (var i = 0; i < libs.length; ++i) {
var mod = libs[i];
st.ok(resolve.core[mod], mod + ' is a core module');
st.doesNotThrow(
function () { require(mod); }, // eslint-disable-line no-loop-func
'requiring ' + mod + ' does not throw'
);
}
st.end();
});
t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) {
var libs = require('module').builtinModules;
if (!libs) {
st.skip('module.builtinModules does not exist');
return st.end();
}
var blacklist = [
'_debug_agent',
'v8/tools/tickprocessor-driver',
'v8/tools/SourceMap',
'v8/tools/tickprocessor',
'v8/tools/profile'
];
for (var i = 0; i < libs.length; ++i) {
var mod = libs[i];
if (blacklist.indexOf(mod) === -1) {
st.ok(resolve.core[mod], mod + ' is a core module');
st.doesNotThrow(
function () { require(mod); }, // eslint-disable-line no-loop-func
'requiring ' + mod + ' does not throw'
);
}
}
st.end();
});
t.end();
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('dotdot', function (t) {
t.plan(4);
var dir = path.join(__dirname, '/dotdot/abc');
resolve('..', { basedir: dir }, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(__dirname, 'dotdot/index.js'));
});
resolve('.', { basedir: dir }, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, 'index.js'));
});
});
test('dotdot sync', function (t) {
t.plan(2);
var dir = path.join(__dirname, '/dotdot/abc');
var a = resolve.sync('..', { basedir: dir });
t.equal(a, path.join(__dirname, 'dotdot/index.js'));
var b = resolve.sync('.', { basedir: dir });
t.equal(b, path.join(dir, 'index.js'));
});
var x = require('..');
console.log(x);
var test = require('tape');
var path = require('path');
var resolve = require('../');
test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) {
t.plan(1);
var resolverDir = 'C:\\a\\b\\c\\d';
resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) {
t.equal(!!err, true);
});
});
test('non-existent basedir should not throw when preserveSymlinks is false', function (t) {
t.plan(2);
var opts = {
basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'),
preserveSymlinks: false
};
var module = './dotdot/abc';
resolve(module, opts, function (err, res) {
t.equal(err.code, 'MODULE_NOT_FOUND');
t.equal(res, undefined);
});
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('filter', function (t) {
t.plan(4);
var dir = path.join(__dirname, 'resolver');
var packageFilterArgs;
resolve('./baz', {
basedir: dir,
packageFilter: function (pkg, pkgfile) {
pkg.main = 'doom'; // eslint-disable-line no-param-reassign
packageFilterArgs = [pkg, pkgfile];
return pkg;
}
}, function (err, res, pkg) {
if (err) t.fail(err);
t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works');
var packageData = packageFilterArgs[0];
t.equal(pkg, packageData, 'first packageFilter argument is "pkg"');
t.equal(packageData.main, 'doom', 'package "main" was altered');
var packageFile = packageFilterArgs[1];
t.equal(
packageFile,
path.join(dir, 'baz/package.json'),
'second packageFilter argument is "pkgfile"'
);
t.end();
});
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('filter', function (t) {
var dir = path.join(__dirname, 'resolver');
var packageFilterArgs;
var res = resolve.sync('./baz', {
basedir: dir,
// NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility
packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment
pkg.main = 'doom'; // eslint-disable-line no-param-reassign
packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef
return pkg;
}
});
t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works');
var packageData = packageFilterArgs[0];
t.equal(packageData.main, 'doom', 'package "main" was altered');
if (!'is 1.x') { // eslint-disable-line no-constant-condition
var packageFile = packageFilterArgs[1];
t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct');
}
var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition
// eslint-disable-next-line no-constant-condition
t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"');
t.end();
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('mock', function (t) {
t.plan(8);
var files = {};
files[path.resolve('/foo/bar/baz.js')] = 'beep';
var dirs = {};
dirs[path.resolve('/foo/bar')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
readFile: function (file, cb) {
cb(null, files[path.resolve(file)]);
},
realpath: function (file, cb) {
cb(null, file);
}
};
}
resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/baz.js'));
t.equal(pkg, undefined);
});
resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/baz.js'));
t.equal(pkg, undefined);
});
resolve('baz', opts('/foo/bar'), function (err, res) {
t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'");
t.equal(err.code, 'MODULE_NOT_FOUND');
});
resolve('../baz', opts('/foo/bar'), function (err, res) {
t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'");
t.equal(err.code, 'MODULE_NOT_FOUND');
});
});
test('mock from package', function (t) {
t.plan(8);
var files = {};
files[path.resolve('/foo/bar/baz.js')] = 'beep';
var dirs = {};
dirs[path.resolve('/foo/bar')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, file));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
'package': { main: 'bar' },
readFile: function (file, cb) {
cb(null, files[file]);
},
realpath: function (file, cb) {
cb(null, file);
}
};
}
resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/baz.js'));
t.equal(pkg && pkg.main, 'bar');
});
resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/baz.js'));
t.equal(pkg && pkg.main, 'bar');
});
resolve('baz', opts('/foo/bar'), function (err, res) {
t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'");
t.equal(err.code, 'MODULE_NOT_FOUND');
});
resolve('../baz', opts('/foo/bar'), function (err, res) {
t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'");
t.equal(err.code, 'MODULE_NOT_FOUND');
});
});
test('mock package', function (t) {
t.plan(2);
var files = {};
files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
main: './baz.js'
});
var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
readFile: function (file, cb) {
cb(null, files[path.resolve(file)]);
},
realpath: function (file, cb) {
cb(null, file);
}
};
}
resolve('bar', opts('/foo'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
t.equal(pkg && pkg.main, './baz.js');
});
});
test('mock package from package', function (t) {
t.plan(2);
var files = {};
files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
main: './baz.js'
});
var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
'package': { main: 'bar' },
readFile: function (file, cb) {
cb(null, files[path.resolve(file)]);
},
realpath: function (file, cb) {
cb(null, file);
}
};
}
resolve('bar', opts('/foo'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
t.equal(pkg && pkg.main, './baz.js');
});
});
test('symlinked', function (t) {
t.plan(4);
var files = {};
files[path.resolve('/foo/bar/baz.js')] = 'beep';
files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep';
var dirs = {};
dirs[path.resolve('/foo/bar')] = true;
dirs[path.resolve('/foo/bar/symlinked')] = true;
function opts(basedir) {
return {
preserveSymlinks: false,
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
readFile: function (file, cb) {
cb(null, files[path.resolve(file)]);
},
realpath: function (file, cb) {
var resolved = path.resolve(file);
if (resolved.indexOf('symlinked') >= 0) {
cb(null, resolved);
return;
}
var ext = path.extname(resolved);
if (ext) {
var dir = path.dirname(resolved);
var base = path.basename(resolved);
cb(null, path.join(dir, 'symlinked', base));
} else {
cb(null, path.join(resolved, 'symlinked'));
}
}
};
}
resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/symlinked/baz.js'));
t.equal(pkg, undefined);
});
resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
if (err) return t.fail(err);
t.equal(res, path.resolve('/foo/bar/symlinked/baz.js'));
t.equal(pkg, undefined);
});
});
test('readPackage', function (t) {
t.plan(3);
var files = {};
files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep';
files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
main: './baz.js'
});
files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop';
var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file, cb) {
cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
},
isDirectory: function (dir, cb) {
cb(null, !!dirs[path.resolve(dir)]);
},
'package': { main: 'bar' },
readFile: function (file, cb) {
cb(null, files[path.resolve(file)]);
},
realpath: function (file, cb) {
cb(null, file);
}
};
}
t.test('with readFile', function (st) {
st.plan(3);
resolve('bar', opts('/foo'), function (err, res, pkg) {
st.error(err);
st.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
st.equal(pkg && pkg.main, './baz.js');
});
});
var readPackage = function (readFile, file, cb) {
var barPackage = path.join('bar', 'package.json');
if (file.slice(-barPackage.length) === barPackage) {
cb(null, { main: './something-else.js' });
} else {
cb(null, JSON.parse(files[path.resolve(file)]));
}
};
t.test('with readPackage', function (st) {
st.plan(3);
var options = opts('/foo');
delete options.readFile;
options.readPackage = readPackage;
resolve('bar', options, function (err, res, pkg) {
st.error(err);
st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js'));
st.equal(pkg && pkg.main, './something-else.js');
});
});
t.test('with readFile and readPackage', function (st) {
st.plan(1);
var options = opts('/foo');
options.readPackage = readPackage;
resolve('bar', options, function (err) {
st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided');
});
});
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('mock', function (t) {
t.plan(4);
var files = {};
files[path.resolve('/foo/bar/baz.js')] = 'beep';
var dirs = {};
dirs[path.resolve('/foo/bar')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file) {
return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
},
isDirectory: function (dir) {
return !!dirs[path.resolve(dir)];
},
readFileSync: function (file) {
return files[path.resolve(file)];
},
realpathSync: function (file) {
return file;
}
};
}
t.equal(
resolve.sync('./baz', opts('/foo/bar')),
path.resolve('/foo/bar/baz.js')
);
t.equal(
resolve.sync('./baz.js', opts('/foo/bar')),
path.resolve('/foo/bar/baz.js')
);
t.throws(function () {
resolve.sync('baz', opts('/foo/bar'));
});
t.throws(function () {
resolve.sync('../baz', opts('/foo/bar'));
});
});
test('mock package', function (t) {
t.plan(1);
var files = {};
files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
main: './baz.js'
});
var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;
function opts(basedir) {
return {
basedir: path.resolve(basedir),
isFile: function (file) {
return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
},
isDirectory: function (dir) {
return !!dirs[path.resolve(dir)];
},
readFileSync: function (file) {
return files[path.resolve(file)];
},
realpathSync: function (file) {
return file;
}
};
}
t.equal(
resolve.sync('bar', opts('/foo')),
path.resolve('/foo/node_modules/bar/baz.js')
);
});
test('symlinked', function (t) {
t.plan(2);
var files = {};
files[path.resolve('/foo/bar/baz.js')] = 'beep';
files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep';
var dirs = {};
dirs[path.resolve('/foo/bar')] = true;
dirs[path.resolve('/foo/bar/symlinked')] = true;
function opts(basedir) {
return {
preserveSymlinks: false,
basedir: path.resolve(basedir),
isFile: function (file) {
return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
},
isDirectory: function (dir) {
return !!dirs[path.resolve(dir)];
},
readFileSync: function (file) {
return files[path.resolve(file)];
},
realpathSync: function (file) {
var resolved = path.resolve(file);
if (resolved.indexOf('symlinked') >= 0) {
return resolved;
}
var ext = path.extname(resolved);
if (ext) {
var dir = path.dirname(resolved);
var base = path.basename(resolved);
return path.join(dir, 'symlinked', base);
} else {
return path.join(resolved, 'symlinked');
}
}
};
}
t.equal(
resolve.sync('./baz', opts('/foo/bar')),
path.resolve('/foo/bar/symlinked/baz.js')
);
t.equal(
resolve.sync('./baz.js', opts('/foo/bar')),
path.resolve('/foo/bar/symlinked/baz.js')
);
});
test('readPackageSync', function (t) {
t.plan(3);
var files = {};
files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep';
files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
main: './baz.js'
});
files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop';
var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;
function opts(basedir, useReadPackage) {
return {
basedir: path.resolve(basedir),
isFile: function (file) {
return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
},
isDirectory: function (dir) {
return !!dirs[path.resolve(dir)];
},
readFileSync: useReadPackage ? null : function (file) {
return files[path.resolve(file)];
},
realpathSync: function (file) {
return file;
}
};
}
t.test('with readFile', function (st) {
st.plan(1);
st.equal(
resolve.sync('bar', opts('/foo')),
path.resolve('/foo/node_modules/bar/baz.js')
);
});
var readPackageSync = function (readFileSync, file) {
if (file.indexOf(path.join('bar', 'package.json')) >= 0) {
return { main: './something-else.js' };
} else {
return JSON.parse(files[path.resolve(file)]);
}
};
t.test('with readPackage', function (st) {
st.plan(1);
var options = opts('/foo');
delete options.readFileSync;
options.readPackageSync = readPackageSync;
st.equal(
resolve.sync('bar', options),
path.resolve('/foo/node_modules/bar/something-else.js')
);
});
t.test('with readFile and readPackage', function (st) {
st.plan(1);
var options = opts('/foo');
options.readPackageSync = readPackageSync;
st.throws(
function () { resolve.sync('bar', options); },
TypeError,
'errors when both readFile and readPackage are provided'
);
});
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('moduleDirectory strings', function (t) {
t.plan(4);
var dir = path.join(__dirname, 'module_dir');
var xopts = {
basedir: dir,
moduleDirectory: 'xmodules'
};
resolve('aaa', xopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
});
var yopts = {
basedir: dir,
moduleDirectory: 'ymodules'
};
resolve('aaa', yopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
});
});
test('moduleDirectory array', function (t) {
t.plan(6);
var dir = path.join(__dirname, 'module_dir');
var aopts = {
basedir: dir,
moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
};
resolve('aaa', aopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
});
var bopts = {
basedir: dir,
moduleDirectory: ['zmodules', 'ymodules', 'xmodules']
};
resolve('aaa', bopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
});
var copts = {
basedir: dir,
moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
};
resolve('bbb', copts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/zmodules/bbb/main.js'));
});
});
module.exports = function (x) { return x * 100; };
module.exports = function (x) { return x + 100; };
module.exports = function (n) { return n * 111; };
var test = require('tape');
var path = require('path');
var parse = path.parse || require('path-parse');
var keys = require('object-keys');
var nodeModulesPaths = require('../lib/node-modules-paths');
var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) {
var moduleDirs = [].concat(moduleDirectories || 'node_modules');
if (paths) {
for (var k = 0; k < paths.length; ++k) {
moduleDirs.push(path.basename(paths[k]));
}
}
var foundModuleDirs = {};
var uniqueDirs = {};
var parsedDirs = {};
for (var i = 0; i < dirs.length; ++i) {
var parsed = parse(dirs[i]);
if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; }
foundModuleDirs[parsed.base] += 1;
parsedDirs[parsed.dir] = true;
uniqueDirs[dirs[i]] = true;
}
t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has');
var foundModuleDirNames = keys(foundModuleDirs);
t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found');
t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique');
var counts = {};
for (var j = 0; j < foundModuleDirNames.length; ++j) {
counts[foundModuleDirs[j]] = true;
}
t.equal(keys(counts).length, 1, 'all found module directories had the same count');
};
test('node-modules-paths', function (t) {
t.test('no options', function (t) {
var start = path.join(__dirname, 'resolver');
var dirs = nodeModulesPaths(start);
verifyDirs(t, start, dirs);
t.end();
});
t.test('empty options', function (t) {
var start = path.join(__dirname, 'resolver');
var dirs = nodeModulesPaths(start, {});
verifyDirs(t, start, dirs);
t.end();
});
t.test('with paths=array option', function (t) {
var start = path.join(__dirname, 'resolver');
var paths = ['a', 'b'];
var dirs = nodeModulesPaths(start, { paths: paths });
verifyDirs(t, start, dirs, null, paths);
t.end();
});
t.test('with paths=function option', function (t) {
var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) {
return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request));
};
var start = path.join(__dirname, 'resolver');
var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg');
verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]);
t.end();
});
t.test('with paths=function skipping node modules resolution', function (t) {
var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) {
return [];
};
var start = path.join(__dirname, 'resolver');
var dirs = nodeModulesPaths(start, { paths: paths });
t.deepEqual(dirs, [], 'no node_modules was computed');
t.end();
});
t.test('with moduleDirectory option', function (t) {
var start = path.join(__dirname, 'resolver');
var moduleDirectory = 'not node modules';
var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory });
verifyDirs(t, start, dirs, moduleDirectory);
t.end();
});
t.test('with 1 moduleDirectory and paths options', function (t) {
var start = path.join(__dirname, 'resolver');
var paths = ['a', 'b'];
var moduleDirectory = 'not node modules';
var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory });
verifyDirs(t, start, dirs, moduleDirectory, paths);
t.end();
});
t.test('with 1+ moduleDirectory and paths options', function (t) {
var start = path.join(__dirname, 'resolver');
var paths = ['a', 'b'];
var moduleDirectories = ['not node modules', 'other modules'];
var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });
verifyDirs(t, start, dirs, moduleDirectories, paths);
t.end();
});
t.test('combine paths correctly on Windows', function (t) {
var start = 'C:\\Users\\username\\myProject\\src';
var paths = [];
var moduleDirectories = ['node_modules', start];
var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });
t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir');
t.end();
});
t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) {
var start = '/Users/username/git/myProject/src';
var paths = [];
var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src'];
var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });
t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir');
t.end();
});
});
var fs = require('fs');
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('$NODE_PATH', function (t) {
t.plan(8);
var isDir = function (dir, cb) {
if (dir === '/node_path' || dir === 'node_path/x') {
return cb(null, true);
}
fs.stat(dir, function (err, stat) {
if (!err) {
return cb(null, stat.isDirectory());
}
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
return cb(err);
});
};
resolve('aaa', {
paths: [
path.join(__dirname, '/node_path/x'),
path.join(__dirname, '/node_path/y')
],
basedir: __dirname,
isDirectory: isDir
}, function (err, res) {
t.error(err);
t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves');
});
resolve('bbb', {
paths: [
path.join(__dirname, '/node_path/x'),
path.join(__dirname, '/node_path/y')
],
basedir: __dirname,
isDirectory: isDir
}, function (err, res) {
t.error(err);
t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves');
});
resolve('ccc', {
paths: [
path.join(__dirname, '/node_path/x'),
path.join(__dirname, '/node_path/y')
],
basedir: __dirname,
isDirectory: isDir
}, function (err, res) {
t.error(err);
t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves');
});
// ensure that relative paths still resolve against the regular `node_modules` correctly
resolve('tap', {
paths: [
'node_path'
],
basedir: path.join(__dirname, 'node_path/x'),
isDirectory: isDir
}, function (err, res) {
var root = require('tap/package.json').main;
t.error(err);
t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves');
});
});
var test = require('tape');
var resolve = require('../');
test('nonstring', function (t) {
t.plan(1);
resolve(555, function (err, res, pkg) {
t.ok(err);
});
});
var path = require('path');
var test = require('tape');
var resolve = require('../');
var resolverDir = path.join(__dirname, '/pathfilter/deep_ref');
var pathFilterFactory = function (t) {
return function (pkg, x, remainder) {
t.equal(pkg.version, '1.2.3');
t.equal(x, path.join(resolverDir, 'node_modules/deep/ref'));
t.equal(remainder, 'ref');
return 'alt';
};
};
test('#62: deep module references and the pathFilter', function (t) {
t.test('deep/ref.js', function (st) {
st.plan(3);
resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) {
if (err) st.fail(err);
st.equal(pkg.version, '1.2.3');
st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js'));
});
var res = resolve.sync('deep/ref', { basedir: resolverDir });
st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js'));
});
t.test('deep/deeper/ref', function (st) {
st.plan(4);
resolve(
'deep/deeper/ref',
{ basedir: resolverDir },
function (err, res, pkg) {
if (err) t.fail(err);
st.notEqual(pkg, undefined);
st.equal(pkg.version, '1.2.3');
st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js'));
}
);
var res = resolve.sync(
'deep/deeper/ref',
{ basedir: resolverDir }
);
st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js'));
});
t.test('deep/ref alt', function (st) {
st.plan(8);
var pathFilter = pathFilterFactory(st);
var res = resolve.sync(
'deep/ref',
{ basedir: resolverDir, pathFilter: pathFilter }
);
st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js'));
resolve(
'deep/ref',
{ basedir: resolverDir, pathFilter: pathFilter },
function (err, res, pkg) {
if (err) st.fail(err);
st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js'));
st.end();
}
);
});
t.end();
});
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.

45 KB | W: | H:

40.9 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin