Skip to content

Commit

Permalink
feat: rewrite in ESModules (#407)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Rewrite to use ESModules instead of CommonJS
Co-authored-by: Gregor Martynus <39992+gr2m@users.noreply.github.com>
Co-authored-by: Lucas Fiegl <iovoid4@gmail.com>
  • Loading branch information
wolfy1339 committed Jun 13, 2021
1 parent 4e22625 commit b3a45cf
Show file tree
Hide file tree
Showing 90 changed files with 434 additions and 431 deletions.
64 changes: 36 additions & 28 deletions bin/record.js
@@ -1,39 +1,47 @@
#!/usr/bin/env node

// run with "DEBUG=axios" to see debug logs
require("axios-debug-log")({
request: function(debug, config) {
import axiosDebugLog from "axios-debug-log";
axiosDebugLog({
request: function (debug, config) {
debug(`${config.method.toUpperCase()} ${config.url}`);
},
response: () => {},
error: () => {}
error: () => {},
});

const axios = require("axios");
const Bottleneck = require("bottleneck");
const chalk = require("chalk");
const cloneDeep = require("lodash/cloneDeep");
const { diff, diffString } = require("json-diff");
const glob = require("glob");
const humanize = require("humanize-string");

const normalize = require("../lib/normalize");
const read = require("../lib/read");
const recordScenario = require("../lib/record-scenario");
const write = require("../lib/write");

const argv = require("minimist")(process.argv.slice(2), {
boolean: ["update", "test-cached"]
import axios from "axios";
import Bottleneck from "bottleneck";
import chalk from "chalk";
import cloneDeep from "lodash/cloneDeep.js";
import { diff, diffString } from "json-diff";
import glob from "glob";
import humanize from "humanize-string";
import minimist from "minimist";

import normalize from "../lib/normalize/index.js";
import read from "../lib/read.js";
import recordScenario from "../lib/record-scenario.js";
import write from "../lib/write.js";

const argv = minimist(process.argv.slice(2), {
boolean: ["update", "test-cached"],
});
const doUpdate = argv.update;
const selectedScenarios = argv._;
const hasSelectedScenarios = selectedScenarios.length > 0;

console.log(`hasSelectedScenarios`);
console.log(hasSelectedScenarios);

const scenarios = hasSelectedScenarios
? selectedScenarios
: glob.sync("scenarios/**/record.js");
const diffs = [];

console.log(`scenarios`);
console.log(scenarios);

// run scenarios one by one
scenarios
.reduce(async (promise, scenarioPath) => {
Expand All @@ -50,16 +58,16 @@ scenarios

const request = axios.create({
baseURL: `https://${domain}`,
maxRedirects: 0 // record redirects explicitly
maxRedirects: 0, // record redirects explicitly
});

// throttle writing requests
// https://developer.github.com/v3/guides/best-practices-for-integrators/#dealing-with-abuse-rate-limits
const limiter = new Bottleneck({
maxConcurrent: 1,
minTime: 3000
minTime: 3000,
});
request.interceptors.request.use(config => {
request.interceptors.request.use((config) => {
if (
!["POST", "PATCH", "PUT", "DELETE"].includes(
config.method.toUpperCase()
Expand All @@ -73,20 +81,20 @@ scenarios

// set strict validation header, remove once stricter validations are applied
// to all requests: https://developer.github.com/changes/2018-11-07-strict-validation/
request.interceptors.request.use(config => {
request.interceptors.request.use((config) => {
config.headers.Accept = `${config.headers.Accept},application/vnd.github.speedy-preview+json`;
return config;
});

const oldNormalizedFixtures = await read(fixtureName);
const newRawFixtures = await recordScenario({
request: request,
scenario: require(`../scenarios/${fixtureName}/record`)
scenario: (await import(`../scenarios/${fixtureName}/record.js`)).default,
});

const scenarioState = {
commitSha: {}, // map original commit sha hashes to normalized commit hashes
ids: {}
ids: {},
};

const newNormalizedFixtures = await Promise.all(
Expand All @@ -107,15 +115,15 @@ scenarios
changes: fixturesDiffs,
newNormalizedFixtures,
oldNormalizedFixtures,
newRawFixtures
newRawFixtures,
});

if (fixturesDiffs[0][0] === "-") {
if (doUpdate) {
console.log("📼 New fixtures recorded");
return write(fixtureName, {
normalized: newNormalizedFixtures,
raw: newRawFixtures
raw: newRawFixtures,
});
}
console.log(`❌ "${fixtureName}" looks like a new fixture`);
Expand All @@ -126,7 +134,7 @@ scenarios
console.log("📼 Fixture updates recorded");
return write(fixtureName, {
normalized: newNormalizedFixtures,
raw: newRawFixtures
raw: newRawFixtures,
});
}

Expand All @@ -152,7 +160,7 @@ scenarios
process.exit(1);
})

.catch(error => {
.catch((error) => {
if (!error.response) {
console.log(error);
process.exit(1);
Expand Down
45 changes: 24 additions & 21 deletions bin/remove-temporary-repositories.js
@@ -1,32 +1,35 @@
#!/usr/bin/env node

const axios = require('axios')
import axios from "axios";

const env = require('../lib/env')
const temporaryRepository = require('../lib/temporary-repository')
import env from "../lib/env.js";
import { regex } from "../lib/temporary-repository.js";

const github = axios.create({
baseURL: 'https://api.github.com',
baseURL: "https://api.github.com",
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${env.FIXTURES_USER_A_TOKEN_FULL_ACCESS}`
}
})
Accept: "application/vnd.github.v3+json",
Authorization: `token ${env.FIXTURES_USER_A_TOKEN_FULL_ACCESS}`,
},
});

github.get('/orgs/octokit-fixture-org/repos')
github
.get("/orgs/octokit-fixture-org/repos")

.then(result => {
return Promise.all(result.data
.map(repository => repository.name)
.filter(name => temporaryRepository.regex.test(name))
.map(name => {
return github.delete(`/repos/octokit-fixture-org/${name}`)
.then((result) => {
return Promise.all(
result.data
.map((repository) => repository.name)
.filter((name) => regex.test(name))
.map((name) => {
return github
.delete(`/repos/octokit-fixture-org/${name}`)

.then(() => {
console.log(`✅ ${name} deleted`)
})
})
)
.then(() => {
console.log(`✅ ${name} deleted`);
});
})
);
})

.catch(console.log)
.catch(console.log);
39 changes: 19 additions & 20 deletions index.js
@@ -1,22 +1,24 @@
const assert = require("assert");
const { URL } = require("url");

const cloneDeep = require("lodash/cloneDeep");
const merge = require("lodash/merge");
const pick = require("lodash/pick");
const nock = require("nock");
const headers = require("./lib/headers");
const diffString = require("json-diff").diffString;

module.exports = {
import assert from "assert";
import { URL } from "url";
import cloneDeep from "lodash/cloneDeep.js";
import merge from "lodash/merge.js";
import pick from "lodash/pick.js";
import nock from "nock";
import headers from "./lib/headers.js";
import { diffString } from "json-diff";
import { readFileSync } from "fs";

export default {
// don’t use short syntax for node@4 compatibility
get: get,
mock: mock,
nock: nock,
get,
mock,
nock,
};

function get(name) {
return require(`./scenarios/${name}/normalized-fixture.json`);
return JSON.parse(
readFileSync(`./scenarios/${name}/normalized-fixture.json`)
);
}

function mock(fixtures, additions) {
Expand Down Expand Up @@ -44,10 +46,7 @@ function mock(fixtures, additions) {

const api = {
pending() {
return [].concat.apply(
[],
mocks.map((mock) => mock.pendingMocks())
);
return [].concat(...mocks.map((mock) => mock.pendingMocks()));
},
explain(error) {
if (!/^Nock: No match/.test(error.message)) {
Expand Down Expand Up @@ -81,7 +80,7 @@ function mock(fixtures, additions) {
done() {
assert.ok(
api.isDone(),
"Mocks not yet satisfied:\n" + api.pending().join("\n")
`Mocks not yet satisfied:\n${api.pending().join("\n")}`
);
},
isDone() {
Expand Down
2 changes: 1 addition & 1 deletion lib/calculate-body-length.js
@@ -1,4 +1,4 @@
module.exports = calculateBodyLength;
export default calculateBodyLength;

function calculateBodyLength(body) {
if (typeof body === "string") {
Expand Down
8 changes: 4 additions & 4 deletions lib/env.js
@@ -1,6 +1,6 @@
const envalid = require("envalid");
import { cleanEnv, str } from "envalid";

module.exports = envalid.cleanEnv(process.env, {
FIXTURES_USER_A_TOKEN_FULL_ACCESS: envalid.str(),
FIXTURES_USER_B_TOKEN_FULL_ACCESS: envalid.str(),
export default cleanEnv(process.env, {
FIXTURES_USER_A_TOKEN_FULL_ACCESS: str(),
FIXTURES_USER_B_TOKEN_FULL_ACCESS: str(),
});
2 changes: 1 addition & 1 deletion lib/fixturize-commit-sha.js
@@ -1,4 +1,4 @@
module.exports = fixturizeCommitSha;
export default fixturizeCommitSha;

// We keep track of commit sha hashes. We don’t want to simply zerofy them as
// there can be multiple commits. So instead we keep state of a counter and
Expand Down
2 changes: 1 addition & 1 deletion lib/fixturize-entity-id.js
@@ -1,4 +1,4 @@
module.exports = fixturizeEntityId;
export default fixturizeEntityId;

// In cases when we can’t simply set IDs to 1 because we have to handle multiple
// entities of the same type, this method returns counter-based IDs per type
Expand Down
16 changes: 8 additions & 8 deletions lib/fixturize-path.js
@@ -1,8 +1,8 @@
module.exports = fixturizePath;
export default fixturizePath;

const fixturizeCommitSha = require("./fixturize-commit-sha");
const fixturizeEntityId = require("./fixturize-entity-id");
const temporaryRepository = require("./temporary-repository");
import fixturizeCommitSha from "./fixturize-commit-sha.js";
import fixturizeEntityId from "./fixturize-entity-id.js";
import { regex } from "./temporary-repository.js";

const PLACEHOLDER_REGEX = /\{[^}]+\}/g;
const PATH_TEMPLATES = [
Expand All @@ -27,7 +27,7 @@ const FIND_SHA_OR_ID_REGEX_STRING = "(\\w{40}|\\d+)";
function fixturizePath(scenarioState, path) {
// rename temporary repositories
// e.g. tmp-scenario-bar-20170924033013835 => bar
path = path.replace(temporaryRepository.regex, "$1");
path = path.replace(regex, "$1");

const pathTemplate = PATH_TEMPLATES.find((pathTemplate) => {
const regexString = pathTemplate.replace(
Expand All @@ -41,11 +41,11 @@ function fixturizePath(scenarioState, path) {
return path;
}

const regex = new RegExp(
const placeholderRegex = new RegExp(
pathTemplate.replace(PLACEHOLDER_REGEX, FIND_SHA_OR_ID_REGEX_STRING)
);
const placeholderNames = pathTemplate.match(PLACEHOLDER_REGEX);
const idsOrShas = path.match(regex).slice(1);
const idsOrShas = path.match(placeholderRegex).slice(1);

const newPath = placeholderNames.reduce((pathTemplate, placeholder, i) => {
const entityName = toEntityName(placeholder);
Expand All @@ -65,7 +65,7 @@ function fixturizePath(scenarioState, path) {

return (
path
.replace(regex, newPath)
.replace(placeholderRegex, newPath)
// ?u=[sha] query parameter
.replace(/\?u=\w{40}/, "?u=0000000000000000000000000000000000000001")
);
Expand Down
10 changes: 2 additions & 8 deletions lib/headers.js
@@ -1,7 +1,4 @@
module.exports = {
toObject: rawHeadersToObject,
toArray: objectToRawHeaders,
};
export default { toObject: rawHeadersToObject, toArray: objectToRawHeaders };

function rawHeadersToObject(rawHeaders) {
const keys = [];
Expand All @@ -19,8 +16,5 @@ function rawHeadersToObject(rawHeaders) {

function objectToRawHeaders(map) {
const keys = Object.keys(map).sort();
return [].concat.apply(
[],
keys.map((key) => [key, map[key]])
);
return [].concat(...keys.map((key) => [key, map[key]]));
}

0 comments on commit b3a45cf

Please sign in to comment.