Skip to content

Commit

Permalink
Support custom headers
Browse files Browse the repository at this point in the history
  • Loading branch information
omrilotan committed Jan 16, 2024
1 parent d66c58b commit e717532
Show file tree
Hide file tree
Showing 14 changed files with 333 additions and 226 deletions.
5 changes: 0 additions & 5 deletions .eslintrc

This file was deleted.

40 changes: 26 additions & 14 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,33 @@ on:
jobs:
build:
runs-on: ubuntu-latest
permissions:
actions: read
contents: write
strategy:
matrix:
node-version:
- '16'
- "20"
steps:
- uses: actions/checkout@v1
- name: Install dependencies
run: npm i
- name: Lint code
run: npm run lint
- name: Add NPM token
if: github.ref == 'refs/heads/main'
run: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Build and Publish
if: github.ref == 'refs/heads/main'
run: npx @lets/publish
- uses: actions/checkout@v4
- run: npm i
- run: npm run format
- name: commit auto fixes
env:
USERNAME: ${{ github.actor }}
BRANCH: ${{ github.ref_name }}
REPO: ${{ github.repository }}
run: |
if [ "$(git diff --quiet && echo 0 || echo $?)" -gt 0 ]; then
git config --global user.email "${USERNAME}@users.noreply.github.com" --replace-all
git config --global user.name "$USERNAME" --replace-all
git commit -am "😎 Autofix"
git remote set-url origin https://github.com/$REPO.git
git push origin $BRANCH
exit 1
fi
- name: Build and Publish
if: github.ref == 'refs/heads/main'
run: |
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
npx @lets/publish
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
16
20
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Changelog

## [2.0.0](https://github.com/omrilotan/isbot/compare/v1.3.7...v2.0.0)

- Support adding custom headers to HTTP requests (see help)
- Drop support for EOL Node.js engines
- Change import to named (consuming as a module is now `import { colombo } from 'colombo'`)
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,26 @@
## 🕵️‍♂️ Use source-map to view Javascript source code from CLI

Run and follow instructions:

```bash
npx colombo
```

![](https://user-images.githubusercontent.com/516342/103102893-ef27da00-4626-11eb-928a-9c67c077520d.gif)

```bash
npx colombo [https://website.com/bundle.js:line:column]
$ colombo [file[:line[:column]]] [options]

Examples:

$ colombo --help
$ colombo https://cdn.example.com/app.d0892a20d266460d6c63.js
$ colombo https://cdn.example.com/app.d0892a20d266460d6c63.js:1:9694
$ colombo https://cdn.example.com/app.d0892a20d266460d6c63.js:1:9694 -H "Access-Token: 1234"

Options:
--header, -H "key: value" Add a header to the request
--version, -V Show version number
--help Show help
```
265 changes: 160 additions & 105 deletions bin.js
Original file line number Diff line number Diff line change
@@ -1,135 +1,190 @@
#!/usr/bin/env node

const { prompt } = require('inquirer');
const axios = require('axios');
const { bold, red } = require('chalk');
const { satisfies } = require('semver');
const { getSourceCodeMapUrl } = require('./lib/getSourceCodeMapUrl');
const { loader } = require('./lib/loader');
const { update } = require('./lib/update');
const {
version,
homepage,
dependencies: { axios: axiosVersion },
engines: { node },
bugs: { url: bugUrl },
} = require('./package.json');

if (!satisfies(process.version, node)) {
console.error(new Error(`This node version (${process.version}) is not supported (${node}).`));
process.exit(1);
}

const colombo = require('.');

Object.assign(
axios.defaults.headers.common,
{ 'User-Agent': `axios/${axiosVersion.replace(/\W/, '')}; (compatible; Colombo/${version}; bot; +${homepage})` },
);

start().then(console.log).catch(error => {
console.log('\n');
if (typeof error.toJSON === 'function') {
console.error(error.toJSON());
return;
}
error.message = red(error.message);
console.error(error);

console.log(`
I can see you were not successful. Feel free to ${bold('submit an issue')}
${bugUrl}`);
});
import { parseArgs } from "node:util";
import { readFile } from "node:fs/promises";
import inquirer from "inquirer";
import chalk from "chalk";
import semver from "semver";
import { getSourceCodeMapUrl } from "./lib/getSourceCodeMapUrl/index.js";
import { loader } from "./lib/loader/index.js";
import { update } from "./lib/update/index.js";

const { satisfies } = semver;
const { bold, red } = chalk;
const { prompt } = inquirer;

let updateMessage;
start();

async function start() {
try {
update().then(message => {
updateMessage = message;
}).catch(() => null);

const [ arg = '' ] = process.argv.slice(2);
const packageJson = await readFile(
new URL("./package.json", import.meta.url),
"utf8",
);
const {
name,
version,
homepage,
dependencies: {},
engines: { node },
bugs: { url: bugUrl },
} = JSON.parse(packageJson);

if (!satisfies(process.version, node)) {
console.error(
new Error(
`This node version (${process.version}) is not supported (${node}).`,
),
);
process.exit(1);
}

const { file } = await prompt(
[
{
name: 'file',
message: 'File URL (optional)',
type: 'input',
default: arg,
try {
const { colombo } = await import("./index.js");

// Lazy call to update. Intentional race condition.
update({ name, version })
.then(
(message) => message && process.on("exit", () => console.log(message)),
)
.catch(() => null);

const {
values: { header = [], help = false, version: showVersion = false },
positionals: [arg = ""],
} = parseArgs({
args: process.argv.slice(2),
options: {
header: {
type: "string",
short: "H",
multiple: true,
},
],
);
version: {
type: "boolean",
short: "V",
},
help: {
type: "boolean",
},
},
allowPositionals: true,
strict: false,
});

if (help) {
console.log(await readFile(new URL("./man", import.meta.url), "utf8"));
process.exit(0);
}
if (showVersion) {
console.log([name, version].join("@"));
process.exit(0);
}

const { file } = await prompt([
{
name: "file",
message: "File URL (optional)",
type: "input",
default: arg,
},
]);

const match = file.match(/:(?<line>\d+):(?<column>\d+)$/);
const { groups = { line: undefined, column: undefined, file } } = match || {};
const clean = file.replace(/:\d+:\d+$/, '').replace(/\?.*/, '');
const { groups = { line: undefined, column: undefined, file } } =
match || {};
const clean = file.replace(/:\d+:\d+$/, "").replace(/\?.*/, "");
let url;

const headers = new Headers(
header.map((header) => header.split(":").map((value) => value.trim())),
);
if (!headers.has("User-Agent")) {
headers.set(
"User-Agent",
`node (compatible; Colombo/${version}; bot; +${homepage})`,
);
}
if (clean) {
loader.start('Load file');
const { data: code } = await axios({ method: 'get', url: clean });
loader.start("Load file");
const response = await fetch(clean, { headers });
if (!response.ok) {
throw new Error(
`Failed to load file ${clean}: ${response.status} ${response.statusText}`,
);
}
const code = await response.text();
loader.end();
const mapUrl = getSourceCodeMapUrl(code, clean);

if (mapUrl) {
({ url } = await prompt([ {
name: 'url',
message: 'Source map (found)',
type: 'input',
default: mapUrl,
validate: Boolean,
} ])
);
({ url } = await prompt([
{
name: "url",
message: "Source map (found)",
type: "input",
default: mapUrl,
validate: Boolean,
},
]));
} else {
({ url } = await prompt([ {
name: 'url',
message: 'Source map (assumed)',
type: 'input',
default: clean + '.map',
validate: Boolean,
} ])
);
({ url } = await prompt([
{
name: "url",
message: "Source map (assumed)",
type: "input",
default: clean + ".map",
validate: Boolean,
},
]));
}
} else {
({ url } = await prompt([ {
name: 'url',
message: 'Source map',
type: 'input',
validate: Boolean,
} ])
);
({ url } = await prompt([
{
name: "url",
message: "Source map",
type: "input",
validate: Boolean,
},
]));
}

if (!url) {
throw new Error('Source-map is a must');
throw new Error("Source-map is a must");
}

const { column, line } = await prompt(
[
{
name: 'line',
message: 'Line number',
type: 'number',
default: groups.line || 1,
},
{
name: 'column',
message: 'Column number',
type: 'number',
default: groups.column || 1,
},
],
);

loader.start('Load source map');
const { column, line } = await prompt([
{
name: "line",
message: "Line number",
type: "number",
default: groups.line || 1,
},
{
name: "column",
message: "Column number",
type: "number",
default: groups.column || 1,
},
]);

loader.start("Load source map");
const result = await colombo({ url, line, column });
loader.end();

return [ result, updateMessage ].filter(Boolean).join('\n');
console.log(result);
process.exit(0);
} catch (error) {
loader.end();
throw error;
console.log("\n");
if (typeof error.toJSON === "function") {
console.error(error.toJSON());
process.exit(1);
}
error.message = red(error.message);
console.error(error);

console.log(`
I can see you were not successful. Feel free to ${bold("submit an issue")}
${bugUrl}`);
process.exit(1);
}
}
Loading

0 comments on commit e717532

Please sign in to comment.