Skip to content

Commit

Permalink
run eslint and prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
echo-bravo-yahoo committed Oct 4, 2024
1 parent 244eb5a commit 2939639
Show file tree
Hide file tree
Showing 37 changed files with 1,033 additions and 927 deletions.
102 changes: 59 additions & 43 deletions src/cli.mjs
Original file line number Diff line number Diff line change
@@ -1,99 +1,115 @@
import yargs from 'yargs'
import chalk from 'chalk'
import yargs from "yargs";
import chalk from "chalk";

import evalCommand from './yargs-commands/eval.mjs'
import loginCommand from './yargs-commands/login.mjs'
import schemaCommand from './yargs-commands/schema/schema.mjs'
import { logArgv } from './lib/middleware.mjs'
export let container
import evalCommand from "./yargs-commands/eval.mjs";
import loginCommand from "./yargs-commands/login.mjs";
import schemaCommand from "./yargs-commands/schema/schema.mjs";
import { logArgv } from "./lib/middleware.mjs";

export let container;
export let builtYargs;

// import { connect } from 'node:tls'
// const socket = connect({ port: 443, host: 'db.fauna.com', checkServerIdentity: () => {} })
// fetch().catch(() => {})
// socket.end(() => { })

export async function run(argvInput, _container) {
container = _container
const logger = container.resolve("logger")
container = _container;
const logger = container.resolve("logger");

try {
buildYargs(argvInput)
await builtYargs.parseAsync()
buildYargs(argvInput);
await builtYargs.parseAsync();
} catch (e) {
const message = `${chalk.reset(await builtYargs.getHelp())}\n\n${chalk.red(e.message)}`
logger.stderr(message)
logger.fatal("\n" + e.stack, "error")
const exit = container.resolve("exit")
exit(1)
const message = `${chalk.reset(await builtYargs.getHelp())}\n\n${chalk.red(
e.message
)}`;
logger.stderr(message);
logger.fatal("\n" + e.stack, "error");
const exit = container.resolve("exit");
exit(1);
}
}

export let builtYargs

// this snapshots the yargs object after building it but before parsing
// this lets us use `builtYargs.argv` anywhere where we need argv but where
// it might be difficult to pipe them in.
function buildYargs(argvInput) {
const logger = container.resolve("logger")
const logger = container.resolve("logger");

builtYargs = yargs(argvInput)
.scriptName("fauna")
.middleware([logArgv], true)
.command("eval", "evaluate a query", evalCommand)
.command("login", "login via website", loginCommand)
.command(schemaCommand)
.command("throw", false, { handler: () => { throw new Error("this is a test error") }, builder: {} })
.command("reject", false, { handler: async () => { throw new Error("this is a rejected promise") }, builder: {} })
.command("throw", false, {
handler: () => {
throw new Error("this is a test error");
},
builder: {},
})
.command("reject", false, {
handler: async () => {
throw new Error("this is a rejected promise");
},
builder: {},
})
.demandCommand()
//.strictCommands(true) blows up... why?
.strictOptions(true)

// .completion('completion', function(currentWord, argv, defaultCompletions, done) {
// .completion('completion', function(currentWord, argv, defaultCompletions, done) {
// const logger = container.resolve("logger")
// logger.debug(`Attempting auto-complete for current word ${currentWord} with argv ${JSON.stringify(argv, null, 4)}.`, 'completion')
// const completions = {
// 'saved': () => Object.keys(argv.savedRolls) || []
// }
// 'saved': () => Object.keys(argv.savedRolls) || []
// }

// for (const [key, completionGetter] of Object.entries(completions)) {
// if (currentWord === argv[key])
// done(prefix(currentWord, completionGetter()))
// }
// if (currentWord === argv[key])
// done(prefix(currentWord, completionGetter()))
// }
// defaultCompletions()
// })
.options({
"color": {
description: "whether or not to emit escape codes for multi-color terminal output.",
type: 'boolean',
color: {
description:
"whether or not to emit escape codes for multi-color terminal output.",
type: "boolean",
// https://github.com/chalk/chalk?tab=readme-ov-file#chalklevel
default: chalk.level > 0,
},
"verbosity": {
verbosity: {
description: "the lowest level diagnostic logs to emit",
type: 'number',
type: "number",
default: 0,
},
"verbose-component": {
description: "components to emit diagnostic logs for; this takes precedence over the 'verbosity' flag",
type: 'array',
description:
"components to emit diagnostic logs for; this takes precedence over the 'verbosity' flag",
type: "array",
default: [],
choices: ['fetch', 'error', 'argv'],
choices: ["fetch", "error", "argv"],
},
})
.wrap(yargs.terminalWidth)
.help('help', 'show help')
.help("help", "show help")
.fail((msg, err, yargs) => {
const exit = container.resolve("exit")
const message = `${chalk.reset(yargs.help())}\n\n${chalk.red(msg || err?.message)}`
logger.stderr(message)
const exit = container.resolve("exit");
const message = `${chalk.reset(yargs.help())}\n\n${chalk.red(
msg || err?.message
)}`;
logger.stderr(message);
if (err && err.stack) {
logger.fatal(err.stack)
logger.fatal(err.stack);
}
exit(1)
exit(1);
})
.exitProcess(false)
.version(false)
.completion()
.completion();

return builtYargs
return builtYargs;
}
4 changes: 2 additions & 2 deletions src/config/setup-container.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import {
writeSchemaFiles,
} from "../lib/schema.mjs";
import { confirm } from "@inquirer/prompts";
import { makeFaunaRequest } from "../lib/db.mjs"
import { makeFaunaRequest } from "../lib/db.mjs";
import fetchWrapper from "../lib/fetch-wrapper.mjs";
import { FaunaAccountClient } from "../lib/fauna-account-client.mjs";
import open from "open";
import OAuthClient from "../lib/auth/oauth-client.mjs";
import { Lifetime } from "awilix";
import fs from 'node:fs'
import fs from "node:fs";

// import { findUpSync } from 'find-up'
// import fs from 'node:fs'
Expand Down
44 changes: 24 additions & 20 deletions src/config/setup-test-container.mjs
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
import fs from 'node:fs'
import fs from "node:fs";

import * as awilix from 'awilix/lib/awilix.module.mjs'
import { setupCommonContainer, injectables } from './setup-container.mjs'
import * as awilix from "awilix/lib/awilix.module.mjs";
import { setupCommonContainer, injectables } from "./setup-container.mjs";

import sinon, { stub } from 'sinon'
import sinon, { stub } from "sinon";

import logger from '../lib/logger.mjs'
import logger from "../lib/logger.mjs";

// Mocks all _functions_ declared on the injectables export from setup-container.mjs
function automock(container) {
const skipped = []
const skipped = [];
for (const [key, value] of Object.entries(injectables)) {
if (value.isLeakSafe && typeof value.resolve() === 'function') {
container.register({ [key]: awilix.asValue(stub()) })
if (value.isLeakSafe && typeof value.resolve() === "function") {
container.register({ [key]: awilix.asValue(stub()) });
} else {
skipped.push(key)
skipped.push(key);
}
}

return skipped
return skipped;
}

function confirmManualMocks(manualMocks, thingsToManuallyMock) {
for (let i = 0; i < thingsToManuallyMock.length; i++) {
const manualMock = manualMocks[thingsToManuallyMock[i]]
const manualMock = manualMocks[thingsToManuallyMock[i]];
if (!manualMock || !manualMock.resolve)
throw new Error (`Please mock the injectable "${thingsToManuallyMock[i]}" by adding it to "./src/config/setup-test-container.mjs".`)
throw new Error(
`Please mock the injectable "${thingsToManuallyMock[i]}" by adding it to "./src/config/setup-test-container.mjs".`
);
}
}

export function setupTestContainer() {
const container = setupCommonContainer()
const container = setupCommonContainer();

const thingsToManuallyMock = automock(container)
const thingsToManuallyMock = automock(container);

const manualMocks = {
fs: awilix.asValue(sinon.stub(fs)),
Expand All @@ -54,18 +56,20 @@ export function setupTestContainer() {
stdout: stub(),
stderr: stub(),
}),
getSimpleClient: awilix.asValue(stub().returns({ close: () => Promise.resolve() })),
getSimpleClient: awilix.asValue(
stub().returns({ close: () => Promise.resolve() })
),
accountClient: awilix.asFunction(stub()),
oauthClient: awilix.asFunction(stub()),
// in tests, let's exit by throwing
exit: awilix.asValue(() => {
throw new Error(1);
})
}
}),
};

confirmManualMocks(manualMocks, thingsToManuallyMock)
confirmManualMocks(manualMocks, thingsToManuallyMock);

container.register(manualMocks)
container.register(manualMocks);

return container
return container;
}
14 changes: 9 additions & 5 deletions src/lib/auth/oauth-client.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import http, { IncomingMessage, ServerResponse } from "http";
import http from "http";
import { randomBytes, createHash } from "crypto";
import url from "url";


// Default to prod client id and secret
const clientId = process.env.FAUNA_CLIENT_ID ?? "-_vEB3FKRoWbJdFpMg72Mx0UVAA";
// Native public clients are not confidential. The client secret is not used beyond
Expand All @@ -14,10 +13,15 @@ const REDIRECT_URI = `http://127.0.0.1`;

class OAuthClient {
server; //: http.Server;

port; //: number;

code_verifier; //: string;

code_challenge; //: string;

auth_code; //: string;

state; //: string;

constructor() {
Expand Down Expand Up @@ -49,8 +53,8 @@ class OAuthClient {
clientSecret,
authCode: this.auth_code,
redirectURI: `${REDIRECT_URI}:${this.port}`,
codeVerifier: this.code_verifier
}
codeVerifier: this.code_verifier,
};
}

_generateCSRFToken() {
Expand Down Expand Up @@ -124,7 +128,7 @@ class OAuthClient {
async start() {
try {
this.server.on("listening", () => {
this.port = (this.server.address()).port;
this.port = this.server.address().port;
this.server.emit("ready");
});
if (!this.server.listening) {
Expand Down
Loading

0 comments on commit 2939639

Please sign in to comment.