From 8e849c4dd07d238ad7e9e91bc843b4116b2b61df Mon Sep 17 00:00:00 2001 From: Neil Macneale V Date: Mon, 25 Sep 2023 10:37:49 -0700 Subject: [PATCH] Switch everything in lib/ to a module (#249) * Switch everything in lib/ to a module * Fix linter problems * Fix undefined variable Client for v4 * Fix import of fauna import writer --- .eslintrc | 4 +- src/commands/add-endpoint.js | 2 +- src/commands/cloud-login.js | 2 +- src/commands/create-database.js | 2 +- src/commands/create-key.js | 2 +- src/commands/default-endpoint.js | 2 +- src/commands/delete-database.js | 2 +- src/commands/delete-endpoint.js | 2 +- src/commands/delete-key.js | 2 +- src/commands/eval.js | 2 +- src/commands/import.js | 6 +- src/commands/list-endpoints.js | 2 +- src/commands/list-keys.js | 2 +- src/commands/run-queries.js | 2 +- src/commands/schema/diff.js | 2 +- src/commands/schema/pull.js | 2 +- src/commands/schema/push.js | 2 +- src/commands/shell.js | 2 +- src/commands/upload-graphql-schema.js | 2 +- src/lib/fauna-client.js | 20 +++---- src/lib/fauna-command.js | 31 +++++----- src/lib/fauna-import-writer.js | 19 +++---- src/lib/fauna-object-translator.js | 20 +++---- src/lib/import-limits.js | 7 +-- src/lib/import-penalty.js | 4 +- src/lib/json-stream.js | 6 +- src/lib/misc.js | 81 +++++++++++---------------- src/lib/schema-command.js | 22 ++++---- test/lib/fauna-import-writer.test.js | 2 +- test/tsconfig.json | 4 +- 30 files changed, 114 insertions(+), 146 deletions(-) diff --git a/.eslintrc b/.eslintrc index 07c72854..24be33c5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -22,7 +22,9 @@ "@jest/globals" ] } - ] + ], + // we use typescript so dynamic imports are fine + "node/no-unsupported-features": "off" }, "ignorePatterns": ["dist/**/*"], "overrides": [ diff --git a/src/commands/add-endpoint.js b/src/commands/add-endpoint.js index ad6c65c3..ead7401c 100644 --- a/src/commands/add-endpoint.js +++ b/src/commands/add-endpoint.js @@ -1,7 +1,7 @@ const { cli } = require("cli-ux"); const { Flags, Args } = require("@oclif/core"); const { saveEndpointOrError } = require("../lib/misc.js"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const url = require("url"); class AddEndpointCommand extends FaunaCommand { diff --git a/src/commands/cloud-login.js b/src/commands/cloud-login.js index 22d89a6d..cc6ba265 100644 --- a/src/commands/cloud-login.js +++ b/src/commands/cloud-login.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const inquirer = require("inquirer"); const fetch = require("node-fetch"); const faunadb = require("faunadb"); diff --git a/src/commands/create-database.js b/src/commands/create-database.js index 3e426780..cd394592 100644 --- a/src/commands/create-database.js +++ b/src/commands/create-database.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { Args } = require("@oclif/core"); const faunadb = require("faunadb"); const q = faunadb.query; diff --git a/src/commands/create-key.js b/src/commands/create-key.js index a7221979..05188a2a 100644 --- a/src/commands/create-key.js +++ b/src/commands/create-key.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { Args } = require("@oclif/core"); const faunadb = require("faunadb"); const q = faunadb.query; diff --git a/src/commands/default-endpoint.js b/src/commands/default-endpoint.js index 7e7b51c7..4212034e 100644 --- a/src/commands/default-endpoint.js +++ b/src/commands/default-endpoint.js @@ -1,6 +1,6 @@ const { setDefaultEndpoint } = require("../lib/misc.js"); const { Args } = require("@oclif/core"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; class DefaultEndpointCommand extends FaunaCommand { async run() { diff --git a/src/commands/delete-database.js b/src/commands/delete-database.js index bdc3a10a..c0bdeeed 100644 --- a/src/commands/delete-database.js +++ b/src/commands/delete-database.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { Args } = require("@oclif/core"); const faunadb = require("faunadb"); const q = faunadb.query; diff --git a/src/commands/delete-endpoint.js b/src/commands/delete-endpoint.js index 6ad8f128..972f6e03 100644 --- a/src/commands/delete-endpoint.js +++ b/src/commands/delete-endpoint.js @@ -1,6 +1,6 @@ const { deleteEndpointOrError } = require("../lib/misc.js"); const { Args } = require("@oclif/core"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; class DeleteEndpoint extends FaunaCommand { async run() { diff --git a/src/commands/delete-key.js b/src/commands/delete-key.js index b96e13cd..21cb8a63 100644 --- a/src/commands/delete-key.js +++ b/src/commands/delete-key.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { Args } = require("@oclif/core"); const faunadb = require("faunadb"); const q = faunadb.query; diff --git a/src/commands/eval.js b/src/commands/eval.js index 84ccbece..4911967c 100644 --- a/src/commands/eval.js +++ b/src/commands/eval.js @@ -3,7 +3,7 @@ const fs = require("fs"); const esprima = require("esprima"); const { Flags, Args } = require("@oclif/core"); const faunadb = require("faunadb"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { readFile, runQueries, writeFile } = require("../lib/misc.js"); const EVAL_OUTPUT_FORMATS = ["json", "json-tagged", "shell"]; diff --git a/src/commands/import.js b/src/commands/import.js index 8bcf1857..31478ac4 100644 --- a/src/commands/import.js +++ b/src/commands/import.js @@ -1,13 +1,13 @@ const fs = require("fs"); const { Flags } = require("@oclif/core"); -const FaunaCommand = require("../lib/fauna-command.js"); -const StreamJson = require("../lib/json-stream"); +const FaunaCommand = require("../lib/fauna-command.js").default; +const StreamJson = require("../lib/json-stream").default; const faunadb = require("faunadb"); const { pipeline } = require("stream"); const p = require("path"); const q = faunadb.query; -const getFaunaImportWriter = require("../lib/fauna-import-writer"); +const getFaunaImportWriter = require("../lib/fauna-import-writer").default; const { parse } = require("csv-parse"); const { ImportLimits } = require("../lib/import-limits"); diff --git a/src/commands/list-endpoints.js b/src/commands/list-endpoints.js index d642204b..c64d5c31 100644 --- a/src/commands/list-endpoints.js +++ b/src/commands/list-endpoints.js @@ -1,5 +1,5 @@ const { loadEndpoints } = require("../lib/misc.js"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; class ListEndpointsCommand extends FaunaCommand { async run() { diff --git a/src/commands/list-keys.js b/src/commands/list-keys.js index 5087d7f5..e0695751 100644 --- a/src/commands/list-keys.js +++ b/src/commands/list-keys.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const faunadb = require("faunadb"); const q = faunadb.query; const Table = require("cli-table"); diff --git a/src/commands/run-queries.js b/src/commands/run-queries.js index e5d1df65..ade65bf0 100644 --- a/src/commands/run-queries.js +++ b/src/commands/run-queries.js @@ -1,5 +1,5 @@ const { Flags } = require("@oclif/core"); -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const EvalCommand = require("./eval"); const DEPRECATED_MSG = diff --git a/src/commands/schema/diff.js b/src/commands/schema/diff.js index 42d7311f..12096c54 100644 --- a/src/commands/schema/diff.js +++ b/src/commands/schema/diff.js @@ -1,4 +1,4 @@ -const SchemaCommand = require("../../lib/schema-command.js"); +const SchemaCommand = require("../../lib/schema-command.js").default; const fetch = require("node-fetch"); const { Flags } = require("@oclif/core"); diff --git a/src/commands/schema/pull.js b/src/commands/schema/pull.js index d73890d6..e499ce24 100644 --- a/src/commands/schema/pull.js +++ b/src/commands/schema/pull.js @@ -1,4 +1,4 @@ -const SchemaCommand = require("../../lib/schema-command.js"); +const SchemaCommand = require("../../lib/schema-command.js").default; const fetch = require("node-fetch"); const fs = require("fs"); const path = require("path"); diff --git a/src/commands/schema/push.js b/src/commands/schema/push.js index 813ddeeb..0ea5e7d3 100644 --- a/src/commands/schema/push.js +++ b/src/commands/schema/push.js @@ -1,4 +1,4 @@ -const SchemaCommand = require("../../lib/schema-command.js"); +const SchemaCommand = require("../../lib/schema-command.js").default; const fetch = require("node-fetch"); const { Flags, ux } = require("@oclif/core"); diff --git a/src/commands/shell.js b/src/commands/shell.js index 9738799b..8af852c1 100644 --- a/src/commands/shell.js +++ b/src/commands/shell.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { runQueries, stringifyEndpoint } = require("../lib/misc.js"); const faunadb = require("faunadb"); const { Flags, Args } = require("@oclif/core"); diff --git a/src/commands/upload-graphql-schema.js b/src/commands/upload-graphql-schema.js index 43e3b69b..1e254923 100644 --- a/src/commands/upload-graphql-schema.js +++ b/src/commands/upload-graphql-schema.js @@ -1,4 +1,4 @@ -const FaunaCommand = require("../lib/fauna-command.js"); +const FaunaCommand = require("../lib/fauna-command.js").default; const { Flags, Args } = require("@oclif/core"); const fetch = require("node-fetch"); const fs = require("fs"); diff --git a/src/lib/fauna-client.js b/src/lib/fauna-client.js index 3e57718b..53f9327f 100644 --- a/src/lib/fauna-client.js +++ b/src/lib/fauna-client.js @@ -1,14 +1,13 @@ -const http2 = require("http2"); +import { connect, constants } from "http2"; // Copied from the fauna-js driver: // https://github.com/fauna/fauna-js/blob/main/src/http-client/node-http2-client.ts -module.exports = class FaunaClient { +export default class FaunaClient { constructor(endpoint, secret, timeout) { - this.session = http2 - .connect(endpoint, { - peerMaxConcurrentStreams: 50, - }) + this.session = connect(endpoint, { + peerMaxConcurrentStreams: 50, + }) .once("error", () => this.close()) .once("goaway", () => this.close()); this.secret = secret; @@ -19,8 +18,7 @@ module.exports = class FaunaClient { return new Promise((resolvePromise, rejectPromise) => { let req; const onResponse = (http2ResponseHeaders) => { - const status = - http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS]; + const status = http2ResponseHeaders[constants.HTTP2_HEADER_STATUS]; let responseData = ""; req.on("data", (chunk) => { @@ -41,8 +39,8 @@ module.exports = class FaunaClient { Authorization: `Bearer ${this.secret}`, "x-format": format, "X-Fauna-Source": "Fauna Shell", - [http2.constants.HTTP2_HEADER_PATH]: "/query/1", - [http2.constants.HTTP2_HEADER_METHOD]: "POST", + [constants.HTTP2_HEADER_PATH]: "/query/1", + [constants.HTTP2_HEADER_METHOD]: "POST", ...(typecheck && { "x-typecheck": typecheck }), ...(this.timeout && { "x-query-timeout-ms": this.timeout }), }; @@ -70,4 +68,4 @@ module.exports = class FaunaClient { async close() { this.session.close(); } -}; +} diff --git a/src/lib/fauna-command.js b/src/lib/fauna-command.js index 16518561..b9776345 100644 --- a/src/lib/fauna-command.js +++ b/src/lib/fauna-command.js @@ -1,11 +1,10 @@ -const { Command, Flags } = require("@oclif/core"); -const { lookupEndpoint } = require("../lib/config/index.ts"); -const { stringifyEndpoint } = require("../lib/misc.js"); -const faunadb = require("faunadb"); -const chalk = require("chalk"); -const q = faunadb.query; -const FaunaClient = require("./fauna-client.js"); -const fetch = require("node-fetch"); +import { Command, Flags } from "@oclif/core"; +import { lookupEndpoint } from "./config"; +import { stringifyEndpoint } from "./misc"; +import { query as q, errors, Client } from "faunadb"; +import { green } from "chalk"; +import FaunaClient from "./fauna-client.js"; +import fetch from "node-fetch"; /** * This is the base class for all fauna-shell commands. @@ -35,7 +34,7 @@ class FaunaCommand extends Command { } success(msg) { - const bang = chalk.green(process.platform === "win32" ? "»" : "›"); + const bang = green(process.platform === "win32" ? "»" : "›"); console.info(` ${bang} Success: ${msg}`); } @@ -58,7 +57,7 @@ class FaunaCommand extends Command { const { hostname, port, protocol } = new URL(connectionOptions.url); - const client = new faunadb.Client({ + const client = new Client({ domain: hostname, port, scheme: protocol?.replace(/:$/, ""), @@ -80,7 +79,7 @@ class FaunaCommand extends Command { } mapConnectionError({ err, connectionOptions }) { - if (err instanceof faunadb.errors.Unauthorized) { + if (err instanceof errors.Unauthorized) { return this.error( `Could not Connect to ${stringifyEndpoint( connectionOptions @@ -99,7 +98,7 @@ class FaunaCommand extends Command { const { hostname, port, protocol } = new URL(connectionOptions.url); - const client = new faunadb.Client({ + const client = new Client({ domain: hostname, port, scheme: protocol?.replace(/:$/, ""), @@ -182,9 +181,9 @@ class FaunaCommand extends Command { } dbExists(dbName, callback) { - return this.withClient(function (testDbClient, _) { - return testDbClient.query(q.Exists(q.Database(dbName))).then(callback); - }); + return this.withClient((testDbClient, _) => + testDbClient.query(q.Exists(q.Database(dbName))).then(callback) + ); } } @@ -222,4 +221,4 @@ FaunaCommand.flags = { }), }; -module.exports = FaunaCommand; +export default FaunaCommand; diff --git a/src/lib/fauna-import-writer.js b/src/lib/fauna-import-writer.js index 9176b9b1..56c07344 100644 --- a/src/lib/fauna-import-writer.js +++ b/src/lib/fauna-import-writer.js @@ -1,14 +1,11 @@ -const q = require("faunadb").query; -const { FaunaObjectTranslator } = require("./fauna-object-translator"); -const sizeof = require("object-sizeof"); -const { backOff } = require("exponential-backoff"); +import { query as q } from "faunadb"; +import { FaunaObjectTranslator } from "./fauna-object-translator"; +import sizeof from "object-sizeof"; +import { backOff } from "exponential-backoff"; const FaunaHTTPError = require("faunadb").errors.FaunaHTTPError; -const { - RateLimiterMemory, - RateLimiterQueue, -} = require("rate-limiter-flexible"); -const { ImportPenalty } = require("./import-penalty"); -const { RateEstimator } = require("./import-limits"); +import { RateLimiterMemory, RateLimiterQueue } from "rate-limiter-flexible"; +import { ImportPenalty } from "./import-penalty"; +import { RateEstimator } from "./import-limits"; /** * Creates a function that consumes a stream of objects and writes creates each object @@ -329,4 +326,4 @@ this item and continuing.` return streamConsumer; } -module.exports = getFaunaImportWriter; +export default getFaunaImportWriter; diff --git a/src/lib/fauna-object-translator.js b/src/lib/fauna-object-translator.js index 4ee697a7..fc7afccb 100644 --- a/src/lib/fauna-object-translator.js +++ b/src/lib/fauna-object-translator.js @@ -1,10 +1,10 @@ -const q = require("faunadb").query; -const moment = require("moment"); +import { query as q } from "faunadb"; +import { utc, ISO_8601, RFC_2822, unix } from "moment"; /** * An error translating an object with a {FaunaObjectTranslater}. */ -class TranslationError extends Error {} +export class TranslationError extends Error {} /** * Helper class for cleaning objects prior to persistence in Fauna. @@ -12,7 +12,7 @@ class TranslationError extends Error {} * - trim input strings to remove unneeded whitespace * - cast types as specified by input **/ -class FaunaObjectTranslator { +export class FaunaObjectTranslator { static #NUMBER_REGEX = /(^\s*[+|-]?\d+\s*$)|(^\s*[+|-]?\d*\.\d+\s*$)/; static #TRULY = ["true", "t", "yes", "1", 1, true]; @@ -117,10 +117,10 @@ class FaunaObjectTranslator { )}' to a date.` ); } - let theDate = moment.utc(val, moment.ISO_8601); + let theDate = utc(val, ISO_8601); if (!theDate.isValid()) { // fallback to other date formats - theDate = moment.utc(val, moment.RFC_2822); + theDate = utc(val, RFC_2822); if (!theDate.isValid()) { theDate = new Date(val); if (Number.isNaN(theDate.getTime())) { @@ -139,8 +139,7 @@ Making a best-effort translation to '${theDate}'`); #epochMillisDate(val) { try { return q.Time( - moment - .unix(this.#getNumber(val) / 1000) + unix(this.#getNumber(val) / 1000) .utc() .toISOString() ); @@ -155,7 +154,7 @@ Making a best-effort translation to '${theDate}'`); #epochSecondsDate(val) { try { - return q.Time(moment.unix(this.#getNumber(val)).utc().toISOString()); + return q.Time(unix(this.#getNumber(val)).utc().toISOString()); } catch (e) { throw new TranslationError( `Cannot convert '${FaunaObjectTranslator.#getErrorValue( @@ -189,6 +188,3 @@ Making a best-effort translation to '${theDate}'`); }, obj); } } - -exports.FaunaObjectTranslator = FaunaObjectTranslator; -exports.TranslationError = TranslationError; diff --git a/src/lib/import-limits.js b/src/lib/import-limits.js index 972010f7..1abba9bc 100644 --- a/src/lib/import-limits.js +++ b/src/lib/import-limits.js @@ -1,6 +1,6 @@ // these functions are present to make testing the import function easy. -class ImportLimits { +export class ImportLimits { /** * @return the maximum import size limit in MB **/ @@ -9,7 +9,7 @@ class ImportLimits { } } -class RateEstimator { +export class RateEstimator { static estimateWriteOpsAsBytes(totalBytes, numberOfIndexes) { if (totalBytes < 0) { throw new Error("Invalid argument totalBytes must be >= 0"); @@ -40,6 +40,3 @@ class RateEstimator { return Math.ceil(actualWriteOps / estimatedWriteOpsNoIndex) - 1; } } - -module.exports.ImportLimits = ImportLimits; -module.exports.RateEstimator = RateEstimator; diff --git a/src/lib/import-penalty.js b/src/lib/import-penalty.js index 68ac2475..07695fbb 100644 --- a/src/lib/import-penalty.js +++ b/src/lib/import-penalty.js @@ -1,4 +1,4 @@ -class ImportPenalty { +export class ImportPenalty { constructor(floor, ceiling) { this.floor = floor; this.ceiling = ceiling; @@ -17,5 +17,3 @@ class ImportPenalty { return next; } } - -exports.ImportPenalty = ImportPenalty; diff --git a/src/lib/json-stream.js b/src/lib/json-stream.js index d6735efd..a4ecffc5 100644 --- a/src/lib/json-stream.js +++ b/src/lib/json-stream.js @@ -1,6 +1,6 @@ "use strict"; -const StreamBase = require("stream-json/streamers/StreamBase"); -const withParser = require("stream-json/utils/withParser"); +import StreamBase from "stream-json/streamers/StreamBase"; +import withParser from "stream-json/utils/withParser"; class StreamJson extends StreamBase { static make(options) { @@ -66,4 +66,4 @@ class StreamJson extends StreamBase { StreamJson.StreamJson = StreamJson.make; StreamJson.make.Constructor = StreamJson; -module.exports = StreamJson; +export default StreamJson; diff --git a/src/lib/misc.js b/src/lib/misc.js index a8206f1e..c1a4750a 100644 --- a/src/lib/misc.js +++ b/src/lib/misc.js @@ -1,13 +1,13 @@ /*eslint no-unused-expressions: [2, { allowTernary: true }]*/ -const vm = require("vm"); -const os = require("os"); -const path = require("path"); -const fs = require("fs"); -const ini = require("ini"); -const { cli } = require("cli-ux"); -const faunadb = require("faunadb"); -const escodegen = require("escodegen"); -const fetch = require("node-fetch"); +import { createContext, runInContext } from "vm"; +import { homedir } from "os"; +import { join } from "path"; +import { readFile as _readFile, writeFile as _writeFile } from "fs"; +import { parse, stringify } from "ini"; +import { cli } from "cli-ux"; +import { query } from "faunadb"; +import { generate } from "escodegen"; +import fetch from "node-fetch"; const FAUNA_CLOUD_DOMAIN = "db.fauna.com"; const ERROR_NO_DEFAULT_ENDPOINT = @@ -25,7 +25,7 @@ const ERROR_SPECIFY_SECRET_KEY = * from the user. * - If no other endpoint exists, then the endpoint will be set as the default one. */ -function saveEndpointOrError(newEndpoint, alias, secret) { +export function saveEndpointOrError(newEndpoint, alias, secret) { return loadEndpoints().then(function (endpoints) { if (endpointExists(endpoints, alias)) { return confirmEndpointOverwrite(alias).then(function (overwrite) { @@ -41,7 +41,7 @@ function saveEndpointOrError(newEndpoint, alias, secret) { }); } -function deleteEndpointOrError(alias) { +export function deleteEndpointOrError(alias) { return loadEndpoints().then(function (endpoints) { if (endpointExists(endpoints, alias)) { return confirmEndpointDelete(alias).then(function (del) { @@ -61,7 +61,7 @@ function deleteEndpointOrError(alias) { * Validates that the 'cloud' endpoint points to FAUNA_CLOUD_DOMAIN. */ // TODO: candidate to delete if new-cloud-login accepted -function validCloudEndpoint() { +export function validCloudEndpoint() { return loadEndpoints().then(function (config) { return new Promise(function (resolve, reject) { if (config.cloud && config.cloud.domain !== FAUNA_CLOUD_DOMAIN) { @@ -77,7 +77,7 @@ function validCloudEndpoint() { * Sets `endpoint` as the default endpoint. * If `endpoint` doesn't exist, returns an error. */ -function setDefaultEndpoint(endpoint) { +export function setDefaultEndpoint(endpoint) { return loadEndpoints().then(function (endpoints) { return new Promise(function (resolve, reject) { if (endpoints[endpoint]) { @@ -100,10 +100,10 @@ function setDefaultEndpoint(endpoint) { * Loads the endpoints from the ~/.fauna-shell file. * If the file doesn't exist, returns an empty object. */ -function loadEndpoints() { +export function loadEndpoints() { return readFile(getConfigFile()) .then(function (configData) { - return ini.parse(configData); + return parse(configData); }) .catch(function (err) { if (fileNotFound(err)) { @@ -129,7 +129,7 @@ function confirmEndpointDelete(alias) { ); } -function saveEndpoint(config, endpoint, alias, secret) { +export function saveEndpoint(config, endpoint, alias, secret) { var port = endpoint.port ? `:${endpoint.port}` : ""; var uri = `${endpoint.protocol}//${endpoint.hostname}${port}`; @@ -185,22 +185,22 @@ function buildEndpointObject(endpoint, secret) { * ~/.fauna-shell file. */ function saveConfig(config) { - return writeFile(getConfigFile(), ini.stringify(config), 0o700); + return writeFile(getConfigFile(), stringify(config), 0o700); } /** * Returns the full path to the `.fauna-shell` config file */ -function getConfigFile() { - return path.join(os.homedir(), ".fauna-shell"); +export function getConfigFile() { + return join(homedir(), ".fauna-shell"); } /** * Wraps `fs.readFile` into a Promise. */ -function readFile(fileName) { +export function readFile(fileName) { return new Promise(function (resolve, reject) { - fs.readFile(fileName, "utf8", (err, data) => { + _readFile(fileName, "utf8", (err, data) => { err ? reject(err) : resolve(data); }); }); @@ -209,9 +209,9 @@ function readFile(fileName) { /** * Wraps `fs.writeFile` into a Promise. */ -function writeFile(fileName, data, mode) { +export function writeFile(fileName, data, mode) { return new Promise(function (resolve, reject) { - fs.writeFile(fileName, data, { mode: mode }, (err) => { + _writeFile(fileName, data, { mode: mode }, (err) => { err ? reject(err) : resolve(data); }); }); @@ -246,12 +246,12 @@ function fileNotFound(err) { * @param {string} dbScope - A database name to scope the connection to. * @param {string} role - A user role: 'admin'|'server'|'server-readonly'|'client'. */ -function buildConnectionOptions(cmdFlags, dbScope, role) { +export function buildConnectionOptions(cmdFlags, dbScope, role) { return new Promise(function (resolve, reject) { readFile(getConfigFile()) .then(function (configData) { var endpoint = {}; - const config = ini.parse(configData); + const config = parse(configData); // having a valid endpoint, assume there's a secret set if (hasValidEndpoint(config, cmdFlags.endpoint)) { endpoint = getEndpoint(config, cmdFlags.endpoint); @@ -363,20 +363,18 @@ class QueryError extends Error { } function wrapQueries(expressions, client) { - const q = faunadb.query; - vm.createContext(q); + const q = query; + createContext(q); return expressions.map(function (exp, queryNumber) { return function () { - return client - .query(vm.runInContext(escodegen.generate(exp), q)) - .catch(function (err) { - throw new QueryError(escodegen.generate(exp), err, queryNumber + 1); - }); + return client.query(runInContext(generate(exp), q)).catch(function (err) { + throw new QueryError(generate(exp), err, queryNumber + 1); + }); }; }); } -function runQueries(expressions, client) { +export function runQueries(expressions, client) { if (expressions.length === 1) { var f = wrapQueries(expressions, client)[0]; return f(); @@ -385,7 +383,7 @@ function runQueries(expressions, client) { } } -function stringifyEndpoint(endpoint) { +export function stringifyEndpoint(endpoint) { var res = ""; if (endpoint.scheme) { res += endpoint.scheme + "://"; @@ -396,18 +394,3 @@ function stringifyEndpoint(endpoint) { } return res; } - -module.exports = { - saveEndpointOrError: saveEndpointOrError, - saveEndpoint: saveEndpoint, - deleteEndpointOrError: deleteEndpointOrError, - setDefaultEndpoint: setDefaultEndpoint, - validCloudEndpoint: validCloudEndpoint, - loadEndpoints: loadEndpoints, - buildConnectionOptions: buildConnectionOptions, - readFile: readFile, - writeFile: writeFile, - runQueries: runQueries, - stringifyEndpoint: stringifyEndpoint, - getConfigFile: getConfigFile, -}; diff --git a/src/lib/schema-command.js b/src/lib/schema-command.js index fc9e6ea2..3526fa7e 100644 --- a/src/lib/schema-command.js +++ b/src/lib/schema-command.js @@ -1,7 +1,7 @@ -const FaunaCommand = require("./fauna-command.js"); -const fs = require("fs"); -const path = require("path"); -const FormData = require("form-data"); +import FaunaCommand from "./fauna-command"; +import { readFileSync, readdirSync, statSync } from "fs"; +import { join } from "path"; +import FormData from "form-data"; class SchemaCommand extends FaunaCommand { static flags = (() => { @@ -39,8 +39,8 @@ class SchemaCommand extends FaunaCommand { const curr = []; var totalsize = 0; for (const relp of relpaths) { - const fp = path.join(basedir, relp); - const content = fs.readFileSync(fp); + const fp = join(basedir, relp); + const content = readFileSync(fp); totalsize += content.length; if (totalsize > FILESIZE_LIMIT_BYTES) { this.error( @@ -58,12 +58,12 @@ class SchemaCommand extends FaunaCommand { gather(basedir) { const FILE_LIMIT = 256; const go = (rel, curr) => { - const names = fs.readdirSync(path.join(basedir, rel)); + const names = readdirSync(join(basedir, rel)); const subdirs = []; for (const n of names) { - const fp = path.join(basedir, rel, n); - const relp = path.join(rel, n); - const isDir = fs.statSync(fp).isDirectory(); + const fp = join(basedir, rel, n); + const relp = join(rel, n); + const isDir = statSync(fp).isDirectory(); if (n.endsWith(".fsl") && !isDir) { curr.push(relp); } @@ -84,4 +84,4 @@ class SchemaCommand extends FaunaCommand { } } -module.exports = SchemaCommand; +export default SchemaCommand; diff --git a/test/lib/fauna-import-writer.test.js b/test/lib/fauna-import-writer.test.js index db6448a5..504fcb6c 100644 --- a/test/lib/fauna-import-writer.test.js +++ b/test/lib/fauna-import-writer.test.js @@ -1,5 +1,5 @@ const expect = require("expect"); -const getFaunaImportWriter = require("../../src/lib/fauna-import-writer"); +const getFaunaImportWriter = require("../../src/lib/fauna-import-writer").default; const jestMock = require("jest-mock"); const sizeof = require("object-sizeof"); const { UnavailableError, FaunaHTTPError } = require("faunadb").errors; diff --git a/test/tsconfig.json b/test/tsconfig.json index db2d5170..d66fc7b0 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -3,7 +3,5 @@ "compilerOptions": { "noEmit": true }, - "references": [ - { "path": ".." } - ] + "references": [{ "path": ".." }] }