Skip to content

Commit

Permalink
Move to ESM
Browse files Browse the repository at this point in the history
Change-type: major
  • Loading branch information
otaviojacobi committed Dec 30, 2024
1 parent 0900db5 commit 690c503
Show file tree
Hide file tree
Showing 190 changed files with 911 additions and 925 deletions.
2 changes: 0 additions & 2 deletions .eslintignore

This file was deleted.

21 changes: 0 additions & 21 deletions .eslintrc.js

This file was deleted.

2 changes: 1 addition & 1 deletion automation/build-bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { exec, execFile } from 'child_process';
import type { Stats } from 'fs';
import * as fs from 'fs-extra';
import * as klaw from 'klaw';
import * as path from 'path';
import path from 'path';
import * as rimraf from 'rimraf';
import { promisify } from 'util';
import { notarize } from '@electron/notarize';
Expand Down
2 changes: 1 addition & 1 deletion automation/capitanodoc/capitanodoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import * as path from 'path';
import path from 'path';
import { MarkdownFileParser } from './utils';
import { GlobSync } from 'glob';

Expand Down
2 changes: 1 addition & 1 deletion automation/capitanodoc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import path from 'path';
import { getCapitanoDoc } from './capitanodoc';
import type { Category, Document, OclifCommand } from './doc-types';
import * as markdown from './markdown';
Expand Down
2 changes: 1 addition & 1 deletion automation/capitanodoc/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
import { Parser } from '@oclif/core';
import * as ent from 'ent';
import * as _ from 'lodash';
import _ from 'lodash';

import { capitanoizeOclifUsage } from '../../src/utils/oclif-utils';
import type { Category, Document } from './doc-types';
Expand Down
2 changes: 1 addition & 1 deletion automation/capitanodoc/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import * as fs from 'fs';
import fs from 'fs';
import * as readline from 'readline';

export class MarkdownFileParser {
Expand Down
4 changes: 2 additions & 2 deletions automation/check-doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@

// eslint-disable-next-line no-restricted-imports
import { stripIndent } from 'common-tags';
import * as _ from 'lodash';
import _ from 'lodash';
import { promises as fs } from 'fs';
import * as path from 'path';
import path from 'path';
import { simpleGit } from 'simple-git';

const ROOT = path.normalize(path.join(__dirname, '..'));
Expand Down
2 changes: 1 addition & 1 deletion automation/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import * as _ from 'lodash';
import _ from 'lodash';

import {
buildOclifInstaller,
Expand Down
4 changes: 2 additions & 2 deletions automation/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
*/

import { spawn } from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import path from 'path';
import fs from 'fs';
import * as whichMod from 'which';

export const ROOT = path.join(__dirname, '..');
Expand Down
12 changes: 7 additions & 5 deletions bin/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ process.env.OCLIF_TS_NODE = '0';

async function run() {
// Use fast-boot to cache require lookups, speeding up startup
await require('../build/fast-boot').start();
const { start } = await import('../build/fast-boot.js');
await start();

// Set the desired es version for downstream modules that support it
require('@balena/es-version').set('es2018');

// Run the CLI
await require('../build/app').run(undefined, { dir: __dirname });
(await import('@balena/es-version')).set('es2018');
//
// // Run the CLI
const { run } = await import('../build/app.js');
run(undefined, { dir: import.meta.url });
}

void run();
10 changes: 8 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
const { FlatCompat } = require('@eslint/eslintrc');
import { FlatCompat } from '@eslint/eslintrc';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import Module from 'node:module';

const __dirname = dirname(fileURLToPath(import.meta.url));
const require = Module.createRequire(import.meta.url);

const compat = new FlatCompat({
baseDirectory: __dirname,
});
module.exports = [
export default [
...require('@balena/lint/config/eslint.config'),
...compat.config({
parserOptions: {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"url": "[email protected]:balena-io/balena-cli.git"
},
"preferGlobal": true,
"type": "module",
"files": [
"bin/.fast-boot.json",
"bin/",
Expand Down
49 changes: 20 additions & 29 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,24 @@
* limitations under the License.
*/

import * as packageJSON from '../package.json';
import type { AppOptions } from './preparser';
import type { AppOptions } from './preparser.js';
import {
checkDeletedCommand,
preparseArgs,
unsupportedFlag,
} from './preparser';
import { CliSettings } from './utils/bootstrap';
import { onceAsync } from './utils/lazy';
} from './preparser.js';
import { CliSettings } from './utils/bootstrap.js';
import { onceAsync, getPackageJson } from './utils/lazy.js';
import { run as mainRun, settings } from '@oclif/core';

const packageJSON = getPackageJson();

/**
* Sentry.io setup
* @see https://docs.sentry.io/error-reporting/quickstart/?platform=node
*/
export const setupSentry = onceAsync(async () => {
const config = await import('./config');
const config = await import('./config.js');
const Sentry = await import('@sentry/node');
Sentry.init({
autoSessionTracking: false,
Expand All @@ -51,30 +52,20 @@ export const setupSentry = onceAsync(async () => {
async function checkNodeVersion() {
const validNodeVersions = packageJSON.engines.node;
if (!(await import('semver')).satisfies(process.version, validNodeVersions)) {
const { getNodeEngineVersionWarn } = await import('./utils/messages');
const { getNodeEngineVersionWarn } = await import('./utils/messages.js');
console.warn(getNodeEngineVersionWarn(process.version, validNodeVersions));
}
}

/** Setup balena-sdk options that are shared with imported packages */
function setupBalenaSdkSharedOptions(settings: CliSettings) {
const BalenaSdk = require('balena-sdk') as typeof import('balena-sdk');
async function setupBalenaSdkSharedOptions(settings: CliSettings) {
const BalenaSdk = await import('balena-sdk');
BalenaSdk.setSharedOptions({
apiUrl: settings.get<string>('apiUrl'),
dataDirectory: settings.get<string>('dataDirectory'),
});
}

/**
* Addresses the console warning:
* (node:49500) MaxListenersExceededWarning: Possible EventEmitter memory
* leak detected. 11 error listeners added. Use emitter.setMaxListeners() to
* increase limit
*/
export function setMaxListeners(maxListeners: number) {
require('events').EventEmitter.defaultMaxListeners = maxListeners;
}

/** Selected CLI initialization steps */
async function init() {
if (process.env.BALENARC_NO_SENTRY) {
Expand All @@ -89,13 +80,13 @@ async function init() {
const settings = new CliSettings();

// Proxy setup should be done early on, before loading balena-sdk
await (await import('./utils/proxy')).setupGlobalHttpProxy(settings);
await (await import('./utils/proxy.js')).setupGlobalHttpProxy(settings);

setupBalenaSdkSharedOptions(settings);
await setupBalenaSdkSharedOptions(settings);

// check for CLI updates once a day
if (!process.env.BALENARC_OFFLINE_MODE) {
(await import('./utils/update')).notify();
(await import('./utils/update.js')).notify();
}
}

Expand All @@ -104,7 +95,7 @@ async function oclifRun(command: string[], options: AppOptions) {
let deprecationPromise: Promise<void> | undefined;
// check and enforce the CLI's deprecation policy
if (!(unsupportedFlag || process.env.BALENARC_UNSUPPORTED)) {
const { DeprecationChecker } = await import('./deprecation');
const { DeprecationChecker } = await import('./deprecation.js');
const deprecationChecker = new DeprecationChecker(packageJSON.version);
// warnAndAbortIfDeprecated uses previously cached data only
await deprecationChecker.warnAndAbortIfDeprecated();
Expand Down Expand Up @@ -147,11 +138,11 @@ async function oclifRun(command: string[], options: AppOptions) {
// the try/catch block above, execution does not get past the
// Promise.all() call below, but I don't understand why.
if (isEEXIT) {
(await import('./fast-boot')).stop();
(await import('./fast-boot.js')).stop();
}
})(!options.noFlush);

const { trackPromise } = await import('./hooks/prerun');
const { trackPromise } = await import('./hooks/prerun.js');

await Promise.all([trackPromise, deprecationPromise, runPromise]);
}
Expand All @@ -160,23 +151,23 @@ async function oclifRun(command: string[], options: AppOptions) {
export async function run(cliArgs = process.argv, options: AppOptions) {
try {
const { setOfflineModeEnvVars, normalizeEnvVars } = await import(
'./utils/bootstrap'
'./utils/bootstrap.js'
);
setOfflineModeEnvVars();
normalizeEnvVars();

await init();

// Look for commands that have been removed and if so, exit with a notice
checkDeletedCommand(cliArgs.slice(2));
await checkDeletedCommand(cliArgs.slice(2));

const args = await preparseArgs(cliArgs);
await oclifRun(args, options);
} catch (err) {
await (await import('./errors')).handleError(err);
await (await import('./errors.js')).handleError(err);
} finally {
try {
(await import('./fast-boot')).stop();
(await import('./fast-boot.js')).stop();
} catch (e) {
if (process.env.DEBUG) {
console.error(`[debug] Stopping fast-boot: ${e}`);
Expand Down
8 changes: 4 additions & 4 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { getBalenaSdk } from '../utils/lazy';
import { LoginServer } from './server';
import { getBalenaSdk } from '../utils/lazy.js';
import { LoginServer } from './server.js';

/**
* @module auth
Expand All @@ -42,7 +42,7 @@ import { LoginServer } from './server';
* console.log("My session token is: #{sessionToken}")
*/
export async function login({ host = '127.0.0.1', port = 0 }) {
const utils = await import('./utils');
const utils = await import('./utils.js');

const loginServer = new LoginServer();
const {
Expand All @@ -55,7 +55,7 @@ export async function login({ host = '127.0.0.1', port = 0 }) {
const loginUrl = await utils.getDashboardLoginURL(callbackUrl);

console.info(`Opening web browser for URL:\n${loginUrl}`);
const open = await import('open');
const { default: open } = await import('open');
await open(loginUrl, { wait: false });

const balena = getBalenaSdk();
Expand Down
10 changes: 5 additions & 5 deletions src/auth/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import * as bodyParser from 'body-parser';
import bodyParser from 'body-parser';
import { EventEmitter } from 'events';
import * as express from 'express';
import express from 'express';
import type { Socket } from 'net';
import * as path from 'path';
import path from 'path';

import * as utils from './utils';
import { ExpectedError } from '../errors';
import * as utils from './utils.js';
import { ExpectedError } from '../errors.js';

export class LoginServer extends EventEmitter {
protected expressApp: express.Express;
Expand Down
2 changes: 1 addition & 1 deletion src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { getBalenaSdk } from '../utils/lazy';
import { getBalenaSdk } from '../utils/lazy.js';

/**
* Get dashboard CLI login URL
Expand Down
6 changes: 3 additions & 3 deletions src/commands/api-key/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
*/

import { Args, Command } from '@oclif/core';
import { ExpectedError } from '../../errors';
import { getBalenaSdk, stripIndent } from '../../utils/lazy';
import { ExpectedError } from '../../errors.js';
import { getBalenaSdk, stripIndent } from '../../utils/lazy.js';

async function isLoggedInWithJwt() {
const balena = getBalenaSdk();
try {
const token = await balena.auth.getToken();
const { default: jwtDecode } = await import('jwt-decode');
jwtDecode(token);
jwtDecode.default(token);
return true;
} catch {
return false;
Expand Down
6 changes: 3 additions & 3 deletions src/commands/api-key/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
*/

import { Flags, Command } from '@oclif/core';
import * as cf from '../../utils/common-flags';
import { getBalenaSdk, getVisuals, stripIndent } from '../../utils/lazy';
import * as cf from '../../utils/common-flags.js';
import { getBalenaSdk, getVisuals, stripIndent } from '../../utils/lazy.js';

export default class APIKeyListCmd extends Command {
public static aliases = ['api-keys'];
Expand Down Expand Up @@ -45,7 +45,7 @@ export default class APIKeyListCmd extends Command {
public async run() {
const { flags: options } = await this.parse(APIKeyListCmd);

const { getApplication } = await import('../../utils/sdk');
const { getApplication } = await import('../../utils/sdk.js');
const actorId = options.fleet
? (
await getApplication(getBalenaSdk(), options.fleet, {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/api-key/revoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/

import { Args, Command } from '@oclif/core';
import { getBalenaSdk, stripIndent } from '../../utils/lazy';
import { getBalenaSdk, stripIndent } from '../../utils/lazy.js';

export default class RevokeCmd extends Command {
public static description = stripIndent`
Expand Down
Loading

0 comments on commit 690c503

Please sign in to comment.