chore: Publish crates

This commit is contained in:
SWC Bot 2023-09-06 17:31:41 +00:00
parent a86e9f3bb5
commit 8bb911269c
813 changed files with 1175811 additions and 98 deletions

View File

@ -10,6 +10,9 @@
- **(es/module)** Revert #7901 (#7906) ([85d6e9b](https://github.com/swc-project/swc/commit/85d6e9be07af7bb788594b21a986636657d86f03))
- **(es/module)** Fix `jsc.paths` for projects using pnpm (#7918) ([a86e9f3](https://github.com/swc-project/swc/commit/a86e9f3bb5bd490ebf0b18fe7349a2b0fbc0c45f))
### Features

40
Cargo.lock generated
View File

@ -235,7 +235,7 @@ dependencies = [
[[package]]
name = "binding_macros"
version = "0.57.0"
version = "0.57.1"
dependencies = [
"anyhow",
"console_error_panic_hook",
@ -964,7 +964,7 @@ checksum = "23d8666cb01533c39dde32bcbab8e227b4ed6679b2c925eba05feabea39508fb"
[[package]]
name = "dbg-swc"
version = "0.87.0"
version = "0.87.1"
dependencies = [
"anyhow",
"clap 3.1.0",
@ -3525,7 +3525,7 @@ dependencies = [
[[package]]
name = "swc"
version = "0.266.0"
version = "0.266.1"
dependencies = [
"ansi_term",
"anyhow",
@ -3595,7 +3595,7 @@ dependencies = [
[[package]]
name = "swc_bundler"
version = "0.220.0"
version = "0.220.1"
dependencies = [
"anyhow",
"crc",
@ -3707,7 +3707,7 @@ dependencies = [
[[package]]
name = "swc_core"
version = "0.83.1"
version = "0.83.2"
dependencies = [
"anyhow",
"binding_macros",
@ -4044,7 +4044,7 @@ dependencies = [
[[package]]
name = "swc_ecma_loader"
version = "0.44.3"
version = "0.44.4"
dependencies = [
"anyhow",
"dashmap",
@ -4064,7 +4064,7 @@ dependencies = [
[[package]]
name = "swc_ecma_minifier"
version = "0.187.0"
version = "0.187.1"
dependencies = [
"ansi_term",
"anyhow",
@ -4131,7 +4131,7 @@ dependencies = [
[[package]]
name = "swc_ecma_preset_env"
version = "0.201.0"
version = "0.201.1"
dependencies = [
"anyhow",
"criterion",
@ -4197,7 +4197,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms"
version = "0.224.0"
version = "0.224.1"
dependencies = [
"pretty_assertions",
"sourcemap",
@ -4300,7 +4300,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_module"
version = "0.176.0"
version = "0.176.1"
dependencies = [
"Inflector",
"anyhow",
@ -4329,7 +4329,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_optimization"
version = "0.193.0"
version = "0.193.1"
dependencies = [
"dashmap",
"indexmap",
@ -4359,7 +4359,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_proposal"
version = "0.167.0"
version = "0.167.1"
dependencies = [
"either",
"rustc-hash",
@ -4383,7 +4383,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_react"
version = "0.179.0"
version = "0.179.1"
dependencies = [
"base64 0.13.1",
"dashmap",
@ -4435,7 +4435,7 @@ dependencies = [
[[package]]
name = "swc_ecma_transforms_typescript"
version = "0.183.0"
version = "0.183.1"
dependencies = [
"criterion",
"serde",
@ -4503,7 +4503,7 @@ dependencies = [
[[package]]
name = "swc_ecmascript"
version = "0.234.0"
version = "0.234.1"
dependencies = [
"swc_ecma_ast",
"swc_ecma_codegen",
@ -4551,7 +4551,7 @@ dependencies = [
[[package]]
name = "swc_estree_compat"
version = "0.191.0"
version = "0.191.1"
dependencies = [
"ahash 0.8.3",
"anyhow",
@ -4599,7 +4599,7 @@ dependencies = [
[[package]]
name = "swc_html"
version = "0.131.0"
version = "0.131.1"
dependencies = [
"swc_html_ast",
"swc_html_codegen",
@ -4650,7 +4650,7 @@ dependencies = [
[[package]]
name = "swc_html_minifier"
version = "0.128.0"
version = "0.128.1"
dependencies = [
"criterion",
"once_cell",
@ -4736,7 +4736,7 @@ dependencies = [
[[package]]
name = "swc_node_bundler"
version = "0.55.0"
version = "0.55.1"
dependencies = [
"anyhow",
"dashmap",
@ -4814,7 +4814,7 @@ dependencies = [
[[package]]
name = "swc_plugin_runner"
version = "0.102.0"
version = "0.102.1"
dependencies = [
"anyhow",
"criterion",

View File

@ -5,7 +5,7 @@ edition = "2021"
license = "Apache-2.0"
name = "binding_macros"
repository = "https://github.com/swc-project/swc.git"
version = "0.57.0"
version = "0.57.1"
[lib]
bench = false
@ -33,10 +33,10 @@ binding_wasm = [
[dependencies]
# Common deps for the SWC imports
swc = { optional = true, version = "0.266.0", path = "../swc" }
swc = { optional = true, version = "0.266.1", path = "../swc" }
swc_common = { optional = true, version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { optional = true, version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_transforms = { optional = true, version = "0.224.0", path = "../swc_ecma_transforms" }
swc_ecma_transforms = { optional = true, version = "0.224.1", path = "../swc_ecma_transforms" }
swc_ecma_visit = { optional = true, version = "0.95.1", path = "../swc_ecma_visit" }
# Optional deps for the wasm binding macro

View File

@ -5,7 +5,7 @@ edition = "2021"
license = "Apache-2.0"
name = "dbg-swc"
repository = "https://github.com/kdy1/dbg-swc.git"
version = "0.87.0"
version = "0.87.1"
[[bin]]
bench = false
@ -32,7 +32,7 @@ swc_common = { version = "0.32.1", features = [
], path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_minifier = { version = "0.187.0", path = "../swc_ecma_minifier", features = [
swc_ecma_minifier = { version = "0.187.1", path = "../swc_ecma_minifier", features = [
"concurrent",
] }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }

View File

@ -9,7 +9,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc"
repository = "https://github.com/swc-project/swc.git"
version = "0.266.0"
version = "0.266.1"
[lib]
bench = false
@ -78,15 +78,15 @@ swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_ext_transforms = { version = "0.109.0", path = "../swc_ecma_ext_transforms" }
swc_ecma_lints = { version = "0.88.0", path = "../swc_ecma_lints" }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader", features = [
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader", features = [
"cache",
"node",
"tsc",
] }
swc_ecma_minifier = { version = "0.187.0", path = "../swc_ecma_minifier" }
swc_ecma_minifier = { version = "0.187.1", path = "../swc_ecma_minifier" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_preset_env = { version = "0.201.0", path = "../swc_ecma_preset_env" }
swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms", features = [
swc_ecma_preset_env = { version = "0.201.1", path = "../swc_ecma_preset_env" }
swc_ecma_transforms = { version = "0.224.1", path = "../swc_ecma_transforms", features = [
"compat",
"module",
"optimization",
@ -96,13 +96,13 @@ swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms", fe
] }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_compat = { version = "0.159.0", path = "../swc_ecma_transforms_compat" }
swc_ecma_transforms_optimization = { version = "0.193.0", path = "../swc_ecma_transforms_optimization" }
swc_ecma_transforms_optimization = { version = "0.193.1", path = "../swc_ecma_transforms_optimization" }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
swc_error_reporters = { version = "0.16.1", path = "../swc_error_reporters" }
swc_node_comments = { version = "0.19.1", path = "../swc_node_comments" }
swc_plugin_proxy = { version = "0.38.1", path = "../swc_plugin_proxy", optional = true }
swc_plugin_runner = { version = "0.102.0", path = "../swc_plugin_runner", optional = true, default-features = false }
swc_plugin_runner = { version = "0.102.1", path = "../swc_plugin_runner", optional = true, default-features = false }
swc_timer = { version = "0.20.1", path = "../swc_timer" }
swc_visit = { version = "0.5.7", path = "../swc_visit" }

View File

@ -9,7 +9,7 @@ include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/**/*.js"]
license = "Apache-2.0"
name = "swc_bundler"
repository = "https://github.com/swc-project/swc.git"
version = "0.220.0"
version = "0.220.1"
[package.metadata.docs.rs]
all-features = true
@ -41,10 +41,10 @@ swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_common = { version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader" }
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_optimization = { version = "0.193.0", path = "../swc_ecma_transforms_optimization" }
swc_ecma_transforms_optimization = { version = "0.193.1", path = "../swc_ecma_transforms_optimization" }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
swc_fast_graph = { version = "0.20.1", path = "../swc_fast_graph/" }
@ -59,15 +59,15 @@ sha-1 = "0.10"
tempfile = "3.6.0"
url = "2.4.0"
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader", features = [
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader", features = [
"node",
"cache",
] }
swc_ecma_minifier = { version = "0.187.0", path = "../swc_ecma_minifier", features = [
swc_ecma_minifier = { version = "0.187.1", path = "../swc_ecma_minifier", features = [
"concurrent",
] }
swc_ecma_transforms_proposal = { version = "0.167.0", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { version = "0.179.0", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_typescript = { version = "0.183.0", path = "../swc_ecma_transforms_typescript" }
swc_ecma_transforms_proposal = { version = "0.167.1", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { version = "0.179.1", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_typescript = { version = "0.183.1", path = "../swc_ecma_transforms_typescript" }
swc_node_base = { version = "0.5.8", path = "../swc_node_base" }
testing = { version = "0.34.1", path = "../testing" }

View File

@ -6,7 +6,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_core"
repository = "https://github.com/swc-project/swc.git"
version = "0.83.1"
version = "0.83.2"
[package.metadata.docs.rs]
features = [
"allocator_node",
@ -324,10 +324,10 @@ __visit = ["__ecma", "swc_ecma_visit"]
once_cell = { optional = true, version = "1.18.0" }
# swc_* dependencies
binding_macros = { optional = true, version = "0.57.0", path = "../binding_macros" }
swc = { optional = true, version = "0.266.0", path = "../swc" }
binding_macros = { optional = true, version = "0.57.1", path = "../binding_macros" }
swc = { optional = true, version = "0.266.1", path = "../swc" }
swc_atoms = { optional = true, version = "0.5.9", path = "../swc_atoms" }
swc_bundler = { optional = true, version = "0.220.0", path = "../swc_bundler" }
swc_bundler = { optional = true, version = "0.220.1", path = "../swc_bundler" }
swc_cached = { optional = true, version = "0.3.17", path = "../swc_cached" }
swc_common = { optional = true, version = "0.32.1", path = "../swc_common" }
swc_css_ast = { optional = true, version = "0.139.1", path = "../swc_css_ast" }
@ -341,24 +341,24 @@ swc_css_utils = { optional = true, version = "0.136.1", path
swc_css_visit = { optional = true, version = "0.138.1", path = "../swc_css_visit" }
swc_ecma_ast = { optional = true, version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { optional = true, version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_loader = { optional = true, version = "0.44.3", path = "../swc_ecma_loader" }
swc_ecma_minifier = { optional = true, version = "0.187.0", path = "../swc_ecma_minifier" }
swc_ecma_loader = { optional = true, version = "0.44.4", path = "../swc_ecma_loader" }
swc_ecma_minifier = { optional = true, version = "0.187.1", path = "../swc_ecma_minifier" }
swc_ecma_parser = { optional = true, version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_preset_env = { optional = true, version = "0.201.0", path = "../swc_ecma_preset_env" }
swc_ecma_preset_env = { optional = true, version = "0.201.1", path = "../swc_ecma_preset_env" }
swc_ecma_quote_macros = { optional = true, version = "0.51.0", path = "../swc_ecma_quote_macros" }
swc_ecma_transforms_base = { optional = true, version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_compat = { optional = true, version = "0.159.0", path = "../swc_ecma_transforms_compat" }
swc_ecma_transforms_module = { optional = true, version = "0.176.0", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_optimization = { optional = true, version = "0.193.0", path = "../swc_ecma_transforms_optimization" }
swc_ecma_transforms_proposal = { optional = true, version = "0.167.0", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { optional = true, version = "0.179.0", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_module = { optional = true, version = "0.176.1", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_optimization = { optional = true, version = "0.193.1", path = "../swc_ecma_transforms_optimization" }
swc_ecma_transforms_proposal = { optional = true, version = "0.167.1", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { optional = true, version = "0.179.1", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_testing = { optional = true, version = "0.136.0", path = "../swc_ecma_transforms_testing" }
swc_ecma_transforms_typescript = { optional = true, version = "0.183.0", path = "../swc_ecma_transforms_typescript" }
swc_ecma_transforms_typescript = { optional = true, version = "0.183.1", path = "../swc_ecma_transforms_typescript" }
swc_ecma_usage_analyzer = { optional = true, version = "0.19.0", path = "../swc_ecma_usage_analyzer" }
swc_ecma_utils = { optional = true, version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { optional = true, version = "0.95.1", path = "../swc_ecma_visit" }
swc_node_base = { optional = true, version = "0.5.8", path = "../swc_node_base" }
swc_node_bundler = { optional = true, version = "0.55.0", path = "../swc_node_bundler" }
swc_node_bundler = { optional = true, version = "0.55.1", path = "../swc_node_bundler" }
swc_nodejs_common = { optional = true, version = "0.0.8", path = "../swc_nodejs_common" }
swc_plugin = { optional = true, version = "0.90.0", path = "../swc_plugin" }
swc_plugin_macro = { optional = true, version = "0.9.15", path = "../swc_plugin_macro" }
@ -366,7 +366,7 @@ swc_plugin_proxy = { optional = true, version = "0.38.1", path =
swc_trace_macro = { optional = true, version = "0.1.3", path = "../swc_trace_macro" }
testing = { optional = true, version = "0.34.1", path = "../testing" }
# TODO: eventually swc_plugin_runner needs to remove default features
swc_plugin_runner = { optional = true, version = "0.102.0", path = "../swc_plugin_runner", default-features = false }
swc_plugin_runner = { optional = true, version = "0.102.1", path = "../swc_plugin_runner", default-features = false }
[build-dependencies]
vergen = { version = "7.3.2", default-features = false, features = ["cargo"] }

View File

@ -6,7 +6,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_ecma_loader"
repository = "https://github.com/swc-project/swc.git"
version = "0.44.3"
version = "0.44.4"
[package.metadata.docs.rs]
all-features = true

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs", "src/lists/*.json"]
license = "Apache-2.0"
name = "swc_ecma_minifier"
repository = "https://github.com/swc-project/swc.git"
version = "0.187.0"
version = "0.187.1"
[package.metadata.docs.rs]
all-features = true
@ -60,7 +60,7 @@ swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast", features = [
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_optimization = { version = "0.193.0", path = "../swc_ecma_transforms_optimization" }
swc_ecma_transforms_optimization = { version = "0.193.1", path = "../swc_ecma_transforms_optimization" }
swc_ecma_usage_analyzer = { version = "0.19.0", path = "../swc_ecma_usage_analyzer" }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }

View File

@ -6,7 +6,7 @@ edition = "2021"
include = ["Cargo.toml", "src/**/*.rs", "src/**/*.json", "data/**/*.json"]
license = "Apache-2.0"
name = "swc_ecma_preset_env"
version = "0.201.0"
version = "0.201.1"
[lib]
bench = false
@ -31,7 +31,7 @@ string_enum = { version = "0.4.1", path = "../string_enum" }
swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_common = { version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms", features = [
swc_ecma_transforms = { version = "0.224.1", path = "../swc_ecma_transforms", features = [
"compat",
"proposal",
] }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms"
repository = "https://github.com/swc-project/swc.git"
version = "0.224.0"
version = "0.224.1"
[package.metadata.docs.rs]
all-features = true
@ -36,11 +36,11 @@ swc_common = { version = "0.32.1", path = "../swc_common"
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_compat = { version = "0.159.0", path = "../swc_ecma_transforms_compat", optional = true }
swc_ecma_transforms_module = { version = "0.176.0", path = "../swc_ecma_transforms_module", optional = true }
swc_ecma_transforms_optimization = { version = "0.193.0", path = "../swc_ecma_transforms_optimization", optional = true }
swc_ecma_transforms_proposal = { version = "0.167.0", path = "../swc_ecma_transforms_proposal", optional = true }
swc_ecma_transforms_react = { version = "0.179.0", path = "../swc_ecma_transforms_react", optional = true }
swc_ecma_transforms_typescript = { version = "0.183.0", path = "../swc_ecma_transforms_typescript", optional = true }
swc_ecma_transforms_module = { version = "0.176.1", path = "../swc_ecma_transforms_module", optional = true }
swc_ecma_transforms_optimization = { version = "0.193.1", path = "../swc_ecma_transforms_optimization", optional = true }
swc_ecma_transforms_proposal = { version = "0.167.1", path = "../swc_ecma_transforms_proposal", optional = true }
swc_ecma_transforms_react = { version = "0.179.1", path = "../swc_ecma_transforms_react", optional = true }
swc_ecma_transforms_typescript = { version = "0.183.1", path = "../swc_ecma_transforms_typescript", optional = true }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms_module"
repository = "https://github.com/swc-project/swc.git"
version = "0.176.0"
version = "0.176.1"
[lib]
bench = false
@ -28,7 +28,7 @@ swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_cached = { version = "0.3.17", path = "../swc_cached" }
swc_common = { version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader", features = [
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader", features = [
"node",
] }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
@ -40,7 +40,7 @@ swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
indexmap = { version = "1.9.3", features = ["serde"] }
serde_json = "1"
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader", features = [
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader", features = [
"node",
"tsc",
] }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms_optimization"
repository = "https://github.com/swc-project/swc.git"
version = "0.193.0"
version = "0.193.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
@ -43,9 +43,9 @@ swc_fast_graph = { version = "0.20.1", path = "../swc_fast_graph" }
[dev-dependencies]
swc_ecma_transforms_compat = { version = "0.159.0", path = "../swc_ecma_transforms_compat" }
swc_ecma_transforms_module = { version = "0.176.0", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_proposal = { version = "0.167.0", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { version = "0.179.0", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_module = { version = "0.176.1", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_proposal = { version = "0.167.1", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_react = { version = "0.179.1", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_testing = { version = "0.136.0", path = "../swc_ecma_transforms_testing" }
swc_ecma_transforms_typescript = { version = "0.183.0", path = "../swc_ecma_transforms_typescript" }
swc_ecma_transforms_typescript = { version = "0.183.1", path = "../swc_ecma_transforms_typescript" }
testing = { version = "0.34.1", path = "../testing" }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms_proposal"
repository = "https://github.com/swc-project/swc.git"
version = "0.167.0"
version = "0.167.1"
[lib]
bench = false
@ -25,7 +25,7 @@ smallvec = "1.8.0"
swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_common = { version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader", optional = true }
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader", optional = true }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_classes = { version = "0.122.0", path = "../swc_ecma_transforms_classes" }
swc_ecma_transforms_macros = { version = "0.5.3", path = "../swc_ecma_transforms_macros" }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms_react"
repository = "https://github.com/swc-project/swc.git"
version = "0.179.0"
version = "0.179.1"
[lib]
bench = false
@ -40,6 +40,6 @@ swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
[dev-dependencies]
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen/" }
swc_ecma_transforms_compat = { version = "0.159.0", path = "../swc_ecma_transforms_compat/" }
swc_ecma_transforms_module = { version = "0.176.0", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_module = { version = "0.176.1", path = "../swc_ecma_transforms_module" }
swc_ecma_transforms_testing = { version = "0.136.0", path = "../swc_ecma_transforms_testing" }
testing = { version = "0.34.1", path = "../testing" }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_ecma_transforms_typescript"
repository = "https://github.com/swc-project/swc.git"
version = "0.183.0"
version = "0.183.1"
[lib]
bench = false
@ -19,7 +19,7 @@ swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_common = { version = "0.32.1", path = "../swc_common" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_transforms_base = { version = "0.133.0", path = "../swc_ecma_transforms_base" }
swc_ecma_transforms_react = { version = "0.179.0", path = "../swc_ecma_transforms_react" }
swc_ecma_transforms_react = { version = "0.179.1", path = "../swc_ecma_transforms_react" }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
@ -29,7 +29,7 @@ criterion = "0.5"
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_transforms_compat = { version = "0.159.0", path = "../swc_ecma_transforms_compat" }
swc_ecma_transforms_proposal = { version = "0.167.0", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_proposal = { version = "0.167.1", path = "../swc_ecma_transforms_proposal" }
swc_ecma_transforms_testing = { version = "0.136.0", path = "../swc_ecma_transforms_testing" }
testing = { version = "0.34.1", path = "../testing" }

View File

@ -6,7 +6,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_ecmascript"
repository = "https://github.com/swc-project/swc.git"
version = "0.234.0"
version = "0.234.1"
[package.metadata.docs.rs]
all-features = true
@ -42,11 +42,11 @@ typescript = ["typescript-parser", "swc_ecma_transforms/typescript"]
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen", optional = true }
swc_ecma_dep_graph = { version = "0.112.0", path = "../swc_ecma_dep_graph", optional = true }
swc_ecma_minifier = { version = "0.187.0", path = "../swc_ecma_minifier", optional = true }
swc_ecma_minifier = { version = "0.187.1", path = "../swc_ecma_minifier", optional = true }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser", optional = true, default-features = false }
swc_ecma_preset_env = { version = "0.201.0", path = "../swc_ecma_preset_env", optional = true }
swc_ecma_preset_env = { version = "0.201.1", path = "../swc_ecma_preset_env", optional = true }
swc_ecma_quote = { version = "0.56.0", path = "../swc_ecma_quote", optional = true }
swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms", optional = true }
swc_ecma_transforms = { version = "0.224.1", path = "../swc_ecma_transforms", optional = true }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils", optional = true }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit", optional = true }

View File

@ -7,7 +7,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
license = "Apache-2.0"
name = "swc_estree_compat"
repository = "https://github.com/swc-project/swc.git"
version = "0.191.0"
version = "0.191.1"
[package.metadata.docs.rs]
all-features = true
@ -40,10 +40,10 @@ swc_node_comments = { version = "0.19.1", path = "../swc_node_comments/" }
criterion = "0.5"
pretty_assertions = "1.3"
swc = { version = "0.266.0", path = "../swc" }
swc = { version = "0.266.1", path = "../swc" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms/" }
swc_ecma_transforms = { version = "0.224.1", path = "../swc_ecma_transforms/" }
testing = { version = "0.34.1", path = "../testing" }
walkdir = "2"

View File

@ -6,7 +6,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_html"
repository = "https://github.com/swc-project/swc.git"
version = "0.131.0"
version = "0.131.1"
[package.metadata.docs.rs]
all-features = true
@ -21,6 +21,6 @@ minifier = ["swc_html_minifier"]
[dependencies]
swc_html_ast = {version = "0.32.1", path = "../swc_html_ast"}
swc_html_codegen = {version = "0.41.1", path = "../swc_html_codegen"}
swc_html_minifier = {version = "0.128.0", path = "../swc_html_minifier", optional = true}
swc_html_minifier = {version = "0.128.1", path = "../swc_html_minifier", optional = true}
swc_html_parser = {version = "0.38.1", path = "../swc_html_parser"}
swc_html_visit = {version = "0.32.1", path = "../swc_html_visit"}

View File

@ -10,7 +10,7 @@ include = ["Cargo.toml", "src/**/*.rs", "data/**/*.json"]
license = "Apache-2.0"
name = "swc_html_minifier"
repository = "https://github.com/swc-project/swc.git"
version = "0.128.0"
version = "0.128.1"
[lib]
bench = false
@ -31,7 +31,7 @@ swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen", features = [
"serde-impl",
] }
swc_ecma_minifier = { version = "0.187.0", path = "../swc_ecma_minifier", features = [
swc_ecma_minifier = { version = "0.187.1", path = "../swc_ecma_minifier", features = [
"extra-serde",
] }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }

View File

@ -7,7 +7,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_node_bundler"
repository = "https://github.com/swc-project/swc.git"
version = "0.55.0"
version = "0.55.1"
[lib]
bench = false
@ -29,9 +29,9 @@ serde_json = "1"
tracing = "0.1.37"
string_enum = { version = "0.4.1", path = "../string_enum" }
swc = { version = "0.266.0", path = "../swc" }
swc = { version = "0.266.1", path = "../swc" }
swc_atoms = { version = "0.5.9", path = "../swc_atoms" }
swc_bundler = { version = "0.220.0", path = "../swc_bundler", features = [
swc_bundler = { version = "0.220.1", path = "../swc_bundler", features = [
"concurrent",
] }
swc_common = { version = "0.32.1", path = "../swc_common", features = [
@ -39,9 +39,9 @@ swc_common = { version = "0.32.1", path = "../swc_common", features = [
] }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast" }
swc_ecma_codegen = { version = "0.145.0", path = "../swc_ecma_codegen" }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader" }
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_transforms = { version = "0.224.0", path = "../swc_ecma_transforms" }
swc_ecma_transforms = { version = "0.224.1", path = "../swc_ecma_transforms" }
swc_ecma_utils = { version = "0.123.0", path = "../swc_ecma_utils" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
swc_node_base = { version = "0.5.8", path = "../swc_node_base" }

View File

@ -6,7 +6,7 @@ edition = "2021"
license = "Apache-2.0"
name = "swc_plugin_runner"
repository = "https://github.com/swc-project/swc.git"
version = "0.102.0"
version = "0.102.1"
[lib]
bench = false
@ -83,7 +83,7 @@ swc_css_parser = { version = "0.148.1", path = "../swc_css_parser" }
swc_ecma_ast = { version = "0.109.1", path = "../swc_ecma_ast", features = [
"rkyv-impl",
] }
swc_ecma_loader = { version = "0.44.3", path = "../swc_ecma_loader" }
swc_ecma_loader = { version = "0.44.4", path = "../swc_ecma_loader" }
swc_ecma_parser = { version = "0.140.0", path = "../swc_ecma_parser" }
swc_ecma_visit = { version = "0.95.1", path = "../swc_ecma_visit" }
swc_node_base = { version = "0.5.8", path = "../swc_node_base" }

1
scripts/bot/node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
scripts/bot/node_modules/.bin/ts-node generated vendored Symbolic link
View File

@ -0,0 +1 @@
../ts-node/dist/bin.js

1
scripts/bot/node_modules/.bin/ts-node-cwd generated vendored Symbolic link
View File

@ -0,0 +1 @@
../ts-node/dist/bin-cwd.js

1
scripts/bot/node_modules/.bin/ts-node-script generated vendored Symbolic link
View File

@ -0,0 +1 @@
../ts-node/dist/bin-script.js

1
scripts/bot/node_modules/.bin/ts-node-transpile-only generated vendored Symbolic link
View File

@ -0,0 +1 @@
../ts-node/dist/bin-transpile.js

1
scripts/bot/node_modules/.bin/ts-script generated vendored Symbolic link
View File

@ -0,0 +1 @@
../ts-node/dist/bin-script-deprecated.js

1
scripts/bot/node_modules/.bin/tsc generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsc

1
scripts/bot/node_modules/.bin/tsserver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsserver

63
scripts/bot/node_modules/.yarn-integrity generated vendored Normal file
View File

@ -0,0 +1,63 @@
{
"systemParams": "linux-x64-93",
"modulesFolders": [
"node_modules"
],
"flags": [],
"linkedModules": [],
"topLevelPatterns": [
"@octokit/rest@^18.12.0",
"@types/node@^17.0.17",
"ts-node@^10.5.0",
"typescript@^4.5.5",
"yaml@^1.10.2"
],
"lockfileEntries": {
"@cspotcode/source-map-consumer@0.8.0": "https://registry.yarnpkg.com/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz#33bf4b7b39c178821606f669bbc447a6a629786b",
"@cspotcode/source-map-support@0.7.0": "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.7.0.tgz#4789840aa859e46d2f3173727ab707c66bf344f5",
"@octokit/auth-token@^2.4.4": "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36",
"@octokit/core@^3.5.1": "https://registry.yarnpkg.com/@octokit/core/-/core-3.5.1.tgz#8601ceeb1ec0e1b1b8217b960a413ed8e947809b",
"@octokit/endpoint@^6.0.1": "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.12.tgz#3b4d47a4b0e79b1027fb8d75d4221928b2d05658",
"@octokit/graphql@^4.5.8": "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3",
"@octokit/openapi-types@^11.2.0": "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-11.2.0.tgz#b38d7fc3736d52a1e96b230c1ccd4a58a2f400a6",
"@octokit/plugin-paginate-rest@^2.16.8": "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.17.0.tgz#32e9c7cab2a374421d3d0de239102287d791bce7",
"@octokit/plugin-request-log@^1.0.4": "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85",
"@octokit/plugin-rest-endpoint-methods@^5.12.0": "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.13.0.tgz#8c46109021a3412233f6f50d28786f8e552427ba",
"@octokit/request-error@^2.0.5": "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677",
"@octokit/request-error@^2.1.0": "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677",
"@octokit/request@^5.6.0": "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0",
"@octokit/rest@^18.12.0": "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881",
"@octokit/types@^6.0.3": "https://registry.yarnpkg.com/@octokit/types/-/types-6.34.0.tgz#c6021333334d1ecfb5d370a8798162ddf1ae8218",
"@octokit/types@^6.16.1": "https://registry.yarnpkg.com/@octokit/types/-/types-6.34.0.tgz#c6021333334d1ecfb5d370a8798162ddf1ae8218",
"@octokit/types@^6.34.0": "https://registry.yarnpkg.com/@octokit/types/-/types-6.34.0.tgz#c6021333334d1ecfb5d370a8798162ddf1ae8218",
"@tsconfig/node10@^1.0.7": "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.8.tgz#c1e4e80d6f964fbecb3359c43bd48b40f7cadad9",
"@tsconfig/node12@^1.0.7": "https://registry.yarnpkg.com/@tsconfig/node12/-/node12-1.0.9.tgz#62c1f6dee2ebd9aead80dc3afa56810e58e1a04c",
"@tsconfig/node14@^1.0.0": "https://registry.yarnpkg.com/@tsconfig/node14/-/node14-1.0.1.tgz#95f2d167ffb9b8d2068b0b235302fafd4df711f2",
"@tsconfig/node16@^1.0.2": "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.2.tgz#423c77877d0569db20e1fc80885ac4118314010e",
"@types/node@^17.0.17": "https://registry.yarnpkg.com/@types/node/-/node-17.0.17.tgz#a8ddf6e0c2341718d74ee3dc413a13a042c45a0c",
"acorn-walk@^8.1.1": "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.2.0.tgz#741210f2e2426454508853a2f44d0ab83b7f69c1",
"acorn@^8.4.1": "https://registry.yarnpkg.com/acorn/-/acorn-8.7.0.tgz#90951fde0f8f09df93549481e5fc141445b791cf",
"arg@^4.1.0": "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089",
"before-after-hook@^2.2.0": "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.2.tgz#a6e8ca41028d90ee2c24222f201c90956091613e",
"create-require@^1.1.0": "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333",
"deprecation@^2.0.0": "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919",
"deprecation@^2.3.1": "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919",
"diff@^4.0.1": "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d",
"is-plain-object@^5.0.0": "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344",
"make-error@^1.1.1": "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2",
"node-fetch@^2.6.7": "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad",
"once@^1.4.0": "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1",
"tr46@~0.0.3": "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a",
"ts-node@^10.5.0": "https://registry.yarnpkg.com/ts-node/-/ts-node-10.5.0.tgz#618bef5854c1fbbedf5e31465cbb224a1d524ef9",
"typescript@^4.5.5": "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3",
"universal-user-agent@^6.0.0": "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee",
"v8-compile-cache-lib@^3.0.0": "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz#0582bcb1c74f3a2ee46487ceecf372e46bce53e8",
"webidl-conversions@^3.0.0": "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871",
"whatwg-url@^5.0.0": "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d",
"wrappy@1": "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f",
"yaml@^1.10.2": "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b",
"yn@3.1.1": "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50"
},
"files": [],
"artifacts": {}
}

View File

@ -0,0 +1,7 @@
A smaller version of @cspotcode/source-map which includes only the consumer, not the generator.
**NOTE**: the type declarations are incorrect. They include declarations for things from @cspotcode/source-map
which are omitted from this package.
This is a delibrate, pragmatic choice. The declarations for things which *are* included -- the consumer -- should
be correct.

View File

@ -0,0 +1,100 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
class ArraySet {
constructor() {
this._array = [];
this._set = new Map();
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
static fromArray(aArray, aAllowDuplicates) {
const set = new ArraySet();
for (let i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
}
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
size() {
return this._set.size;
}
/**
* Add the given string to this set.
*
* @param String aStr
*/
add(aStr, aAllowDuplicates) {
const isDuplicate = this.has(aStr);
const idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set.set(aStr, idx);
}
}
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
has(aStr) {
return this._set.has(aStr);
}
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
indexOf(aStr) {
const idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
throw new Error('"' + aStr + '" is not in the set.');
}
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error("No element indexed by " + aIdx);
}
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
toArray() {
return this._array.slice();
}
}
exports.ArraySet = ArraySet;

View File

@ -0,0 +1,107 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
const mid = Math.floor((aHigh - aLow) / 2) + aLow;
const cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
} else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
}
return mid;
}
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
}
return aLow < 0 ? -1 : aLow;
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

Binary file not shown.

View File

@ -0,0 +1,25 @@
// Node version of reading a wasm file into an array buffer.
const fs = require("fs");
const path = require("path");
module.exports = function readWasm() {
return new Promise((resolve, reject) => {
const wasmPath = path.join(__dirname, "mappings.wasm");
fs.readFile(wasmPath, null, (error, data) => {
if (error) {
reject(error);
return;
}
resolve(data.buffer);
});
});
};
module.exports.sync = function readWasmSync() {
const wasmPath = path.join(__dirname, "mappings.wasm");
return fs.readFileSync(wasmPath).buffer;
};
module.exports.initialize = _ => {
console.debug("SourceMapConsumer.initialize is a no-op when running in node.js");
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,546 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
}
throw new Error('"' + aName + '" is a required argument.');
}
exports.getArg = getArg;
const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
const dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
const match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
let url = "";
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ":";
}
url += "//";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@";
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
const MAX_CACHED_INPUTS = 32;
/**
* Takes some function `f(input) -> result` and returns a memoized version of
* `f`.
*
* We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
* memoization is a dumb-simple, linear least-recently-used cache.
*/
function lruMemoize(f) {
const cache = [];
return function(input) {
for (let i = 0; i < cache.length; i++) {
if (cache[i].input === input) {
const temp = cache[0];
cache[0] = cache[i];
cache[i] = temp;
return cache[0].result;
}
}
const result = f(input);
cache.unshift({
input,
result,
});
if (cache.length > MAX_CACHED_INPUTS) {
cache.pop();
}
return result;
};
}
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
const normalize = lruMemoize(function normalize(aPath) {
let path = aPath;
const url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
const isAbsolute = exports.isAbsolute(path);
// Split the path into parts between `/` characters. This is much faster than
// using `.split(/\/+/g)`.
const parts = [];
let start = 0;
let i = 0;
while (true) {
start = i;
i = path.indexOf("/", start);
if (i === -1) {
parts.push(path.slice(start));
break;
} else {
parts.push(path.slice(start, i));
while (i < path.length && path[i] === "/") {
i++;
}
}
}
let up = 0;
for (i = parts.length - 1; i >= 0; i--) {
const part = parts[i];
if (part === ".") {
parts.splice(i, 1);
} else if (part === "..") {
up++;
} else if (up > 0) {
if (part === "") {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join("/");
if (path === "") {
path = isAbsolute ? "/" : ".";
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
});
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
const aPathUrl = urlParse(aPath);
const aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || "/";
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
const joined = aPath.charAt(0) === "/"
? aPath
: normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function(aPath) {
return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, "");
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
let level = 0;
while (aPath.indexOf(aRoot + "/") !== 0) {
const index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
const supportsNullProto = (function() {
const obj = Object.create(null);
return !("__proto__" in obj);
}());
function identity(s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return "$" + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
const length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
/* eslint-disable no-multi-spaces */
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
/* eslint-enable no-multi-spaces */
for (let i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
let cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
let cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 === null) {
return 1; // aStr2 !== null
}
if (aStr2 === null) {
return -1; // aStr1 !== null
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
let cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
/**
* Strip any JSON XSSI avoidance prefix from the string (as documented
* in the source maps specification), and then parse the string as
* JSON.
*/
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
}
exports.parseSourceMapInput = parseSourceMapInput;
/**
* Compute the URL of a source given the the source root, the source's
* URL, and the source map's URL.
*/
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
sourceURL = sourceURL || "";
if (sourceRoot) {
// This follows what Chrome does.
if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
sourceRoot += "/";
}
// The spec says:
// Line 4: An optional source root, useful for relocating source
// files on a server or removing repeated values in the
// “sources” entry. This value is prepended to the individual
// entries in the “source” field.
sourceURL = sourceRoot + sourceURL;
}
// Historically, SourceMapConsumer did not take the sourceMapURL as
// a parameter. This mode is still somewhat supported, which is why
// this code block is conditional. However, it's preferable to pass
// the source map URL to SourceMapConsumer, so that this function
// can implement the source URL resolution algorithm as outlined in
// the spec. This block is basically the equivalent of:
// new URL(sourceURL, sourceMapURL).toString()
// ... except it avoids using URL, which wasn't available in the
// older releases of node still supported by this library.
//
// The spec says:
// If the sources are not absolute URLs after prepending of the
// “sourceRoot”, the sources are resolved relative to the
// SourceMap (like resolving script src in a html document).
if (sourceMapURL) {
const parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
const index = parsed.path.lastIndexOf("/");
if (index >= 0) {
parsed.path = parsed.path.substring(0, index + 1);
}
}
sourceURL = join(urlGenerate(parsed), sourceURL);
}
return normalize(sourceURL);
}
exports.computeSourceURL = computeSourceURL;

View File

@ -0,0 +1,153 @@
const readWasm = require("../lib/read-wasm");
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.lastGeneratedColumn = null;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
let cachedWasm = null;
let cachedWasmSync = null;
module.exports = async function wasm() {
if (cachedWasm) {
return cachedWasm;
}
// At every step of the way, if a sync load already succeeded, abort and return
// the sync-loaded module.
cachedWasm = async () => {
try {
const callbackStack = [];
const buffer = await readWasm();
if (cachedWasmSync) return cachedWasmSync;
const Wasm = await WebAssembly.instantiate(buffer, getImportObject({callbackStack}));
if (cachedWasmSync) return cachedWasmSync;
cachedWasmSync = {
exports: Wasm.instance.exports,
withMappingCallback: (mappingCallback, f) => {
callbackStack.push(mappingCallback);
try {
f();
} finally {
callbackStack.pop();
}
}
};
} catch (e) {
if (cachedWasmSync) return cachedWasmSync;
cachedWasm = null;
throw e;
}
return cachedWasmSync;
};
return cachedWasm;
};
module.exports.sync = function wasmSync() {
if (cachedWasmSync) {
return cachedWasmSync;
}
const callbackStack = [];
try {
const cachedWasmBuffer = readWasm.sync();
const wasmModule = new WebAssembly.Module(cachedWasmBuffer);
const Wasm = new WebAssembly.Instance(wasmModule, getImportObject({callbackStack}));
cachedWasmSync = {
exports: Wasm.exports,
withMappingCallback: (mappingCallback, f) => {
callbackStack.push(mappingCallback);
try {
f();
} finally {
callbackStack.pop();
}
}
};
} catch (e) {
cachedWasmSync = null;
throw e;
}
return cachedWasmSync;
};
function getImportObject({callbackStack}) {
return {
env: {
mapping_callback(
generatedLine,
generatedColumn,
hasLastGeneratedColumn,
lastGeneratedColumn,
hasOriginal,
source,
originalLine,
originalColumn,
hasName,
name
) {
const mapping = new Mapping();
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.generatedLine = generatedLine + 1;
mapping.generatedColumn = generatedColumn;
if (hasLastGeneratedColumn) {
// JS uses inclusive last generated column, wasm uses exclusive.
mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
}
if (hasOriginal) {
mapping.source = source;
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.originalLine = originalLine + 1;
mapping.originalColumn = originalColumn;
if (hasName) {
mapping.name = name;
}
}
callbackStack[callbackStack.length - 1](mapping);
},
start_all_generated_locations_for() { console.time("all_generated_locations_for"); },
end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); },
start_compute_column_spans() { console.time("compute_column_spans"); },
end_compute_column_spans() { console.timeEnd("compute_column_spans"); },
start_generated_location_for() { console.time("generated_location_for"); },
end_generated_location_for() { console.timeEnd("generated_location_for"); },
start_original_location_for() { console.time("original_location_for"); },
end_original_location_for() { console.timeEnd("original_location_for"); },
start_parse_mappings() { console.time("parse_mappings"); },
end_parse_mappings() { console.timeEnd("parse_mappings"); },
start_sort_by_generated_location() { console.time("sort_by_generated_location"); },
end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); },
start_sort_by_original_location() { console.time("sort_by_original_location"); },
end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); },
}
};
}

View File

@ -0,0 +1,91 @@
{
"name": "@cspotcode/source-map-consumer",
"description": "Generates and consumes source maps",
"version": "0.8.0",
"homepage": "https://github.com/cspotcode/source-map",
"author": "Andrew Bradley <cspotcode@gmail.com>",
"contributors": [
"Nick Fitzgerald <nfitzgerald@mozilla.com>",
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/cspotcode/source-map.git"
},
"main": "./source-map.js",
"types": "./source-map.d.ts",
"files": [
"/source-map.js",
"/source-map.d.ts",
"/lib/"
],
"engines": {
"node": ">= 12"
},
"license": "BSD-3-Clause",
"scripts": {
"lint": "eslint *.js lib/ test/",
"prebuild": "npm run lint",
"build": "webpack --color",
"pretest": "npm run build",
"test": "node test/run-tests.js",
"precoverage": "npm run build",
"coverage": "nyc node test/run-tests.js",
"coverage-report": "nyc report --reporter=lcov",
"setup": "mkdir -p coverage && cp -n .waiting.html coverage/index.html || true",
"dev:live": "live-server --port=4103 --ignorePattern='(js|css|png)$' coverage",
"dev:watch": "watch 'npm run coverage' lib/ test/",
"predev": "npm run setup",
"dev": "npm-run-all -p --silent dev:*",
"clean": "rm -rf coverage .nyc_output",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"eslint": "^4.19.1",
"live-server": "^1.2.0",
"npm-run-all": "^4.1.2",
"nyc": "^11.7.1",
"watch": "^1.0.2",
"webpack": "^3.10"
},
"nyc": {
"reporter": "html"
},
"typings": "source-map"
}

View File

@ -0,0 +1,369 @@
// Type definitions for source-map 0.7
// Project: https://github.com/mozilla/source-map
// Definitions by: Morten Houston Ludvigsen <https://github.com/MortenHoustonLudvigsen>,
// Ron Buckton <https://github.com/rbuckton>,
// John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/mozilla/source-map
export type SourceMapUrl = string;
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
skipValidation?: boolean;
}
export interface RawSourceMap {
version: number;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
}
export interface RawIndexMap extends StartOfSourceMap {
version: number;
sections: RawSection[];
}
export interface RawSection {
offset: Position;
map: RawSourceMap;
}
export interface Position {
line: number;
column: number;
}
export interface NullablePosition {
line: number | null;
column: number | null;
lastColumn: number | null;
}
export interface MappedPosition {
source: string;
line: number;
column: number;
name?: string;
}
export interface NullableMappedPosition {
source: string | null;
line: number | null;
column: number | null;
name: string | null;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export interface SourceMapConsumer {
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
computeColumnSpans(): void;
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition;
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition;
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[];
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
hasContentsOfAllSources(): boolean;
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param callback
* The function that is called with each mapping.
* @param context
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param order
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
/**
* Free this source map consumer's associated wasm data that is manually-managed.
* Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy.
*/
destroy(): void;
}
export interface SourceMapConsumerConstructor {
prototype: SourceMapConsumer;
GENERATED_ORDER: number;
ORIGINAL_ORDER: number;
GREATEST_LOWER_BOUND: number;
LEAST_UPPER_BOUND: number;
new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): BasicSourceMapConsumer;
new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): IndexedSourceMapConsumer;
new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): BasicSourceMapConsumer | IndexedSourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>;
/**
* Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
* (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
* function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
* for `f` to complete, call `destroy` on the consumer, and return `f`'s return
* value.
*
* You must not use the consumer after `f` completes!
*
* By using `with`, you do not have to remember to manually call `destroy` on
* the consumer, since it will be called automatically once `f` completes.
*
* ```js
* const xSquared = await SourceMapConsumer.with(
* myRawSourceMap,
* null,
* async function (consumer) {
* // Use `consumer` inside here and don't worry about remembering
* // to call `destroy`.
*
* const x = await whatever(consumer);
* return x * x;
* }
* );
*
* // You may not use that `consumer` anymore out here; it has
* // been destroyed. But you can use `xSquared`.
* console.log(xSquared);
* ```
*/
with<T>(rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise<T> | T): Promise<T>;
}
export const SourceMapConsumer: SourceMapConsumerConstructor;
export interface BasicSourceMapConsumer extends SourceMapConsumer {
file: string;
sourceRoot: string;
sources: string[];
sourcesContent: string[];
}
export interface BasicSourceMapConsumerConstructor {
prototype: BasicSourceMapConsumer;
new (rawSourceMap: RawSourceMap | string): BasicSourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator): Promise<BasicSourceMapConsumer>;
}
export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor;
export interface IndexedSourceMapConsumer extends SourceMapConsumer {
sources: string[];
}
export interface IndexedSourceMapConsumerConstructor {
prototype: IndexedSourceMapConsumer;
new (rawSourceMap: RawIndexMap | string): IndexedSourceMapConsumer;
}
export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor;
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param sourceMapConsumer The SourceMap.
*/
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
addMapping(mapping: Mapping): void;
/**
* Set the source content for a source file.
*/
setSourceContent(sourceFile: string, sourceContent: string): void;
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param sourceMapConsumer The source map to be applied.
* @param sourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param sourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
toJSON(): RawSourceMap;
}
export class SourceNode {
children: SourceNode[];
sourceContents: any;
line: number;
column: number;
source: string;
name: string;
constructor();
constructor(
line: number | null,
column: number | null,
source: string | null,
chunks?: Array<(string | SourceNode)> | SourceNode | string,
name?: string
);
static fromStringWithSourceMap(
code: string,
sourceMapConsumer: SourceMapConsumer,
relativePath?: string
): SourceNode;
add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}

View File

@ -0,0 +1,6 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapConsumer = require("./lib/source-map-consumer").SourceMapConsumer;

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Evan Wallace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,289 @@
# Source Map Support
[![NPM version](https://img.shields.io/npm/v/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support)
[![NPM downloads](https://img.shields.io/npm/dm/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support)
[![Build status](https://img.shields.io/github/workflow/status/cspotcode/node-source-map-support/Continuous%20Integration)](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22)
This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
## Installation and Usage
#### Node support
```
$ npm install @cspotcode/source-map-support
```
Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
```
//# sourceMappingURL=path/to/source.map
```
If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
The path should either be absolute or relative to the compiled file.
From here you have two options.
##### CLI Usage
```bash
node -r @cspotcode/source-map-support/register compiled.js
# Or to enable hookRequire
node -r @cspotcode/source-map-support/register-hook-require compiled.js
```
##### Programmatic Usage
Put the following line at the top of the compiled file.
```js
require('@cspotcode/source-map-support').install();
```
It is also possible to install the source map support directly by
requiring the `register` module which can be handy with ES6:
```js
import '@cspotcode/source-map-support/register'
// Instead of:
import sourceMapSupport from '@cspotcode/source-map-support'
sourceMapSupport.install()
```
Note: if you're using babel-register, it includes source-map-support already.
It is also very useful with Mocha:
```
$ mocha --require @cspotcode/source-map-support/register tests/
```
#### Browser support
This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
```html
<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>
```
This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
```html
<script>
define(['browser-source-map-support'], function(sourceMapSupport) {
sourceMapSupport.install();
});
</script>
```
## Options
This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
```js
require('@cspotcode/source-map-support').install({
handleUncaughtExceptions: false
});
```
This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
```js
require('@cspotcode/source-map-support').install({
retrieveSourceMap: function(source) {
if (source === 'compiled.js') {
return {
url: 'original.js',
map: fs.readFileSync('compiled.js.map', 'utf8')
};
}
return null;
}
});
```
The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
```js
require('@cspotcode/source-map-support').install({
environment: 'node'
});
```
To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
```js
require('@cspotcode/source-map-support').install({
hookRequire: true
});
```
This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
## Demos
#### Basic Demo
original.js:
```js
throw new Error('test'); // This is the original code
```
compiled.js:
```js
require('@cspotcode/source-map-support').install();
throw new Error('test'); // This is the compiled code
// The next line defines the sourceMapping.
//# sourceMappingURL=compiled.js.map
```
compiled.js.map:
```json
{
"version": 3,
"file": "compiled.js",
"sources": ["original.js"],
"names": [],
"mappings": ";;AAAA,MAAM,IAAI"
}
```
Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
```
$ node compiled.js
original.js:1
throw new Error('test'); // This is the original code
^
Error: test
at Object.<anonymous> (original.js:1:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### TypeScript Demo
demo.ts:
```typescript
declare function require(name: string);
require('@cspotcode/source-map-support').install();
class Foo {
constructor() { this.bar(); }
bar() { throw new Error('this is a demo'); }
}
new Foo();
```
Compile and run the file using the TypeScript compiler from the terminal:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node -r source-map-support/register demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### CoffeeScript Demo
demo.coffee:
```coffee
require('@cspotcode/source-map-support').install()
foo = ->
bar = -> throw new Error 'this is a demo'
bar()
foo()
```
Compile and run the file using the CoffeeScript compiler from the terminal:
```sh
$ npm install @cspotcode/source-map-support coffeescript
$ node_modules/.bin/coffee --map --compile demo.coffee
$ node demo.js
demo.coffee:3
bar = -> throw new Error 'this is a demo'
^
Error: this is a demo
at bar (demo.coffee:3:22)
at foo (demo.coffee:4:3)
at Object.<anonymous> (demo.coffee:5:1)
at Object.<anonymous> (demo.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
```
## Tests
This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
* Build the tests using `build.js`
* Launch the HTTP server (`npm run serve-tests`) and visit
* http://127.0.0.1:1336/amd-test
* http://127.0.0.1:1336/browser-test
* http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
## License
This code is available under the [MIT license](http://opensource.org/licenses/MIT).

View File

@ -0,0 +1,46 @@
{
"name": "@cspotcode/source-map-support",
"description": "Fixes stack traces for files with source maps",
"version": "0.7.0",
"main": "./source-map-support.js",
"types": "./source-map-support.d.ts",
"scripts": {
"build": "node build.js",
"serve-tests": "http-server -p 1336",
"test": "mocha"
},
"files": [
"/register.d.ts",
"/register.js",
"/register-hook-require.d.ts",
"/register-hook-require.js",
"/source-map-support.d.ts",
"/source-map-support.js"
],
"dependencies": {
"@cspotcode/source-map-consumer": "0.8.0"
},
"devDependencies": {
"browserify": "^4.2.3",
"coffeescript": "^1.12.7",
"http-server": "^0.11.1",
"mocha": "^3.5.3",
"source-map": "0.6.1",
"webpack": "^1.15.0"
},
"repository": {
"type": "git",
"url": "https://github.com/cspotcode/node-source-map-support"
},
"bugs": {
"url": "https://github.com/cspotcode/node-source-map-support/issues"
},
"license": "MIT",
"engines": {
"node": ">=12"
},
"volta": {
"node": "16.11.0",
"npm": "7.24.2"
}
}

View File

@ -0,0 +1,7 @@
// tslint:disable:no-useless-files
// For following usage:
// import '@cspotcode/source-map-support/register-hook-require'
// Instead of:
// import sourceMapSupport from '@cspotcode/source-map-support'
// sourceMapSupport.install({hookRequire: true})

View File

@ -0,0 +1,3 @@
require('./').install({
hookRequire: true
});

View File

@ -0,0 +1,7 @@
// tslint:disable:no-useless-files
// For following usage:
// import '@cspotcode/source-map-support/register'
// Instead of:
// import sourceMapSupport from '@cspotcode/source-map-support'
// sourceMapSupport.install()

View File

@ -0,0 +1 @@
require('./').install();

View File

@ -0,0 +1,68 @@
// Type definitions for source-map-support 0.5
// Project: https://github.com/evanw/node-source-map-support
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Jason Cheatham <https://github.com/jason0x43>
// Alcedo Nathaniel De Guzman Jr <https://github.com/natealcedo>
// Griffin Yourick <https://github.com/tough-griff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { RawSourceMap } from '@cspotcode/source-map-consumer';
/**
* Output of retrieveSourceMap().
* From source-map-support:
* The map field may be either a string or the parsed JSON object (i.e.,
* it must be a valid argument to the SourceMapConsumer constructor).
*/
export interface UrlAndMap {
url: string;
map: string | RawSourceMap;
}
/**
* Options to install().
*/
export interface Options {
handleUncaughtExceptions?: boolean | undefined;
hookRequire?: boolean | undefined;
emptyCacheBetweenOperations?: boolean | undefined;
environment?: 'auto' | 'browser' | 'node' | undefined;
overrideRetrieveFile?: boolean | undefined;
overrideRetrieveSourceMap?: boolean | undefined;
retrieveFile?(path: string): string;
retrieveSourceMap?(source: string): UrlAndMap | null;
/**
* Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support`
*/
redirectConflictingLibrary?: boolean;
/**
* Callback will be called every time we redirect due to `redirectConflictingLibrary`
* This allows consumers to log helpful warnings if they choose.
* @param parent NodeJS.Module which made the require() or require.resolve() call
* @param options options object internally passed to node's `_resolveFilename` hook
*/
onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void;
}
export interface Position {
source: string;
line: number;
column: number;
}
export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */;
export function getErrorSource(error: Error): string | null;
export function mapSourcePosition(position: Position): Position;
export function retrieveSourceMap(source: string): UrlAndMap | null;
export function resetRetrieveHandlers(): void;
/**
* Install SourceMap support.
* @param options Can be used to e.g. disable uncaughtException handler.
*/
export function install(options?: Options): void;
/**
* Uninstall SourceMap support.
*/
export function uninstall(): void;

View File

@ -0,0 +1,806 @@
var SourceMapConsumer = require('@cspotcode/source-map-consumer').SourceMapConsumer;
var path = require('path');
var util = require('util');
var fs;
try {
fs = require('fs');
if (!fs.existsSync || !fs.readFileSync) {
// fs doesn't have all methods we need
fs = null;
}
} catch (err) {
/* nop */
}
/**
* Requires a module which is protected against bundler minification.
*
* @param {NodeModule} mod
* @param {string} request
*/
function dynamicRequire(mod, request) {
return mod.require(request);
}
/**
* @typedef {{
* enabled: boolean;
* originalValue: any;
* installedValue: any;
* }} HookState
* Used for installing and uninstalling hooks
*/
// Increment this if the format of sharedData changes in a breaking way.
var sharedDataVersion = 1;
/**
* @template T
* @param {T} defaults
* @returns {T}
*/
function initializeSharedData(defaults) {
var sharedDataKey = 'source-map-support/sharedData';
if (typeof Symbol !== 'undefined') {
sharedDataKey = Symbol.for(sharedDataKey);
}
var sharedData = this[sharedDataKey];
if (!sharedData) {
sharedData = { version: sharedDataVersion };
if (Object.defineProperty) {
Object.defineProperty(this, sharedDataKey, { value: sharedData });
} else {
this[sharedDataKey] = sharedData;
}
}
if (sharedDataVersion !== sharedData.version) {
throw new Error("Multiple incompatible instances of source-map-support were loaded");
}
for (var key in defaults) {
if (!(key in sharedData)) {
sharedData[key] = defaults[key];
}
}
return sharedData;
}
// If multiple instances of source-map-support are loaded into the same
// context, they shouldn't overwrite each other. By storing handlers, caches,
// and other state on a shared object, different instances of
// source-map-support can work together in a limited way. This does require
// that future versions of source-map-support continue to support the fields on
// this object. If this internal contract ever needs to be broken, increment
// sharedDataVersion. (This version number is not the same as any of the
// package's version numbers, which should reflect the *external* API of
// source-map-support.)
var sharedData = initializeSharedData({
// Only install once if called multiple times
// Remember how the environment looked before installation so we can restore if able
/** @type {HookState} */
errorPrepareStackTraceHook: undefined,
/** @type {HookState} */
processEmitHook: undefined,
/** @type {HookState} */
moduleResolveFilenameHook: undefined,
/** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */
onConflictingLibraryRedirectArr: [],
// If true, the caches are reset before a stack trace formatting operation
emptyCacheBetweenOperations: false,
// Maps a file path to a string containing the file contents
fileContentsCache: {},
// Maps a file path to a source map for that file
sourceMapCache: {},
// Priority list of retrieve handlers
retrieveFileHandlers: [],
retrieveMapHandlers: [],
// Priority list of internally-implemented handlers.
// When resetting state, we must keep these.
internalRetrieveFileHandlers: [],
internalRetrieveMapHandlers: [],
});
// Supports {browser, node, auto}
var environment = "auto";
// Regex for detecting source maps
var reSourceMap = /^data:application\/json[^,]+base64,/;
function isInBrowser() {
if (environment === "browser")
return true;
if (environment === "node")
return false;
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
}
function hasGlobalProcessEventEmitter() {
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
}
function handlerExec(list, internalList) {
return function(arg) {
for (var i = 0; i < list.length; i++) {
var ret = list[i](arg);
if (ret) {
return ret;
}
}
for (var i = 0; i < internalList.length; i++) {
var ret = internalList[i](arg);
if (ret) {
return ret;
}
}
return null;
};
}
var retrieveFile = handlerExec(sharedData.retrieveFileHandlers, sharedData.internalRetrieveFileHandlers);
sharedData.internalRetrieveFileHandlers.push(function(path) {
// Trim the path to make sure there is no extra whitespace.
path = path.trim();
if (/^file:/.test(path)) {
// existsSync/readFileSync can't handle file protocol, but once stripped, it works
path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
return drive ?
'' : // file:///C:/dir/file -> C:/dir/file
'/'; // file:///root-dir/file -> /root-dir/file
});
}
if (path in sharedData.fileContentsCache) {
return sharedData.fileContentsCache[path];
}
var contents = '';
try {
if (!fs) {
// Use SJAX if we are in the browser
var xhr = new XMLHttpRequest();
xhr.open('GET', path, /** async */ false);
xhr.send(null);
if (xhr.readyState === 4 && xhr.status === 200) {
contents = xhr.responseText;
}
} else if (fs.existsSync(path)) {
// Otherwise, use the filesystem
contents = fs.readFileSync(path, 'utf8');
}
} catch (er) {
/* ignore any errors */
}
return sharedData.fileContentsCache[path] = contents;
});
// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
function supportRelativeURL(file, url) {
if (!file) return url;
var dir = path.dirname(file);
var match = /^\w+:\/\/[^\/]*/.exec(dir);
var protocol = match ? match[0] : '';
var startPath = dir.slice(protocol.length);
if (protocol && /^\/\w\:/.test(startPath)) {
// handle file:///C:/ paths
protocol += '/';
return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
}
return protocol + path.resolve(dir.slice(protocol.length), url);
}
function retrieveSourceMapURL(source) {
var fileData;
if (isInBrowser()) {
try {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, false);
xhr.send(null);
fileData = xhr.readyState === 4 ? xhr.responseText : null;
// Support providing a sourceMappingURL via the SourceMap header
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
xhr.getResponseHeader("X-SourceMap");
if (sourceMapHeader) {
return sourceMapHeader;
}
} catch (e) {
}
}
// Get the URL of the source map
fileData = retrieveFile(source);
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
// Keep executing the search to find the *last* sourceMappingURL to avoid
// picking up sourceMappingURLs from comments, strings, etc.
var lastMatch, match;
while (match = re.exec(fileData)) lastMatch = match;
if (!lastMatch) return null;
return lastMatch[1];
};
// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map. The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers);
sharedData.internalRetrieveMapHandlers.push(function(source) {
var sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL) return null;
// Read the contents of the source map
var sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
// Support source map URL as a data url
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
sourceMapData = Buffer.from(rawData, "base64").toString();
sourceMappingURL = source;
} else {
// Support source map URLs relative to the source URL
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(sourceMappingURL);
}
if (!sourceMapData) {
return null;
}
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
var sourceMap = sharedData.sourceMapCache[position.source];
if (!sourceMap) {
// Call the (overrideable) retrieveSourceMap function to get the source map.
var urlAndMap = retrieveSourceMap(position.source);
if (urlAndMap) {
sourceMap = sharedData.sourceMapCache[position.source] = {
url: urlAndMap.url,
map: new SourceMapConsumer(urlAndMap.map)
};
// Load all sources stored inline with the source map into the file cache
// to pretend like they are already loaded. They may not exist on disk.
if (sourceMap.map.sourcesContent) {
sourceMap.map.sources.forEach(function(source, i) {
var contents = sourceMap.map.sourcesContent[i];
if (contents) {
var url = supportRelativeURL(sourceMap.url, source);
sharedData.fileContentsCache[url] = contents;
}
});
}
} else {
sourceMap = sharedData.sourceMapCache[position.source] = {
url: null,
map: null
};
}
}
// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
var originalPosition = sourceMap.map.originalPositionFor(position);
// Only return the original position if a matching line was found. If no
// matching line is found then we return position instead, which will cause
// the stack trace to print the path and line for the compiled file. It is
// better to give a precise location in the compiled file than a vague
// location in the original file.
if (originalPosition.source !== null) {
originalPosition.source = supportRelativeURL(
sourceMap.url, originalPosition.source);
return originalPosition;
}
}
return position;
}
// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
// Most eval() calls are in this format
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
var position = mapSourcePosition({
source: match[2],
line: +match[3],
column: match[4] - 1
});
return 'eval at ' + match[1] + ' (' + position.source + ':' +
position.line + ':' + (position.column + 1) + ')';
}
// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) {
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
}
// Make sure we still return useful information if we didn't find anything
return origin;
}
// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
// implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
var fileName;
var fileLocation = "";
if (this.isNative()) {
fileLocation = "native";
} else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", "; // Expecting source position to follow.
}
if (fileName) {
fileLocation += fileName;
} else {
// Source code does not originate from a file and is not native, but we
// can still get the source position inside the source string, e.g. in
// an eval string.
fileLocation += "<anonymous>";
}
var lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = this.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
}
}
var line = "";
var isAsync = this.isAsync ? this.isAsync() : false;
if(isAsync) {
line += 'async ';
var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false;
var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false;
if(isPromiseAny || isPromiseAll) {
line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index ';
var promiseIndex = this.getPromiseIndex();
line += promiseIndex + ')';
}
}
var functionName = this.getFunctionName();
var addSuffix = true;
var isConstructor = this.isConstructor();
var isMethodCall = !(this.isToplevel() || isConstructor);
if (isMethodCall) {
var typeName = this.getTypeName();
// Fixes shim to be backward compatable with Node v0 to v4
if (typeName === "[object Object]") {
typeName = "null";
}
var methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += typeName + ".";
}
line += functionName;
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
line += " [as " + methodName + "]";
}
} else {
line += typeName + "." + (methodName || "<anonymous>");
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) {
line += " (" + fileLocation + ")";
}
return line;
}
function cloneCallSite(frame) {
var object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame, state) {
// provides interface backward compatibility
if (state === undefined) {
state = { nextPosition: null, curPosition: null }
}
if(frame.isNative()) {
state.curPosition = null;
return frame;
}
// Most call sites will return the source file from getFileName(), but code
// passed to eval() ending in "//# sourceURL=..." will return the source file
// from getScriptNameOrSourceURL() instead
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
var line = frame.getLineNumber();
var column = frame.getColumnNumber() - 1;
// Fix position in Node where some (internal) code is prepended.
// See https://github.com/evanw/node-source-map-support/issues/36
// Header removed in node at ^10.16 || >=11.11.0
// v11 is not an LTS candidate, we can just test the one version with it.
// Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
var headerLength = noHeader.test(process.version) ? 0 : 62;
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
column -= headerLength;
}
var position = mapSourcePosition({
source: source,
line: line,
column: column
});
state.curPosition = position;
frame = cloneCallSite(frame);
var originalFunctionName = frame.getFunctionName;
frame.getFunctionName = function() {
if (state.nextPosition == null) {
return originalFunctionName();
}
return state.nextPosition.name || originalFunctionName();
};
frame.getFileName = function() { return position.source; };
frame.getLineNumber = function() { return position.line; };
frame.getColumnNumber = function() { return position.column + 1; };
frame.getScriptNameOrSourceURL = function() { return position.source; };
return frame;
}
// Code called using eval() needs special handling
var origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() { return origin; };
return frame;
}
// If we get here then we were unable to change the source position
return frame;
}
var kIsNodeError = undefined;
try {
// Get a deliberate ERR_INVALID_ARG_TYPE
// TODO is there a better way to reliably get an instance of NodeError?
path.resolve(123);
} catch(e) {
const symbols = Object.getOwnPropertySymbols(e);
const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0});
if(symbol) kIsNodeError = symbol;
}
const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err);
/** @param {HookState} hookState */
function createPrepareStackTrace(hookState) {
return prepareStackTrace;
// This function is part of the V8 stack trace API, for more info see:
// https://v8.dev/docs/stack-trace-api
function prepareStackTrace(error, stack) {
if(!hookState.enabled) return hookState.originalValue.apply(this, arguments);
if (sharedData.emptyCacheBetweenOperations) {
sharedData.fileContentsCache = {};
sharedData.sourceMapCache = {};
}
// node gives its own errors special treatment. Mimic that behavior
// https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128
// https://github.com/nodejs/node/pull/39182
var errorString;
if (kIsNodeError) {
if(kIsNodeError in error) {
errorString = `${error.name} [${error.code}]: ${error.message}`;
} else {
errorString = ErrorPrototypeToString(error);
}
} else {
var name = error.name || 'Error';
var message = error.message || '';
errorString = name + ": " + message;
}
var state = { nextPosition: null, curPosition: null };
var processedStack = [];
for (var i = stack.length - 1; i >= 0; i--) {
processedStack.push('\n at ' + wrapCallSite(stack[i], state));
state.nextPosition = state.curPosition;
}
state.curPosition = state.nextPosition = null;
return errorString + processedStack.reverse().join('');
}
}
// Generate position and snippet of original source with pointer
function getErrorSource(error) {
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
if (match) {
var source = match[1];
var line = +match[2];
var column = +match[3];
// Support the inline sourceContents inside the source map
var contents = sharedData.fileContentsCache[source];
// Support files on disk
if (!contents && fs && fs.existsSync(source)) {
try {
contents = fs.readFileSync(source, 'utf8');
} catch (er) {
contents = '';
}
}
// Format the line from the original source code like node does
if (contents) {
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
if (code) {
return source + ':' + line + '\n' + code + '\n' +
new Array(column).join(' ') + '^';
}
}
}
return null;
}
function printFatalErrorUponExit (error) {
var source = getErrorSource(error);
// Ensure error is printed synchronously and not truncated
if (process.stderr._handle && process.stderr._handle.setBlocking) {
process.stderr._handle.setBlocking(true);
}
if (source) {
console.error(source);
}
// Matches node's behavior for colorized output
console.error(
util.inspect(error, {
customInspect: false,
colors: process.stderr.isTTY
})
);
}
function shimEmitUncaughtException () {
const originalValue = process.emit;
var hook = sharedData.processEmitHook = {
enabled: true,
originalValue,
installedValue: undefined
};
var isTerminatingDueToFatalException = false;
var fatalException;
process.emit = sharedData.processEmitHook.installedValue = function (type) {
const hadListeners = originalValue.apply(this, arguments);
if(hook.enabled) {
if (type === 'uncaughtException' && !hadListeners) {
isTerminatingDueToFatalException = true;
fatalException = arguments[1];
process.exit(1);
}
if (type === 'exit' && isTerminatingDueToFatalException) {
printFatalErrorUponExit(fatalException);
}
}
return hadListeners;
};
}
var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0);
var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0);
exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;
exports.install = function(options) {
options = options || {};
if (options.environment) {
environment = options.environment;
if (["node", "browser", "auto"].indexOf(environment) === -1) {
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
}
}
// Use dynamicRequire to avoid including in browser bundles
var Module = dynamicRequire(module, 'module');
// Redirect subsequent imports of "source-map-support"
// to this package
const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options;
if(redirectConflictingLibrary) {
if (!sharedData.moduleResolveFilenameHook) {
const originalValue = Module._resolveFilename;
const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = {
enabled: true,
originalValue,
installedValue: undefined,
}
Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) {
if (moduleResolveFilenameHook.enabled) {
// Match all source-map-support entrypoints: source-map-support, source-map-support/register
let requestRedirect;
if (request === 'source-map-support') {
requestRedirect = './';
} else if (request === 'source-map-support/register') {
requestRedirect = './register';
}
if (requestRedirect !== undefined) {
const newRequest = require.resolve(requestRedirect);
for (const cb of sharedData.onConflictingLibraryRedirectArr) {
cb(request, parent, isMain, options, newRequest);
}
request = newRequest;
}
}
return originalValue.call(this, request, parent, isMain, options);
}
}
if (onConflictingLibraryRedirect) {
sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect);
}
}
// Allow sources to be found by methods other than reading the files
// directly from disk.
if (options.retrieveFile) {
if (options.overrideRetrieveFile) {
sharedData.retrieveFileHandlers.length = 0;
}
sharedData.retrieveFileHandlers.unshift(options.retrieveFile);
}
// Allow source maps to be found by methods other than reading the files
// directly from disk.
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) {
sharedData.retrieveMapHandlers.length = 0;
}
sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
// Support runtime transpilers that include inline source maps
if (options.hookRequire && !isInBrowser()) {
var $compile = Module.prototype._compile;
if (!$compile.__sourceMapSupport) {
Module.prototype._compile = function(content, filename) {
sharedData.fileContentsCache[filename] = content;
sharedData.sourceMapCache[filename] = undefined;
return $compile.call(this, content, filename);
};
Module.prototype._compile.__sourceMapSupport = true;
}
}
// Configure options
if (!sharedData.emptyCacheBetweenOperations) {
sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
options.emptyCacheBetweenOperations : false;
}
// Install the error reformatter
if (!sharedData.errorPrepareStackTraceHook) {
const originalValue = Error.prepareStackTrace;
sharedData.errorPrepareStackTraceHook = {
enabled: true,
originalValue,
installedValue: undefined
};
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook);
}
if (!sharedData.processEmitHook) {
var installHandler = 'handleUncaughtExceptions' in options ?
options.handleUncaughtExceptions : true;
// Do not override 'uncaughtException' with our own handler in Node.js
// Worker threads. Workers pass the error to the main thread as an event,
// rather than printing something to stderr and exiting.
try {
// We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
var worker_threads = dynamicRequire(module, 'worker_threads');
if (worker_threads.isMainThread === false) {
installHandler = false;
}
} catch(e) {}
// Provide the option to not install the uncaught exception handler. This is
// to support other uncaught exception handlers (in test frameworks, for
// example). If this handler is not installed and there are no other uncaught
// exception handlers, uncaught exceptions will be caught by node's built-in
// exception handler and the process will still be terminated. However, the
// generated JavaScript code will be shown above the stack trace instead of
// the original source code.
if (installHandler && hasGlobalProcessEventEmitter()) {
shimEmitUncaughtException();
}
}
};
exports.uninstall = function() {
if(sharedData.processEmitHook) {
// Disable behavior
sharedData.processEmitHook.enabled = false;
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
if(process.emit === sharedData.processEmitHook.installedValue) {
process.emit = sharedData.processEmitHook.originalValue;
}
sharedData.processEmitHook = undefined;
}
if(sharedData.errorPrepareStackTraceHook) {
// Disable behavior
sharedData.errorPrepareStackTraceHook.enabled = false;
// If possible or necessary, remove our hook function.
// In vanilla environments, prepareStackTrace is `undefined`.
// We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function.
// If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both.
if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') {
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue;
}
sharedData.errorPrepareStackTraceHook = undefined;
}
if (sharedData.moduleResolveFilenameHook) {
// Disable behavior
sharedData.moduleResolveFilenameHook.enabled = false;
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
var Module = dynamicRequire(module, 'module');
if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) {
Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue;
}
sharedData.moduleResolveFilenameHook = undefined;
}
sharedData.onConflictingLibraryRedirectArr.length = 0;
}
exports.resetRetrieveHandlers = function() {
sharedData.retrieveFileHandlers.length = 0;
sharedData.retrieveMapHandlers.length = 0;
}

21
scripts/bot/node_modules/@octokit/auth-token/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

290
scripts/bot/node_modules/@octokit/auth-token/README.md generated vendored Normal file
View File

@ -0,0 +1,290 @@
# auth-token.js
> GitHub API token authentication for browsers and Node.js
[![@latest](https://img.shields.io/npm/v/@octokit/auth-token.svg)](https://www.npmjs.com/package/@octokit/auth-token)
[![Build Status](https://github.com/octokit/auth-token.js/workflows/Test/badge.svg)](https://github.com/octokit/auth-token.js/actions?query=workflow%3ATest)
`@octokit/auth-token` is the simplest of [GitHubs authentication strategies](https://github.com/octokit/auth.js).
It is useful if you want to support multiple authentication strategies, as its API is compatible with its sibling packages for [basic](https://github.com/octokit/auth-basic.js), [GitHub App](https://github.com/octokit/auth-app.js) and [OAuth app](https://github.com/octokit/auth.js) authentication.
<!-- toc -->
- [Usage](#usage)
- [`createTokenAuth(token) options`](#createtokenauthtoken-options)
- [`auth()`](#auth)
- [Authentication object](#authentication-object)
- [`auth.hook(request, route, options)` or `auth.hook(request, options)`](#authhookrequest-route-options-or-authhookrequest-options)
- [Find more information](#find-more-information)
- [Find out what scopes are enabled for oauth tokens](#find-out-what-scopes-are-enabled-for-oauth-tokens)
- [Find out if token is a personal access token or if it belongs to an OAuth app](#find-out-if-token-is-a-personal-access-token-or-if-it-belongs-to-an-oauth-app)
- [Find out what permissions are enabled for a repository](#find-out-what-permissions-are-enabled-for-a-repository)
- [Use token for git operations](#use-token-for-git-operations)
- [License](#license)
<!-- tocstop -->
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load `@octokit/auth-token` directly from [cdn.skypack.dev](https://cdn.skypack.dev)
```html
<script type="module">
import { createTokenAuth } from "https://cdn.skypack.dev/@octokit/auth-token";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/auth-token</code>
```js
const { createTokenAuth } = require("@octokit/auth-token");
// or: import { createTokenAuth } from "@octokit/auth-token";
```
</td></tr>
</tbody>
</table>
```js
const auth = createTokenAuth("ghp_PersonalAccessToken01245678900000000");
const authentication = await auth();
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
```
## `createTokenAuth(token) options`
The `createTokenAuth` method accepts a single argument of type string, which is the token. The passed token can be one of the following:
- [Personal access token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line)
- [OAuth access token](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)
- [GITHUB_TOKEN provided to GitHub Actions](https://developer.github.com/actions/creating-github-actions/accessing-the-runtime-environment/#environment-variables)
- Installation access token ([server-to-server](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation))
- User authentication for installation ([user-to-server](https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps))
Examples
```js
// Personal access token or OAuth access token
createTokenAuth("ghp_PersonalAccessToken01245678900000000");
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
// Installation access token or GitHub Action token
createTokenAuth("ghs_InstallallationOrActionToken00000000");
// {
// type: 'token',
// token: 'ghs_InstallallationOrActionToken00000000',
// tokenType: 'installation'
// }
// Installation access token or GitHub Action token
createTokenAuth("ghu_InstallationUserToServer000000000000");
// {
// type: 'token',
// token: 'ghu_InstallationUserToServer000000000000',
// tokenType: 'user-to-server'
// }
```
## `auth()`
The `auth()` method has no options. It returns a promise which resolves with the the authentication object.
## Authentication object
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>type</code>
</th>
<th>
<code>string</code>
</th>
<td>
<code>"token"</code>
</td>
</tr>
<tr>
<th>
<code>token</code>
</th>
<th>
<code>string</code>
</th>
<td>
The provided token.
</td>
</tr>
<tr>
<th>
<code>tokenType</code>
</th>
<th>
<code>string</code>
</th>
<td>
Can be either <code>"oauth"</code> for personal access tokens and OAuth tokens, <code>"installation"</code> for installation access tokens (includes <code>GITHUB_TOKEN</code> provided to GitHub Actions), <code>"app"</code> for a GitHub App JSON Web Token, or <code>"user-to-server"</code> for a user authentication token through an app installation.
</td>
</tr>
</tbody>
</table>
## `auth.hook(request, route, options)` or `auth.hook(request, options)`
`auth.hook()` hooks directly into the request life cycle. It authenticates the request using the provided token.
The `request` option is an instance of [`@octokit/request`](https://github.com/octokit/request.js#readme). The `route`/`options` parameters are the same as for the [`request()` method](https://github.com/octokit/request.js#request).
`auth.hook()` can be called directly to send an authenticated request
```js
const { data: authorizations } = await auth.hook(
request,
"GET /authorizations"
);
```
Or it can be passed as option to [`request()`](https://github.com/octokit/request.js#request).
```js
const requestWithAuth = request.defaults({
request: {
hook: auth.hook,
},
});
const { data: authorizations } = await requestWithAuth("GET /authorizations");
```
## Find more information
`auth()` does not send any requests, it only transforms the provided token string into an authentication object.
Here is a list of things you can do to retrieve further information
### Find out what scopes are enabled for oauth tokens
Note that this does not work for installations. There is no way to retrieve permissions based on an installation access tokens.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("HEAD /", {
headers: authentication.headers,
});
const scopes = response.headers["x-oauth-scopes"].split(/,\s+/);
if (scopes.length) {
console.log(
`"${TOKEN}" has ${scopes.length} scopes enabled: ${scopes.join(", ")}`
);
} else {
console.log(`"${TOKEN}" has no scopes enabled`);
}
```
### Find out if token is a personal access token or if it belongs to an OAuth app
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("HEAD /", {
headers: authentication.headers,
});
const clientId = response.headers["x-oauth-client-id"];
if (clientId) {
console.log(
`"${token}" is an OAuth token, its apps client_id is ${clientId}.`
);
} else {
console.log(`"${token}" is a personal access token`);
}
```
### Find out what permissions are enabled for a repository
Note that the `permissions` key is not set when authenticated using an installation access token.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("GET /repos/{owner}/{repo}", {
owner: 'octocat',
repo: 'hello-world'
headers: authentication.headers
});
console.log(response.data.permissions)
// {
// admin: true,
// push: true,
// pull: true
// }
```
### Use token for git operations
Both OAuth and installation access tokens can be used for git operations. However, when using with an installation, [the token must be prefixed with `x-access-token`](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation).
This example is using the [`execa`](https://github.com/sindresorhus/execa) package to run a `git push` command.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();
const tokenWithPrefix =
tokenType === "installation" ? `x-access-token:${token}` : token;
const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`;
const { stdout } = await execa("git", ["push", repositoryUrl]);
console.log(stdout);
```
## License
[MIT](LICENSE)

View File

@ -0,0 +1,55 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
return {
type: "token",
token: token,
tokenType
};
}
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
const createTokenAuth = function createTokenAuth(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
});
};
exports.createTokenAuth = createTokenAuth;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["const REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nconst REGEX_IS_INSTALLATION = /^ghs_/;\nconst REGEX_IS_USER_TO_SERVER = /^ghu_/;\nexport async function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||\n REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp\n ? \"app\"\n : isInstallation\n ? \"installation\"\n : isUserToServer\n ? \"user-to-server\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType,\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token),\n });\n};\n"],"names":["REGEX_IS_INSTALLATION_LEGACY","REGEX_IS_INSTALLATION","REGEX_IS_USER_TO_SERVER","auth","token","isApp","split","length","isInstallation","test","isUserToServer","tokenType","type","withAuthorizationPrefix","hook","request","route","parameters","endpoint","merge","headers","authorization","createTokenAuth","Error","replace","Object","assign","bind"],"mappings":";;;;AAAA,MAAMA,4BAA4B,GAAG,OAArC;AACA,MAAMC,qBAAqB,GAAG,OAA9B;AACA,MAAMC,uBAAuB,GAAG,OAAhC;AACO,eAAeC,IAAf,CAAoBC,KAApB,EAA2B;AAC9B,QAAMC,KAAK,GAAGD,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAA3C;AACA,QAAMC,cAAc,GAAGR,4BAA4B,CAACS,IAA7B,CAAkCL,KAAlC,KACnBH,qBAAqB,CAACQ,IAAtB,CAA2BL,KAA3B,CADJ;AAEA,QAAMM,cAAc,GAAGR,uBAAuB,CAACO,IAAxB,CAA6BL,KAA7B,CAAvB;AACA,QAAMO,SAAS,GAAGN,KAAK,GACjB,KADiB,GAEjBG,cAAc,GACV,cADU,GAEVE,cAAc,GACV,gBADU,GAEV,OANd;AAOA,SAAO;AACHE,IAAAA,IAAI,EAAE,OADH;AAEHR,IAAAA,KAAK,EAAEA,KAFJ;AAGHO,IAAAA;AAHG,GAAP;AAKH;;ACpBD;AACA;AACA;AACA;AACA;AACA,AAAO,SAASE,uBAAT,CAAiCT,KAAjC,EAAwC;AAC3C,MAAIA,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAAjC,EAAoC;AAChC,WAAQ,UAASH,KAAM,EAAvB;AACH;;AACD,SAAQ,SAAQA,KAAM,EAAtB;AACH;;ACTM,eAAeU,IAAf,CAAoBV,KAApB,EAA2BW,OAA3B,EAAoCC,KAApC,EAA2CC,UAA3C,EAAuD;AAC1D,QAAMC,QAAQ,GAAGH,OAAO,CAACG,QAAR,CAAiBC,KAAjB,CAAuBH,KAAvB,EAA8BC,UAA9B,CAAjB;AACAC,EAAAA,QAAQ,CAACE,OAAT,CAAiBC,aAAjB,GAAiCR,uBAAuB,CAACT,KAAD,CAAxD;AACA,SAAOW,OAAO,CAACG,QAAD,CAAd;AACH;;MCHYI,eAAe,GAAG,SAASA,eAAT,CAAyBlB,KAAzB,EAAgC;AAC3D,MAAI,CAACA,KAAL,EAAY;AACR,UAAM,IAAImB,KAAJ,CAAU,0DAAV,CAAN;AACH;;AACD,MAAI,OAAOnB,KAAP,KAAiB,QAArB,EAA+B;AAC3B,UAAM,IAAImB,KAAJ,CAAU,uEAAV,CAAN;AACH;;AACDnB,EAAAA,KAAK,GAAGA,KAAK,CAACoB,OAAN,CAAc,oBAAd,EAAoC,EAApC,CAAR;AACA,SAAOC,MAAM,CAACC,MAAP,CAAcvB,IAAI,CAACwB,IAAL,CAAU,IAAV,EAAgBvB,KAAhB,CAAd,EAAsC;AACzCU,IAAAA,IAAI,EAAEA,IAAI,CAACa,IAAL,CAAU,IAAV,EAAgBvB,KAAhB;AADmC,GAAtC,CAAP;AAGH,CAXM;;;;"}

View File

@ -0,0 +1,21 @@
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
export async function auth(token) {
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||
REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp
? "app"
: isInstallation
? "installation"
: isUserToServer
? "user-to-server"
: "oauth";
return {
type: "token",
token: token,
tokenType,
};
}

View File

@ -0,0 +1,6 @@
import { withAuthorizationPrefix } from "./with-authorization-prefix";
export async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}

View File

@ -0,0 +1,14 @@
import { auth } from "./auth";
import { hook } from "./hook";
export const createTokenAuth = function createTokenAuth(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token),
});
};

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,11 @@
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
export function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}

View File

@ -0,0 +1,2 @@
import { Token, Authentication } from "./types";
export declare function auth(token: Token): Promise<Authentication>;

View File

@ -0,0 +1,2 @@
import { AnyResponse, EndpointOptions, RequestInterface, RequestParameters, Route, Token } from "./types";
export declare function hook(token: Token, request: RequestInterface, route: Route | EndpointOptions, parameters?: RequestParameters): Promise<AnyResponse>;

View File

@ -0,0 +1,7 @@
import { StrategyInterface, Token, Authentication } from "./types";
export declare type Types = {
StrategyOptions: Token;
AuthOptions: never;
Authentication: Authentication;
};
export declare const createTokenAuth: StrategyInterface;

View File

@ -0,0 +1,33 @@
import * as OctokitTypes from "@octokit/types";
export declare type AnyResponse = OctokitTypes.OctokitResponse<any>;
export declare type StrategyInterface = OctokitTypes.StrategyInterface<[
Token
], [
], Authentication>;
export declare type EndpointDefaults = OctokitTypes.EndpointDefaults;
export declare type EndpointOptions = OctokitTypes.EndpointOptions;
export declare type RequestParameters = OctokitTypes.RequestParameters;
export declare type RequestInterface = OctokitTypes.RequestInterface;
export declare type Route = OctokitTypes.Route;
export declare type Token = string;
export declare type OAuthTokenAuthentication = {
type: "token";
tokenType: "oauth";
token: Token;
};
export declare type InstallationTokenAuthentication = {
type: "token";
tokenType: "installation";
token: Token;
};
export declare type AppAuthentication = {
type: "token";
tokenType: "app";
token: Token;
};
export declare type UserToServerAuthentication = {
type: "token";
tokenType: "user-to-server";
token: Token;
};
export declare type Authentication = OAuthTokenAuthentication | InstallationTokenAuthentication | AppAuthentication | UserToServerAuthentication;

View File

@ -0,0 +1,6 @@
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
export declare function withAuthorizationPrefix(token: string): string;

View File

@ -0,0 +1,55 @@
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||
REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp
? "app"
: isInstallation
? "installation"
: isUserToServer
? "user-to-server"
: "oauth";
return {
type: "token",
token: token,
tokenType,
};
}
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
const createTokenAuth = function createTokenAuth(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token),
});
};
export { createTokenAuth };
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["const REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nconst REGEX_IS_INSTALLATION = /^ghs_/;\nconst REGEX_IS_USER_TO_SERVER = /^ghu_/;\nexport async function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||\n REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp\n ? \"app\"\n : isInstallation\n ? \"installation\"\n : isUserToServer\n ? \"user-to-server\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType,\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token),\n });\n};\n"],"names":[],"mappings":"AAAA,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAC7C,MAAM,qBAAqB,GAAG,OAAO,CAAC;AACtC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AACjC,eAAe,IAAI,CAAC,KAAK,EAAE;AAClC,IAAI,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AACjD,IAAI,MAAM,cAAc,GAAG,4BAA4B,CAAC,IAAI,CAAC,KAAK,CAAC;AACnE,QAAQ,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC1C,IAAI,MAAM,cAAc,GAAG,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC/D,IAAI,MAAM,SAAS,GAAG,KAAK;AAC3B,UAAU,KAAK;AACf,UAAU,cAAc;AACxB,cAAc,cAAc;AAC5B,cAAc,cAAc;AAC5B,kBAAkB,gBAAgB;AAClC,kBAAkB,OAAO,CAAC;AAC1B,IAAI,OAAO;AACX,QAAQ,IAAI,EAAE,OAAO;AACrB,QAAQ,KAAK,EAAE,KAAK;AACpB,QAAQ,SAAS;AACjB,KAAK,CAAC;AACN;;ACpBA;AACA;AACA;AACA;AACA;AACA,AAAO,SAAS,uBAAuB,CAAC,KAAK,EAAE;AAC/C,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;AACxC,QAAQ,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACjC,KAAK;AACL,IAAI,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;AAC5B,CAAC;;ACTM,eAAe,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE;AAC9D,IAAI,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AAC/D,IAAI,QAAQ,CAAC,OAAO,CAAC,aAAa,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;AACpE,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC7B,CAAC;;ACHW,MAAC,eAAe,GAAG,SAAS,eAAe,CAAC,KAAK,EAAE;AAC/D,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;AACpF,KAAK;AACL,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACnC,QAAQ,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;AACjG,KAAK;AACL,IAAI,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;AACpD,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;AACjD,QAAQ,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC;AACpC,KAAK,CAAC,CAAC;AACP,CAAC;;;;"}

View File

@ -0,0 +1,45 @@
{
"name": "@octokit/auth-token",
"description": "GitHub API token authentication for browsers and Node.js",
"version": "2.5.0",
"license": "MIT",
"files": [
"dist-*/",
"bin/"
],
"pika": true,
"sideEffects": false,
"keywords": [
"github",
"octokit",
"authentication",
"api"
],
"repository": "github:octokit/auth-token.js",
"dependencies": {
"@octokit/types": "^6.0.3"
},
"devDependencies": {
"@octokit/core": "^3.0.0",
"@octokit/request": "^5.3.0",
"@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.9.0",
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^27.0.0",
"fetch-mock": "^9.0.0",
"jest": "^27.0.0",
"prettier": "2.4.1",
"semantic-release": "^17.0.0",
"ts-jest": "^27.0.0-next.12",
"typescript": "^4.0.0"
},
"publishConfig": {
"access": "public"
},
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"main": "dist-node/index.js",
"module": "dist-web/index.js"
}

21
scripts/bot/node_modules/@octokit/core/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

440
scripts/bot/node_modules/@octokit/core/README.md generated vendored Normal file
View File

@ -0,0 +1,440 @@
# core.js
> Extendable client for GitHub's REST & GraphQL APIs
[![@latest](https://img.shields.io/npm/v/@octokit/core.svg)](https://www.npmjs.com/package/@octokit/core)
[![Build Status](https://github.com/octokit/core.js/workflows/Test/badge.svg)](https://github.com/octokit/core.js/actions?query=workflow%3ATest+branch%3Amaster)
<!-- toc -->
- [Usage](#usage)
- [REST API example](#rest-api-example)
- [GraphQL example](#graphql-example)
- [Options](#options)
- [Defaults](#defaults)
- [Authentication](#authentication)
- [Logging](#logging)
- [Hooks](#hooks)
- [Plugins](#plugins)
- [Build your own Octokit with Plugins and Defaults](#build-your-own-octokit-with-plugins-and-defaults)
- [LICENSE](#license)
<!-- tocstop -->
If you need a minimalistic library to utilize GitHub's [REST API](https://developer.github.com/v3/) and [GraphQL API](https://developer.github.com/v4/) which you can extend with plugins as needed, then `@octokit/core` is a great starting point.
If you don't need the Plugin API then using [`@octokit/request`](https://github.com/octokit/request.js/) or [`@octokit/graphql`](https://github.com/octokit/graphql.js/) directly is a good alternative.
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load <code>@octokit/core</code> directly from <a href="https://cdn.skypack.dev">cdn.skypack.dev</a>
```html
<script type="module">
import { Octokit } from "https://cdn.skypack.dev/@octokit/core";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/core</code>
```js
const { Octokit } = require("@octokit/core");
// or: import { Octokit } from "@octokit/core";
```
</td></tr>
</tbody>
</table>
### REST API example
```js
// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: `personal-access-token123` });
const response = await octokit.request("GET /orgs/{org}/repos", {
org: "octokit",
type: "private",
});
```
See [`@octokit/request`](https://github.com/octokit/request.js) for full documentation of the `.request` method.
### GraphQL example
```js
const octokit = new Octokit({ auth: `secret123` });
const response = await octokit.graphql(
`query ($login: String!) {
organization(login: $login) {
repositories(privacy: PRIVATE) {
totalCount
}
}
}`,
{ login: "octokit" }
);
```
See [`@octokit/graphql`](https://github.com/octokit/graphql.js) for full documentation of the `.graphql` method.
## Options
<table>
<thead align=left>
<tr>
<th>
name
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>options.authStrategy</code>
</th>
<td>
<code>Function<code>
</td>
<td>
Defaults to <a href="https://github.com/octokit/auth-token.js#readme"><code>@octokit/auth-token</code></a>. See <a href="#authentication">Authentication</a> below for examples.
</td>
</tr>
<tr>
<th>
<code>options.auth</code>
</th>
<td>
<code>String</code> or <code>Object</code>
</td>
<td>
See <a href="#authentication">Authentication</a> below for examples.
</td>
</tr>
<tr>
<th>
<code>options.baseUrl</code>
</th>
<td>
<code>String</code>
</td>
<td>
When using with GitHub Enterprise Server, set `options.baseUrl` to the root URL of the API. For example, if your GitHub Enterprise Server's hostname is `github.acme-inc.com`, then set `options.baseUrl` to `https://github.acme-inc.com/api/v3`. Example
```js
const octokit = new Octokit({
baseUrl: "https://github.acme-inc.com/api/v3",
});
```
</td></tr>
<tr>
<th>
<code>options.previews</code>
</th>
<td>
<code>Array of Strings</code>
</td>
<td>
Some REST API endpoints require preview headers to be set, or enable
additional features. Preview headers can be set on a per-request basis, e.g.
```js
octokit.request("POST /repos/{owner}/{repo}/pulls", {
mediaType: {
previews: ["shadow-cat"],
},
owner,
repo,
title: "My pull request",
base: "master",
head: "my-feature",
draft: true,
});
```
You can also set previews globally, by setting the `options.previews` option on the constructor. Example:
```js
const octokit = new Octokit({
previews: ["shadow-cat"],
});
```
</td></tr>
<tr>
<th>
<code>options.request</code>
</th>
<td>
<code>Object</code>
</td>
<td>
Set a default request timeout (`options.request.timeout`) or an [`http(s).Agent`](https://nodejs.org/api/http.html#http_class_http_agent) e.g. for proxy usage (Node only, `options.request.agent`).
There are more `options.request.*` options, see [`@octokit/request` options](https://github.com/octokit/request.js#request). `options.request` can also be set on a per-request basis.
</td></tr>
<tr>
<th>
<code>options.timeZone</code>
</th>
<td>
<code>String</code>
</td>
<td>
Sets the `Time-Zone` header which defines a timezone according to the [list of names from the Olson database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
```js
const octokit = new Octokit({
timeZone: "America/Los_Angeles",
});
```
The time zone header will determine the timezone used for generating the timestamp when creating commits. See [GitHub's Timezones documentation](https://developer.github.com/v3/#timezones).
</td></tr>
<tr>
<th>
<code>options.userAgent</code>
</th>
<td>
<code>String</code>
</td>
<td>
A custom user agent string for your app or library. Example
```js
const octokit = new Octokit({
userAgent: "my-app/v1.2.3",
});
```
</td></tr>
</tbody>
</table>
## Defaults
You can create a new Octokit class with customized default options.
```js
const MyOctokit = Octokit.defaults({
auth: "personal-access-token123",
baseUrl: "https://github.acme-inc.com/api/v3",
userAgent: "my-app/v1.2.3",
});
const octokit1 = new MyOctokit();
const octokit2 = new MyOctokit();
```
If you pass additional options to your new constructor, the options will be merged shallowly.
```js
const MyOctokit = Octokit.defaults({
foo: {
opt1: 1,
},
});
const octokit = new MyOctokit({
foo: {
opt2: 1,
},
});
// options will be { foo: { opt2: 1 }}
```
If you need a deep or conditional merge, you can pass a function instead.
```js
const MyOctokit = Octokit.defaults((options) => {
return {
foo: Object.assign({}, options.foo, { opt2: 1 }),
};
});
const octokit = new MyOctokit({
foo: { opt2: 1 },
});
// options will be { foo: { opt1: 1, opt2: 1 }}
```
Be careful about mutating the `options` object in the `Octokit.defaults` callback, as it can have unforeseen consequences.
## Authentication
Authentication is optional for some REST API endpoints accessing public data, but is required for GraphQL queries. Using authentication also increases your [API rate limit](https://developer.github.com/v3/#rate-limiting).
By default, Octokit authenticates using the [token authentication strategy](https://github.com/octokit/auth-token.js). Pass in a token using `options.auth`. It can be a personal access token, an OAuth token, an installation access token or a JSON Web Token for GitHub App authentication. The `Authorization` header will be set according to the type of token.
```js
import { Octokit } from "@octokit/core";
const octokit = new Octokit({
auth: "mypersonalaccesstoken123",
});
const { data } = await octokit.request("/user");
```
To use a different authentication strategy, set `options.authStrategy`. A list of authentication strategies is available at [octokit/authentication-strategies.js](https://github.com/octokit/authentication-strategies.js/#readme).
Example
```js
import { Octokit } from "@octokit/core";
import { createAppAuth } from "@octokit/auth-app";
const appOctokit = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: 123,
privateKey: process.env.PRIVATE_KEY,
},
});
const { data } = await appOctokit.request("/app");
```
The `.auth()` method returned by the current authentication strategy can be accessed at `octokit.auth()`. Example
```js
const { token } = await appOctokit.auth({
type: "installation",
installationId: 123,
});
```
## Logging
There are four built-in log methods
1. `octokit.log.debug(message[, additionalInfo])`
1. `octokit.log.info(message[, additionalInfo])`
1. `octokit.log.warn(message[, additionalInfo])`
1. `octokit.log.error(message[, additionalInfo])`
They can be configured using the [`log` client option](client-options). By default, `octokit.log.debug()` and `octokit.log.info()` are no-ops, while the other two call `console.warn()` and `console.error()` respectively.
This is useful if you build reusable [plugins](#plugins).
If you would like to make the log level configurable using an environment variable or external option, we recommend the [console-log-level](https://github.com/watson/console-log-level) package. Example
```js
const octokit = new Octokit({
log: require("console-log-level")({ level: "info" }),
});
```
## Hooks
You can customize Octokit's request lifecycle with hooks.
```js
octokit.hook.before("request", async (options) => {
validate(options);
});
octokit.hook.after("request", async (response, options) => {
console.log(`${options.method} ${options.url}: ${response.status}`);
});
octokit.hook.error("request", async (error, options) => {
if (error.status === 304) {
return findInCache(error.response.headers.etag);
}
throw error;
});
octokit.hook.wrap("request", async (request, options) => {
// add logic before, after, catch errors or replace the request altogether
return request(options);
});
```
See [before-after-hook](https://github.com/gr2m/before-after-hook#readme) for more documentation on hooks.
## Plugins
Octokits functionality can be extended using plugins. The `Octokit.plugin()` method accepts a plugin (or many) and returns a new constructor.
A plugin is a function which gets two arguments:
1. the current instance
2. the options passed to the constructor.
In order to extend `octokit`'s API, the plugin must return an object with the new methods.
```js
// index.js
const { Octokit } = require("@octokit/core")
const MyOctokit = Octokit.plugin(
require("./lib/my-plugin"),
require("octokit-plugin-example")
);
const octokit = new MyOctokit({ greeting: "Moin moin" });
octokit.helloWorld(); // logs "Moin moin, world!"
octokit.request("GET /"); // logs "GET / - 200 in 123ms"
// lib/my-plugin.js
module.exports = (octokit, options = { greeting: "Hello" }) => {
// hook into the request lifecycle
octokit.hook.wrap("request", async (request, options) => {
const time = Date.now();
const response = await request(options);
console.log(
`${options.method} ${options.url} ${response.status} in ${Date.now() -
time}ms`
);
return response;
});
// add a custom method
return {
helloWorld: () => console.log(`${options.greeting}, world!`);
}
};
```
## Build your own Octokit with Plugins and Defaults
You can build your own Octokit class with preset default options and plugins. In fact, this is mostly how the `@octokit/<context>` modules work, such as [`@octokit/action`](https://github.com/octokit/action.js):
```js
const { Octokit } = require("@octokit/core");
const MyActionOctokit = Octokit.plugin(
require("@octokit/plugin-paginate-rest"),
require("@octokit/plugin-throttling"),
require("@octokit/plugin-retry")
).defaults({
authStrategy: require("@octokit/auth-action"),
userAgent: `my-octokit-action/v1.2.3`,
});
const octokit = new MyActionOctokit();
const installations = await octokit.paginate("GET /app/installations");
```
## LICENSE
[MIT](LICENSE)

View File

@ -0,0 +1,176 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var universalUserAgent = require('universal-user-agent');
var beforeAfterHook = require('before-after-hook');
var request = require('@octokit/request');
var graphql = require('@octokit/graphql');
var authToken = require('@octokit/auth-token');
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const VERSION = "3.5.1";
const _excluded = ["authStrategy"];
class Octokit {
constructor(options = {}) {
const hook = new beforeAfterHook.Collection();
const requestDefaults = {
baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
}; // prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.request.defaults(requestDefaults);
this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign({
debug: () => {},
info: () => {},
warn: console.warn.bind(console),
error: console.error.bind(console)
}, options.log);
this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
// (2) If only `options.auth` is set, use the default token authentication strategy.
// (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
// TODO: type `options.auth` based on `options.authStrategy`.
if (!options.authStrategy) {
if (!options.auth) {
// (1)
this.auth = async () => ({
type: "unauthenticated"
});
} else {
// (2)
const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
} else {
const {
authStrategy
} = options,
otherOptions = _objectWithoutProperties(options, _excluded);
const auth = authStrategy(Object.assign({
request: this.request,
log: this.log,
// we pass the current octokit instance as well as its constructor options
// to allow for authentication strategies that return a new octokit instance
// that shares the same internal state as the current one. The original
// requirement for this was the "event-octokit" authentication strategy
// of https://github.com/probot/octokit-auth-probot.
octokit: this,
octokitOptions: otherOptions
}, options.auth)); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
} // apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor;
classConstructor.plugins.forEach(plugin => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
userAgent: `${options.userAgent} ${defaults.userAgent}`
} : null));
}
};
return OctokitWithDefaults;
}
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);
return NewOctokit;
}
}
Octokit.VERSION = VERSION;
Octokit.plugins = [];
exports.Octokit = Octokit;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,125 @@
import { getUserAgent } from "universal-user-agent";
import { Collection } from "before-after-hook";
import { request } from "@octokit/request";
import { withCustomRequest } from "@octokit/graphql";
import { createTokenAuth } from "@octokit/auth-token";
import { VERSION } from "./version";
export class Octokit {
constructor(options = {}) {
const hook = new Collection();
const requestDefaults = {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request"),
}),
mediaType: {
previews: [],
format: "",
},
};
// prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [
options.userAgent,
`octokit-core.js/${VERSION} ${getUserAgent()}`,
]
.filter(Boolean)
.join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.defaults(requestDefaults);
this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign({
debug: () => { },
info: () => { },
warn: console.warn.bind(console),
error: console.error.bind(console),
}, options.log);
this.hook = hook;
// (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
// (2) If only `options.auth` is set, use the default token authentication strategy.
// (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
// TODO: type `options.auth` based on `options.authStrategy`.
if (!options.authStrategy) {
if (!options.auth) {
// (1)
this.auth = async () => ({
type: "unauthenticated",
});
}
else {
// (2)
const auth = createTokenAuth(options.auth);
// @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
}
else {
const { authStrategy, ...otherOptions } = options;
const auth = authStrategy(Object.assign({
request: this.request,
log: this.log,
// we pass the current octokit instance as well as its constructor options
// to allow for authentication strategies that return a new octokit instance
// that shares the same internal state as the current one. The original
// requirement for this was the "event-octokit" authentication strategy
// of https://github.com/probot/octokit-auth-probot.
octokit: this,
octokitOptions: otherOptions,
}, options.auth));
// @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
// apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor;
classConstructor.plugins.forEach((plugin) => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent
? {
userAgent: `${options.userAgent} ${defaults.userAgent}`,
}
: null));
}
};
return OctokitWithDefaults;
}
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {
},
_a.plugins = currentPlugins.concat(newPlugins.filter((plugin) => !currentPlugins.includes(plugin))),
_a);
return NewOctokit;
}
}
Octokit.VERSION = VERSION;
Octokit.plugins = [];

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1 @@
export const VERSION = "3.5.1";

View File

@ -0,0 +1,30 @@
import { HookCollection } from "before-after-hook";
import { request } from "@octokit/request";
import { graphql } from "@octokit/graphql";
import { Constructor, Hooks, OctokitOptions, OctokitPlugin, ReturnTypeOf, UnionToIntersection } from "./types";
export declare class Octokit {
static VERSION: string;
static defaults<S extends Constructor<any>>(this: S, defaults: OctokitOptions | Function): S;
static plugins: OctokitPlugin[];
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin<S extends Constructor<any> & {
plugins: any[];
}, T extends OctokitPlugin[]>(this: S, ...newPlugins: T): S & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;
constructor(options?: OctokitOptions);
request: typeof request;
graphql: typeof graphql;
log: {
debug: (message: string, additionalInfo?: object) => any;
info: (message: string, additionalInfo?: object) => any;
warn: (message: string, additionalInfo?: object) => any;
error: (message: string, additionalInfo?: object) => any;
[key: string]: any;
};
hook: HookCollection<Hooks>;
auth: (...args: unknown[]) => Promise<unknown>;
}

View File

@ -0,0 +1,44 @@
import * as OctokitTypes from "@octokit/types";
import { RequestError } from "@octokit/request-error";
import { Octokit } from ".";
export declare type RequestParameters = OctokitTypes.RequestParameters;
export declare type OctokitOptions = {
authStrategy?: any;
auth?: any;
userAgent?: string;
previews?: string[];
baseUrl?: string;
log?: {
debug: (message: string) => unknown;
info: (message: string) => unknown;
warn: (message: string) => unknown;
error: (message: string) => unknown;
};
request?: OctokitTypes.RequestRequestOptions;
timeZone?: string;
[option: string]: any;
};
export declare type Constructor<T> = new (...args: any[]) => T;
export declare type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> = T extends AnyFunction ? ReturnType<T> : T extends AnyFunction[] ? UnionToIntersection<Exclude<ReturnType<T[number]>, void>> : never;
/**
* @author https://stackoverflow.com/users/2887218/jcalz
* @see https://stackoverflow.com/a/50375286/10325032
*/
export declare type UnionToIntersection<Union> = (Union extends any ? (argument: Union) => void : never) extends (argument: infer Intersection) => void ? Intersection : never;
declare type AnyFunction = (...args: any) => any;
export declare type OctokitPlugin = (octokit: Octokit, options: OctokitOptions) => {
[key: string]: any;
} | void;
export declare type Hooks = {
request: {
Options: Required<OctokitTypes.EndpointDefaults>;
Result: OctokitTypes.OctokitResponse<any>;
Error: RequestError | Error;
};
[key: string]: {
Options: unknown;
Result: unknown;
Error: unknown;
};
};
export {};

View File

@ -0,0 +1 @@
export declare const VERSION = "3.5.1";

View File

@ -0,0 +1,130 @@
import { getUserAgent } from 'universal-user-agent';
import { Collection } from 'before-after-hook';
import { request } from '@octokit/request';
import { withCustomRequest } from '@octokit/graphql';
import { createTokenAuth } from '@octokit/auth-token';
const VERSION = "3.5.1";
class Octokit {
constructor(options = {}) {
const hook = new Collection();
const requestDefaults = {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request"),
}),
mediaType: {
previews: [],
format: "",
},
};
// prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [
options.userAgent,
`octokit-core.js/${VERSION} ${getUserAgent()}`,
]
.filter(Boolean)
.join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.defaults(requestDefaults);
this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign({
debug: () => { },
info: () => { },
warn: console.warn.bind(console),
error: console.error.bind(console),
}, options.log);
this.hook = hook;
// (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
// (2) If only `options.auth` is set, use the default token authentication strategy.
// (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
// TODO: type `options.auth` based on `options.authStrategy`.
if (!options.authStrategy) {
if (!options.auth) {
// (1)
this.auth = async () => ({
type: "unauthenticated",
});
}
else {
// (2)
const auth = createTokenAuth(options.auth);
// @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
}
else {
const { authStrategy, ...otherOptions } = options;
const auth = authStrategy(Object.assign({
request: this.request,
log: this.log,
// we pass the current octokit instance as well as its constructor options
// to allow for authentication strategies that return a new octokit instance
// that shares the same internal state as the current one. The original
// requirement for this was the "event-octokit" authentication strategy
// of https://github.com/probot/octokit-auth-probot.
octokit: this,
octokitOptions: otherOptions,
}, options.auth));
// @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
// apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor;
classConstructor.plugins.forEach((plugin) => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent
? {
userAgent: `${options.userAgent} ${defaults.userAgent}`,
}
: null));
}
};
return OctokitWithDefaults;
}
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {
},
_a.plugins = currentPlugins.concat(newPlugins.filter((plugin) => !currentPlugins.includes(plugin))),
_a);
return NewOctokit;
}
}
Octokit.VERSION = VERSION;
Octokit.plugins = [];
export { Octokit };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

58
scripts/bot/node_modules/@octokit/core/package.json generated vendored Normal file
View File

@ -0,0 +1,58 @@
{
"name": "@octokit/core",
"description": "Extendable client for GitHub's REST & GraphQL APIs",
"version": "3.5.1",
"license": "MIT",
"files": [
"dist-*/",
"bin/"
],
"pika": true,
"sideEffects": false,
"keywords": [
"octokit",
"github",
"api",
"sdk",
"toolkit"
],
"repository": "github:octokit/core.js",
"dependencies": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.6.0",
"@octokit/request-error": "^2.0.5",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
},
"devDependencies": {
"@octokit/auth": "^3.0.1",
"@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.9.0",
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^26.0.0",
"@types/lolex": "^5.1.0",
"@types/node": "^14.0.4",
"@types/node-fetch": "^2.5.0",
"fetch-mock": "^9.0.0",
"http-proxy-agent": "^4.0.1",
"jest": "^27.0.0",
"lolex": "^6.0.0",
"prettier": "2.3.1",
"proxy": "^1.0.1",
"semantic-release": "^17.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^27.0.0",
"typescript": "^4.0.2"
},
"publishConfig": {
"access": "public"
},
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"main": "dist-node/index.js",
"module": "dist-web/index.js"
}

21
scripts/bot/node_modules/@octokit/endpoint/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

421
scripts/bot/node_modules/@octokit/endpoint/README.md generated vendored Normal file
View File

@ -0,0 +1,421 @@
# endpoint.js
> Turns GitHub REST API endpoints into generic request options
[![@latest](https://img.shields.io/npm/v/@octokit/endpoint.svg)](https://www.npmjs.com/package/@octokit/endpoint)
![Build Status](https://github.com/octokit/endpoint.js/workflows/Test/badge.svg)
`@octokit/endpoint` combines [GitHub REST API routes](https://developer.github.com/v3/) with your parameters and turns them into generic request options that can be used in any request library.
<!-- update table of contents by running `npx markdown-toc README.md -i` -->
<!-- toc -->
- [Usage](#usage)
- [API](#api)
- [`endpoint(route, options)` or `endpoint(options)`](#endpointroute-options-or-endpointoptions)
- [`endpoint.defaults()`](#endpointdefaults)
- [`endpoint.DEFAULTS`](#endpointdefaults)
- [`endpoint.merge(route, options)` or `endpoint.merge(options)`](#endpointmergeroute-options-or-endpointmergeoptions)
- [`endpoint.parse()`](#endpointparse)
- [Special cases](#special-cases)
- [The `data` parameter set request body directly](#the-data-parameter-%E2%80%93-set-request-body-directly)
- [Set parameters for both the URL/query and the request body](#set-parameters-for-both-the-urlquery-and-the-request-body)
- [LICENSE](#license)
<!-- tocstop -->
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load <code>@octokit/endpoint</code> directly from <a href="https://cdn.skypack.dev">cdn.skypack.dev</a>
```html
<script type="module">
import { endpoint } from "https://cdn.skypack.dev/@octokit/endpoint";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/endpoint</code>
```js
const { endpoint } = require("@octokit/endpoint");
// or: import { endpoint } from "@octokit/endpoint";
```
</td></tr>
</tbody>
</table>
Example for [List organization repositories](https://developer.github.com/v3/repos/#list-organization-repositories)
```js
const requestOptions = endpoint("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
});
```
The resulting `requestOptions` looks as follows
```json
{
"method": "GET",
"url": "https://api.github.com/orgs/octokit/repos?type=private",
"headers": {
"accept": "application/vnd.github.v3+json",
"authorization": "token 0000000000000000000000000000000000000001",
"user-agent": "octokit/endpoint.js v1.2.3"
}
}
```
You can pass `requestOptions` to common request libraries
```js
const { url, ...options } = requestOptions;
// using with fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
fetch(url, options);
// using with request (https://github.com/request/request)
request(requestOptions);
// using with got (https://github.com/sindresorhus/got)
got[options.method](url, options);
// using with axios
axios(requestOptions);
```
## API
### `endpoint(route, options)` or `endpoint(options)`
<table>
<thead align=left>
<tr>
<th>
name
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>route</code>
</th>
<td>
String
</td>
<td>
If set, it has to be a string consisting of URL and the request method, e.g., <code>GET /orgs/{org}</code>. If its set to a URL, only the method defaults to <code>GET</code>.
</td>
</tr>
<tr>
<th>
<code>options.method</code>
</th>
<td>
String
</td>
<td>
<strong>Required unless <code>route</code> is set.</strong> Any supported <a href="https://developer.github.com/v3/#http-verbs">http verb</a>. <em>Defaults to <code>GET</code></em>.
</td>
</tr>
<tr>
<th>
<code>options.url</code>
</th>
<td>
String
</td>
<td>
<strong>Required unless <code>route</code> is set.</strong> A path or full URL which may contain <code>:variable</code> or <code>{variable}</code> placeholders,
e.g., <code>/orgs/{org}/repos</code>. The <code>url</code> is parsed using <a href="https://github.com/bramstein/url-template">url-template</a>.
</td>
</tr>
<tr>
<th>
<code>options.baseUrl</code>
</th>
<td>
String
</td>
<td>
<em>Defaults to <code>https://api.github.com</code></em>.
</td>
</tr>
<tr>
<th>
<code>options.headers</code>
</th>
<td>
Object
</td>
<td>
Custom headers. Passed headers are merged with defaults:<br>
<em><code>headers['user-agent']</code> defaults to <code>octokit-endpoint.js/1.2.3</code> (where <code>1.2.3</code> is the released version)</em>.<br>
<em><code>headers['accept']</code> defaults to <code>application/vnd.github.v3+json</code></em>.<br>
</td>
</tr>
<tr>
<th>
<code>options.mediaType.format</code>
</th>
<td>
String
</td>
<td>
Media type param, such as <code>raw</code>, <code>diff</code>, or <code>text+json</code>. See <a href="https://developer.github.com/v3/media/">Media Types</a>. Setting <code>options.mediaType.format</code> will amend the <code>headers.accept</code> value.
</td>
</tr>
<tr>
<th>
<code>options.mediaType.previews</code>
</th>
<td>
Array of Strings
</td>
<td>
Name of previews, such as <code>mercy</code>, <code>symmetra</code>, or <code>scarlet-witch</code>. See <a href="https://developer.github.com/v3/previews/">API Previews</a>. If <code>options.mediaType.previews</code> was set as default, the new previews will be merged into the default ones. Setting <code>options.mediaType.previews</code> will amend the <code>headers.accept</code> value. <code>options.mediaType.previews</code> will be merged with an existing array set using <code>.defaults()</code>.
</td>
</tr>
<tr>
<th>
<code>options.data</code>
</th>
<td>
Any
</td>
<td>
Set request body directly instead of setting it to JSON based on additional parameters. See <a href="#data-parameter">"The <code>data</code> parameter"</a> below.
</td>
</tr>
<tr>
<th>
<code>options.request</code>
</th>
<td>
Object
</td>
<td>
Pass custom meta information for the request. The <code>request</code> object will be returned as is.
</td>
</tr>
</tbody>
</table>
All other options will be passed depending on the `method` and `url` options.
1. If the option key has a placeholder in the `url`, it will be used as the replacement. For example, if the passed options are `{url: '/orgs/{org}/repos', org: 'foo'}` the returned `options.url` is `https://api.github.com/orgs/foo/repos`.
2. If the `method` is `GET` or `HEAD`, the option is passed as a query parameter.
3. Otherwise, the parameter is passed in the request body as a JSON key.
**Result**
`endpoint()` is a synchronous method and returns an object with the following keys:
<table>
<thead align=left>
<tr>
<th>
key
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th><code>method</code></th>
<td>String</td>
<td>The http method. Always lowercase.</td>
</tr>
<tr>
<th><code>url</code></th>
<td>String</td>
<td>The url with placeholders replaced with passed parameters.</td>
</tr>
<tr>
<th><code>headers</code></th>
<td>Object</td>
<td>All header names are lowercased.</td>
</tr>
<tr>
<th><code>body</code></th>
<td>Any</td>
<td>The request body if one is present. Only for <code>PATCH</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code> requests.</td>
</tr>
<tr>
<th><code>request</code></th>
<td>Object</td>
<td>Request meta option, it will be returned as it was passed into <code>endpoint()</code></td>
</tr>
</tbody>
</table>
### `endpoint.defaults()`
Override or set default options. Example:
```js
const request = require("request");
const myEndpoint = require("@octokit/endpoint").defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
headers: {
"user-agent": "myApp/1.2.3",
authorization: `token 0000000000000000000000000000000000000001`,
},
org: "my-project",
per_page: 100,
});
request(myEndpoint(`GET /orgs/{org}/repos`));
```
You can call `.defaults()` again on the returned method, the defaults will cascade.
```js
const myProjectEndpoint = endpoint.defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
headers: {
"user-agent": "myApp/1.2.3",
},
org: "my-project",
});
const myProjectEndpointWithAuth = myProjectEndpoint.defaults({
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
});
```
`myProjectEndpointWithAuth` now defaults the `baseUrl`, `headers['user-agent']`,
`org` and `headers['authorization']` on top of `headers['accept']` that is set
by the global default.
### `endpoint.DEFAULTS`
The current default options.
```js
endpoint.DEFAULTS.baseUrl; // https://api.github.com
const myEndpoint = endpoint.defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
});
myEndpoint.DEFAULTS.baseUrl; // https://github-enterprise.acme-inc.com/api/v3
```
### `endpoint.merge(route, options)` or `endpoint.merge(options)`
Get the defaulted endpoint options, but without parsing them into request options:
```js
const myProjectEndpoint = endpoint.defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
headers: {
"user-agent": "myApp/1.2.3",
},
org: "my-project",
});
myProjectEndpoint.merge("GET /orgs/{org}/repos", {
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
org: "my-secret-project",
type: "private",
});
// {
// baseUrl: 'https://github-enterprise.acme-inc.com/api/v3',
// method: 'GET',
// url: '/orgs/{org}/repos',
// headers: {
// accept: 'application/vnd.github.v3+json',
// authorization: `token 0000000000000000000000000000000000000001`,
// 'user-agent': 'myApp/1.2.3'
// },
// org: 'my-secret-project',
// type: 'private'
// }
```
### `endpoint.parse()`
Stateless method to turn endpoint options into request options. Calling
`endpoint(options)` is the same as calling `endpoint.parse(endpoint.merge(options))`.
## Special cases
<a name="data-parameter"></a>
### The `data` parameter set request body directly
Some endpoints such as [Render a Markdown document in raw mode](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode) dont have parameters that are sent as request body keys, instead, the request body needs to be set directly. In these cases, set the `data` parameter.
```js
const options = endpoint("POST /markdown/raw", {
data: "Hello world github/linguist#1 **cool**, and #1!",
headers: {
accept: "text/html;charset=utf-8",
"content-type": "text/plain",
},
});
// options is
// {
// method: 'post',
// url: 'https://api.github.com/markdown/raw',
// headers: {
// accept: 'text/html;charset=utf-8',
// 'content-type': 'text/plain',
// 'user-agent': userAgent
// },
// body: 'Hello world github/linguist#1 **cool**, and #1!'
// }
```
### Set parameters for both the URL/query and the request body
There are API endpoints that accept both query parameters as well as a body. In that case, you need to add the query parameters as templates to `options.url`, as defined in the [RFC 6570 URI Template specification](https://tools.ietf.org/html/rfc6570).
Example
```js
endpoint(
"POST https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}",
{
name: "example.zip",
label: "short description",
headers: {
"content-type": "text/plain",
"content-length": 14,
authorization: `token 0000000000000000000000000000000000000001`,
},
data: "Hello, world!",
}
);
```
## LICENSE
[MIT](LICENSE)

View File

@ -0,0 +1,390 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var isPlainObject = require('is-plain-object');
var universalUserAgent = require('universal-user-agent');
function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach(key => {
if (isPlainObject.isPlainObject(options[key])) {
if (!(key in defaults)) Object.assign(result, {
[key]: options[key]
});else result[key] = mergeDeep(defaults[key], options[key]);
} else {
Object.assign(result, {
[key]: options[key]
});
}
});
return result;
}
function removeUndefinedProperties(obj) {
for (const key in obj) {
if (obj[key] === undefined) {
delete obj[key];
}
}
return obj;
}
function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? {
method,
url
} : {
url: method
}, options);
} else {
options = Object.assign({}, route);
} // lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
removeUndefinedProperties(options);
removeUndefinedProperties(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
return mergedOptions;
}
function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return url + separator + names.map(name => {
if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
}
return `${name}=${encodeURIComponent(parameters[name])}`;
}).join("&");
}
const urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
function omit(object, keysToOmit) {
return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
}
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key],
result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
} else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
} else {
return values.join(",");
}
} else {
return encodeReserved(literal);
}
});
}
function parse(options) {
// https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
let headers = Object.assign({}, options.headers);
let body;
let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url);
url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) {
url = options.baseUrl + url;
}
const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequest) {
if (options.mediaType.format) {
// e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
}
if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
return `application/vnd.github.${preview}-preview${format}`;
}).join(",");
}
} // for GET/HEAD requests, set URL query parameters from remaining parameters
// for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
} else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
} else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
} else {
headers["content-length"] = 0;
}
}
} // default content-type for JSON if body is set
if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8";
} // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
// fetch does not allow to set `content-length` header, but we can set body to an empty string
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = "";
} // Only return body/request keys if present
return Object.assign({
method,
url,
headers
}, typeof body !== "undefined" ? {
body
} : null, options.request ? {
request: options.request
} : null);
}
function endpointWithDefaults(defaults, route, options) {
return parse(merge(defaults, route, options));
}
function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS = merge(oldDefaults, newDefaults);
const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
return Object.assign(endpoint, {
DEFAULTS,
defaults: withDefaults.bind(null, DEFAULTS),
merge: merge.bind(null, DEFAULTS),
parse
});
}
const VERSION = "6.0.12";
const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property.
const DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: "",
previews: []
}
};
const endpoint = withDefaults(null, DEFAULTS);
exports.endpoint = endpoint;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,17 @@
import { getUserAgent } from "universal-user-agent";
import { VERSION } from "./version";
const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
// DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property.
export const DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent,
},
mediaType: {
format: "",
previews: [],
},
};

View File

@ -0,0 +1,5 @@
import { merge } from "./merge";
import { parse } from "./parse";
export function endpointWithDefaults(defaults, route, options) {
return parse(merge(defaults, route, options));
}

View File

@ -0,0 +1,3 @@
import { withDefaults } from "./with-defaults";
import { DEFAULTS } from "./defaults";
export const endpoint = withDefaults(null, DEFAULTS);

View File

@ -0,0 +1,26 @@
import { lowercaseKeys } from "./util/lowercase-keys";
import { mergeDeep } from "./util/merge-deep";
import { removeUndefinedProperties } from "./util/remove-undefined-properties";
export function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? { method, url } : { url: method }, options);
}
else {
options = Object.assign({}, route);
}
// lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers);
// remove properties with undefined values before merging
removeUndefinedProperties(options);
removeUndefinedProperties(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options);
// mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews
.filter((preview) => !mergedOptions.mediaType.previews.includes(preview))
.concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map((preview) => preview.replace(/-preview/, ""));
return mergedOptions;
}

View File

@ -0,0 +1,81 @@
import { addQueryParameters } from "./util/add-query-parameters";
import { extractUrlVariableNames } from "./util/extract-url-variable-names";
import { omit } from "./util/omit";
import { parseUrl } from "./util/url-template";
export function parse(options) {
// https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase();
// replace :varname with {varname} to make it RFC 6570 compatible
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
let headers = Object.assign({}, options.headers);
let body;
let parameters = omit(options, [
"method",
"baseUrl",
"url",
"headers",
"request",
"mediaType",
]);
// extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url);
url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) {
url = options.baseUrl + url;
}
const omittedParameters = Object.keys(options)
.filter((option) => urlVariableNames.includes(option))
.concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequest) {
if (options.mediaType.format) {
// e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
headers.accept = headers.accept
.split(/,/)
.map((preview) => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`))
.join(",");
}
if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader
.concat(options.mediaType.previews)
.map((preview) => {
const format = options.mediaType.format
? `.${options.mediaType.format}`
: "+json";
return `application/vnd.github.${preview}-preview${format}`;
})
.join(",");
}
}
// for GET/HEAD requests, set URL query parameters from remaining parameters
// for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
}
else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
}
else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
}
else {
headers["content-length"] = 0;
}
}
}
// default content-type for JSON if body is set
if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8";
}
// GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
// fetch does not allow to set `content-length` header, but we can set body to an empty string
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = "";
}
// Only return body/request keys if present
return Object.assign({ method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null);
}

View File

@ -0,0 +1,17 @@
export function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return (url +
separator +
names
.map((name) => {
if (name === "q") {
return ("q=" + parameters.q.split("+").map(encodeURIComponent).join("+"));
}
return `${name}=${encodeURIComponent(parameters[name])}`;
})
.join("&"));
}

View File

@ -0,0 +1,11 @@
const urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
}
export function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}

View File

@ -0,0 +1,9 @@
export function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}

View File

@ -0,0 +1,16 @@
import { isPlainObject } from "is-plain-object";
export function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach((key) => {
if (isPlainObject(options[key])) {
if (!(key in defaults))
Object.assign(result, { [key]: options[key] });
else
result[key] = mergeDeep(defaults[key], options[key]);
}
else {
Object.assign(result, { [key]: options[key] });
}
});
return result;
}

View File

@ -0,0 +1,8 @@
export function omit(object, keysToOmit) {
return Object.keys(object)
.filter((option) => !keysToOmit.includes(option))
.reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
}

View File

@ -0,0 +1,8 @@
export function removeUndefinedProperties(obj) {
for (const key in obj) {
if (obj[key] === undefined) {
delete obj[key];
}
}
return obj;
}

View File

@ -0,0 +1,164 @@
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str
.split(/(%[0-9A-Fa-f]{2})/g)
.map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
})
.join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value =
operator === "+" || operator === "#"
? encodeReserved(value)
: encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
}
else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key], result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
}
else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
}
else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
}
else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
}
else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
}
else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
}
else if (value === "") {
result.push("");
}
}
return result;
}
export function parseUrl(template) {
return {
expand: expand.bind(null, template),
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
}
else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
}
else {
return values.join(",");
}
}
else {
return encodeReserved(literal);
}
});
}

View File

@ -0,0 +1 @@
export const VERSION = "6.0.12";

View File

@ -0,0 +1,13 @@
import { endpointWithDefaults } from "./endpoint-with-defaults";
import { merge } from "./merge";
import { parse } from "./parse";
export function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS = merge(oldDefaults, newDefaults);
const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
return Object.assign(endpoint, {
DEFAULTS,
defaults: withDefaults.bind(null, DEFAULTS),
merge: merge.bind(null, DEFAULTS),
parse,
});
}

View File

@ -0,0 +1,2 @@
import { EndpointDefaults } from "@octokit/types";
export declare const DEFAULTS: EndpointDefaults;

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