1
0
mirror of https://github.com/bitwarden/jslib synced 2026-01-10 20:43:15 +00:00

Apply Prettier (#581)

This commit is contained in:
Oscar Hinton
2021-12-16 13:36:21 +01:00
committed by GitHub
parent 8b2dfc6cdc
commit 193434461d
589 changed files with 46650 additions and 41924 deletions

View File

@@ -1,108 +1,113 @@
import * as chalk from 'chalk';
import * as chalk from "chalk";
import { StateService } from 'jslib-common/abstractions/state.service';
import { StateService } from "jslib-common/abstractions/state.service";
import { Response } from './models/response';
import { ListResponse } from './models/response/listResponse';
import { MessageResponse } from './models/response/messageResponse';
import { StringResponse } from './models/response/stringResponse';
import { Response } from "./models/response";
import { ListResponse } from "./models/response/listResponse";
import { MessageResponse } from "./models/response/messageResponse";
import { StringResponse } from "./models/response/stringResponse";
export abstract class BaseProgram {
constructor(
private stateService: StateService,
private writeLn: (s: string, finalLine: boolean, error: boolean) => void) { }
constructor(
private stateService: StateService,
private writeLn: (s: string, finalLine: boolean, error: boolean) => void
) {}
protected processResponse(response: Response, exitImmediately = false, dataProcessor: () => string = null) {
if (!response.success) {
if (process.env.BW_QUIET !== 'true') {
if (process.env.BW_RESPONSE === 'true') {
this.writeLn(this.getJson(response), true, false);
} else {
this.writeLn(chalk.redBright(response.message), true, true);
}
}
const exitCode = process.env.BW_CLEANEXIT ? 0 : 1;
if (exitImmediately) {
process.exit(exitCode);
} else {
process.exitCode = exitCode;
}
return;
}
if (process.env.BW_RESPONSE === 'true') {
this.writeLn(this.getJson(response), true, false);
} else if (response.data != null) {
let out: string = dataProcessor != null ? dataProcessor() : null;
if (out == null) {
if (response.data.object === 'string') {
const data = (response.data as StringResponse).data;
if (data != null) {
out = data;
}
} else if (response.data.object === 'list') {
out = this.getJson((response.data as ListResponse).data);
} else if (response.data.object === 'message') {
out = this.getMessage(response);
} else {
out = this.getJson(response.data);
}
}
if (out != null && process.env.BW_QUIET !== 'true') {
this.writeLn(out, true, false);
}
}
if (exitImmediately) {
process.exit(0);
protected processResponse(
response: Response,
exitImmediately = false,
dataProcessor: () => string = null
) {
if (!response.success) {
if (process.env.BW_QUIET !== "true") {
if (process.env.BW_RESPONSE === "true") {
this.writeLn(this.getJson(response), true, false);
} else {
process.exitCode = 0;
this.writeLn(chalk.redBright(response.message), true, true);
}
}
const exitCode = process.env.BW_CLEANEXIT ? 0 : 1;
if (exitImmediately) {
process.exit(exitCode);
} else {
process.exitCode = exitCode;
}
return;
}
protected getJson(obj: any): string {
if (process.env.BW_PRETTY === 'true') {
return JSON.stringify(obj, null, ' ');
if (process.env.BW_RESPONSE === "true") {
this.writeLn(this.getJson(response), true, false);
} else if (response.data != null) {
let out: string = dataProcessor != null ? dataProcessor() : null;
if (out == null) {
if (response.data.object === "string") {
const data = (response.data as StringResponse).data;
if (data != null) {
out = data;
}
} else if (response.data.object === "list") {
out = this.getJson((response.data as ListResponse).data);
} else if (response.data.object === "message") {
out = this.getMessage(response);
} else {
return JSON.stringify(obj);
out = this.getJson(response.data);
}
}
if (out != null && process.env.BW_QUIET !== "true") {
this.writeLn(out, true, false);
}
}
if (exitImmediately) {
process.exit(0);
} else {
process.exitCode = 0;
}
}
protected getJson(obj: any): string {
if (process.env.BW_PRETTY === "true") {
return JSON.stringify(obj, null, " ");
} else {
return JSON.stringify(obj);
}
}
protected getMessage(response: Response): string {
const message = response.data as MessageResponse;
if (process.env.BW_RAW === "true") {
return message.raw;
}
protected getMessage(response: Response): string {
const message = (response.data as MessageResponse);
if (process.env.BW_RAW === 'true') {
return message.raw;
}
let out: string = '';
if (message.title != null) {
if (message.noColor) {
out = message.title;
} else {
out = chalk.greenBright(message.title);
}
}
if (message.message != null) {
if (message.title != null) {
out += '\n';
}
out += message.message;
}
return out.trim() === '' ? null : out;
let out: string = "";
if (message.title != null) {
if (message.noColor) {
out = message.title;
} else {
out = chalk.greenBright(message.title);
}
}
protected async exitIfAuthed() {
const authed = await this.stateService.getIsAuthenticated();
if (authed) {
const email = await this.stateService.getEmail();
this.processResponse(Response.error('You are already logged in as ' + email + '.'), true);
}
if (message.message != null) {
if (message.title != null) {
out += "\n";
}
out += message.message;
}
return out.trim() === "" ? null : out;
}
protected async exitIfNotAuthed() {
const authed = await this.stateService.getIsAuthenticated();
if (!authed) {
this.processResponse(Response.error('You are not logged in.'), true);
}
protected async exitIfAuthed() {
const authed = await this.stateService.getIsAuthenticated();
if (authed) {
const email = await this.stateService.getEmail();
this.processResponse(Response.error("You are already logged in as " + email + "."), true);
}
}
protected async exitIfNotAuthed() {
const authed = await this.stateService.getIsAuthenticated();
if (!authed) {
this.processResponse(Response.error("You are not logged in."), true);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,24 @@
import * as program from 'commander';
import * as program from "commander";
import { AuthService } from 'jslib-common/abstractions/auth.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { AuthService } from "jslib-common/abstractions/auth.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { Response } from '../models/response';
import { MessageResponse } from '../models/response/messageResponse';
import { Response } from "../models/response";
import { MessageResponse } from "../models/response/messageResponse";
export class LogoutCommand {
constructor(private authService: AuthService, private i18nService: I18nService,
private logoutCallback: () => Promise<void>) { }
constructor(
private authService: AuthService,
private i18nService: I18nService,
private logoutCallback: () => Promise<void>
) {}
async run() {
await this.logoutCallback();
this.authService.logOut(() => { /* Do nothing */ });
const res = new MessageResponse('You have logged out.', null);
return Response.success(res);
}
async run() {
await this.logoutCallback();
this.authService.logOut(() => {
/* Do nothing */
});
const res = new MessageResponse("You have logged out.", null);
return Response.success(res);
}
}

View File

@@ -1,86 +1,105 @@
import * as program from 'commander';
import * as fetch from 'node-fetch';
import * as program from "commander";
import * as fetch from "node-fetch";
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { Response } from '../models/response';
import { MessageResponse } from '../models/response/messageResponse';
import { Response } from "../models/response";
import { MessageResponse } from "../models/response/messageResponse";
export class UpdateCommand {
inPkg: boolean = false;
inPkg: boolean = false;
constructor(private platformUtilsService: PlatformUtilsService, private i18nService: I18nService,
private repoName: string, private executableName: string, private showExtendedMessage: boolean) {
this.inPkg = !!(process as any).pkg;
}
constructor(
private platformUtilsService: PlatformUtilsService,
private i18nService: I18nService,
private repoName: string,
private executableName: string,
private showExtendedMessage: boolean
) {
this.inPkg = !!(process as any).pkg;
}
async run(): Promise<Response> {
const currentVersion = await this.platformUtilsService.getApplicationVersion();
async run(): Promise<Response> {
const currentVersion = await this.platformUtilsService.getApplicationVersion();
const response = await fetch.default('https://api.github.com/repos/bitwarden/' +
this.repoName + '/releases/latest');
if (response.status === 200) {
const responseJson = await response.json();
const res = new MessageResponse(null, null);
const response = await fetch.default(
"https://api.github.com/repos/bitwarden/" + this.repoName + "/releases/latest"
);
if (response.status === 200) {
const responseJson = await response.json();
const res = new MessageResponse(null, null);
const tagName: string = responseJson.tag_name;
if (tagName === ('v' + currentVersion)) {
res.title = 'No update available.';
res.noColor = true;
return Response.success(res);
}
const tagName: string = responseJson.tag_name;
if (tagName === "v" + currentVersion) {
res.title = "No update available.";
res.noColor = true;
return Response.success(res);
}
let downloadUrl: string = null;
if (responseJson.assets != null) {
for (const a of responseJson.assets) {
const download: string = a.browser_download_url;
if (download == null) {
continue;
}
let downloadUrl: string = null;
if (responseJson.assets != null) {
for (const a of responseJson.assets) {
const download: string = a.browser_download_url;
if (download == null) {
continue;
}
if (download.indexOf('.zip') === -1) {
continue;
}
if (download.indexOf(".zip") === -1) {
continue;
}
if (process.platform === 'win32' && download.indexOf(this.executableName + '-windows') > -1) {
downloadUrl = download;
break;
} else if (process.platform === 'darwin' && download.indexOf(this.executableName + '-macos') > -1) {
downloadUrl = download;
break;
} else if (process.platform === 'linux' && download.indexOf(this.executableName + '-linux') > -1) {
downloadUrl = download;
break;
}
}
}
res.title = 'A new version is available: ' + tagName;
if (downloadUrl == null) {
downloadUrl = 'https://github.com/bitwarden/' + this.repoName + '/releases';
} else {
res.raw = downloadUrl;
}
res.message = '';
if (responseJson.body != null && responseJson.body !== '') {
res.message = responseJson.body + '\n\n';
}
res.message += 'You can download this update at ' + downloadUrl;
if (this.showExtendedMessage) {
if (this.inPkg) {
res.message += '\n\nIf you installed this CLI through a package manager ' +
'you should probably update using its update command instead.';
} else {
res.message += '\n\nIf you installed this CLI through NPM ' +
'you should update using `npm install -g @bitwarden/' + this.repoName + '`';
}
}
return Response.success(res);
} else {
return Response.error('Error contacting update API: ' + response.status);
if (
process.platform === "win32" &&
download.indexOf(this.executableName + "-windows") > -1
) {
downloadUrl = download;
break;
} else if (
process.platform === "darwin" &&
download.indexOf(this.executableName + "-macos") > -1
) {
downloadUrl = download;
break;
} else if (
process.platform === "linux" &&
download.indexOf(this.executableName + "-linux") > -1
) {
downloadUrl = download;
break;
}
}
}
res.title = "A new version is available: " + tagName;
if (downloadUrl == null) {
downloadUrl = "https://github.com/bitwarden/" + this.repoName + "/releases";
} else {
res.raw = downloadUrl;
}
res.message = "";
if (responseJson.body != null && responseJson.body !== "") {
res.message = responseJson.body + "\n\n";
}
res.message += "You can download this update at " + downloadUrl;
if (this.showExtendedMessage) {
if (this.inPkg) {
res.message +=
"\n\nIf you installed this CLI through a package manager " +
"you should probably update using its update command instead.";
} else {
res.message +=
"\n\nIf you installed this CLI through NPM " +
"you should update using `npm install -g @bitwarden/" +
this.repoName +
"`";
}
}
return Response.success(res);
} else {
return Response.error("Error contacting update API: " + response.status);
}
}
}

View File

@@ -1,45 +1,50 @@
import { BaseResponse } from './response/baseResponse';
import { BaseResponse } from "./response/baseResponse";
export class Response {
static error(error: any, data?: any): Response {
const res = new Response();
res.success = false;
if (typeof (error) === 'string') {
res.message = error;
} else {
res.message = error.message != null ? error.message :
error.toString() === '[object Object]' ? JSON.stringify(error) : error.toString();
}
res.data = data;
return res;
static error(error: any, data?: any): Response {
const res = new Response();
res.success = false;
if (typeof error === "string") {
res.message = error;
} else {
res.message =
error.message != null
? error.message
: error.toString() === "[object Object]"
? JSON.stringify(error)
: error.toString();
}
res.data = data;
return res;
}
static notFound(): Response {
return Response.error('Not found.');
}
static notFound(): Response {
return Response.error("Not found.");
}
static badRequest(message: string): Response {
return Response.error(message);
}
static badRequest(message: string): Response {
return Response.error(message);
}
static multipleResults(ids: string[]): Response {
let msg = 'More than one result was found. Try getting a specific object by `id` instead. ' +
'The following objects were found:';
ids.forEach(id => {
msg += '\n' + id;
});
return Response.error(msg, ids);
}
static multipleResults(ids: string[]): Response {
let msg =
"More than one result was found. Try getting a specific object by `id` instead. " +
"The following objects were found:";
ids.forEach((id) => {
msg += "\n" + id;
});
return Response.error(msg, ids);
}
static success(data?: BaseResponse): Response {
const res = new Response();
res.success = true;
res.data = data;
return res;
}
static success(data?: BaseResponse): Response {
const res = new Response();
res.success = true;
res.data = data;
return res;
}
success: boolean;
message: string;
errorCode: number;
data: BaseResponse;
success: boolean;
message: string;
errorCode: number;
data: BaseResponse;
}

View File

@@ -1,3 +1,3 @@
export interface BaseResponse {
object: string;
object: string;
}

View File

@@ -1,13 +1,13 @@
import { BaseResponse } from './baseResponse';
import { BaseResponse } from "./baseResponse";
export class FileResponse implements BaseResponse {
object: string;
data: Buffer;
fileName: string;
object: string;
data: Buffer;
fileName: string;
constructor(data: Buffer, fileName: string) {
this.object = 'file';
this.data = data;
this.fileName = fileName;
}
constructor(data: Buffer, fileName: string) {
this.object = "file";
this.data = data;
this.fileName = fileName;
}
}

View File

@@ -1,11 +1,11 @@
import { BaseResponse } from './baseResponse';
import { BaseResponse } from "./baseResponse";
export class ListResponse implements BaseResponse {
object: string;
data: BaseResponse[];
object: string;
data: BaseResponse[];
constructor(data: BaseResponse[]) {
this.object = 'list';
this.data = data;
}
constructor(data: BaseResponse[]) {
this.object = "list";
this.data = data;
}
}

View File

@@ -1,15 +1,15 @@
import { BaseResponse } from './baseResponse';
import { BaseResponse } from "./baseResponse";
export class MessageResponse implements BaseResponse {
object: string;
title: string;
message: string;
raw: string;
noColor = false;
object: string;
title: string;
message: string;
raw: string;
noColor = false;
constructor(title: string, message: string) {
this.object = 'message';
this.title = title;
this.message = message;
}
constructor(title: string, message: string) {
this.object = "message";
this.title = title;
this.message = message;
}
}

View File

@@ -1,11 +1,11 @@
import { BaseResponse } from './baseResponse';
import { BaseResponse } from "./baseResponse";
export class StringResponse implements BaseResponse {
object: string;
data: string;
object: string;
data: string;
constructor(data: string) {
this.object = 'string';
this.data = data;
}
constructor(data: string) {
this.object = "string";
this.data = data;
}
}

View File

@@ -1,157 +1,166 @@
import * as child_process from 'child_process';
import * as child_process from "child_process";
import { DeviceType } from 'jslib-common/enums/deviceType';
import { ThemeType } from 'jslib-common/enums/themeType';
import { DeviceType } from "jslib-common/enums/deviceType";
import { ThemeType } from "jslib-common/enums/themeType";
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
// tslint:disable-next-line
const open = require('open');
const open = require("open");
export class CliPlatformUtilsService implements PlatformUtilsService {
identityClientId: string;
identityClientId: string;
private deviceCache: DeviceType = null;
private deviceCache: DeviceType = null;
constructor(identityClientId: string, private packageJson: any) {
this.identityClientId = identityClientId;
constructor(identityClientId: string, private packageJson: any) {
this.identityClientId = identityClientId;
}
getDevice(): DeviceType {
if (!this.deviceCache) {
switch (process.platform) {
case "win32":
this.deviceCache = DeviceType.WindowsDesktop;
break;
case "darwin":
this.deviceCache = DeviceType.MacOsDesktop;
break;
case "linux":
default:
this.deviceCache = DeviceType.LinuxDesktop;
break;
}
}
getDevice(): DeviceType {
if (!this.deviceCache) {
switch (process.platform) {
case 'win32':
this.deviceCache = DeviceType.WindowsDesktop;
break;
case 'darwin':
this.deviceCache = DeviceType.MacOsDesktop;
break;
case 'linux':
default:
this.deviceCache = DeviceType.LinuxDesktop;
break;
}
}
return this.deviceCache;
}
return this.deviceCache;
}
getDeviceString(): string {
const device = DeviceType[this.getDevice()].toLowerCase();
return device.replace("desktop", "");
}
getDeviceString(): string {
const device = DeviceType[this.getDevice()].toLowerCase();
return device.replace('desktop', '');
}
isFirefox() {
return false;
}
isFirefox() {
return false;
}
isChrome() {
return false;
}
isChrome() {
return false;
}
isEdge() {
return false;
}
isEdge() {
return false;
}
isOpera() {
return false;
}
isOpera() {
return false;
}
isVivaldi() {
return false;
}
isVivaldi() {
return false;
}
isSafari() {
return false;
}
isSafari() {
return false;
}
isIE() {
return false;
}
isIE() {
return false;
}
isMacAppStore() {
return false;
}
isMacAppStore() {
return false;
}
isViewOpen() {
return Promise.resolve(false);
}
isViewOpen() {
return Promise.resolve(false);
launchUri(uri: string, options?: any): void {
if (process.platform === "linux") {
child_process.spawnSync("xdg-open", [uri]);
} else {
open(uri);
}
}
launchUri(uri: string, options?: any): void {
if (process.platform === 'linux') {
child_process.spawnSync('xdg-open', [uri]);
} else {
open(uri);
}
}
saveFile(win: Window, blobData: any, blobOptions: any, fileName: string): void {
throw new Error("Not implemented.");
}
saveFile(win: Window, blobData: any, blobOptions: any, fileName: string): void {
throw new Error('Not implemented.');
}
getApplicationVersion(): Promise<string> {
return Promise.resolve(this.packageJson.version);
}
getApplicationVersion(): Promise<string> {
return Promise.resolve(this.packageJson.version);
}
getApplicationVersionSync(): string {
return this.packageJson.version;
}
getApplicationVersionSync(): string {
return this.packageJson.version;
}
supportsWebAuthn(win: Window) {
return false;
}
supportsWebAuthn(win: Window) {
return false;
}
supportsDuo(): boolean {
return false;
}
supportsDuo(): boolean {
return false;
}
showToast(
type: "error" | "success" | "warning" | "info",
title: string,
text: string | string[],
options?: any
): void {
throw new Error("Not implemented.");
}
showToast(type: 'error' | 'success' | 'warning' | 'info', title: string, text: string | string[],
options?: any): void {
throw new Error('Not implemented.');
}
showDialog(
text: string,
title?: string,
confirmText?: string,
cancelText?: string,
type?: string
): Promise<boolean> {
throw new Error("Not implemented.");
}
showDialog(text: string, title?: string, confirmText?: string, cancelText?: string, type?: string):
Promise<boolean> {
throw new Error('Not implemented.');
}
isDev(): boolean {
return process.env.BWCLI_ENV === "development";
}
isDev(): boolean {
return process.env.BWCLI_ENV === 'development';
}
isSelfHost(): boolean {
return false;
}
isSelfHost(): boolean {
return false;
}
copyToClipboard(text: string, options?: any): void {
throw new Error("Not implemented.");
}
copyToClipboard(text: string, options?: any): void {
throw new Error('Not implemented.');
}
readFromClipboard(options?: any): Promise<string> {
throw new Error("Not implemented.");
}
readFromClipboard(options?: any): Promise<string> {
throw new Error('Not implemented.');
}
supportsBiometric(): Promise<boolean> {
return Promise.resolve(false);
}
supportsBiometric(): Promise<boolean> {
return Promise.resolve(false);
}
authenticateBiometric(): Promise<boolean> {
return Promise.resolve(false);
}
authenticateBiometric(): Promise<boolean> {
return Promise.resolve(false);
}
getDefaultSystemTheme() {
return Promise.resolve(ThemeType.Light as ThemeType.Light | ThemeType.Dark);
}
getDefaultSystemTheme() {
return Promise.resolve(ThemeType.Light as ThemeType.Light | ThemeType.Dark);
}
onDefaultSystemThemeChange() {
/* noop */
}
onDefaultSystemThemeChange() {
/* noop */
}
getEffectiveTheme() {
return Promise.resolve(ThemeType.Light);
}
getEffectiveTheme() {
return Promise.resolve(ThemeType.Light);
}
supportsSecureStorage(): boolean {
return false;
}
supportsSecureStorage(): boolean {
return false;
}
}

View File

@@ -1,23 +1,23 @@
import { LogLevelType } from 'jslib-common/enums/logLevelType';
import { LogLevelType } from "jslib-common/enums/logLevelType";
import { ConsoleLogService as BaseConsoleLogService } from 'jslib-common/services/consoleLog.service';
import { ConsoleLogService as BaseConsoleLogService } from "jslib-common/services/consoleLog.service";
export class ConsoleLogService extends BaseConsoleLogService {
constructor(isDev: boolean, filter: (level: LogLevelType) => boolean = null) {
super(isDev, filter);
constructor(isDev: boolean, filter: (level: LogLevelType) => boolean = null) {
super(isDev, filter);
}
write(level: LogLevelType, message: string) {
if (this.filter != null && this.filter(level)) {
return;
}
write(level: LogLevelType, message: string) {
if (this.filter != null && this.filter(level)) {
return;
}
if (process.env.BW_RESPONSE === 'true') {
// tslint:disable-next-line
console.error(message);
return;
}
super.write(level, message);
if (process.env.BW_RESPONSE === "true") {
// tslint:disable-next-line
console.error(message);
return;
}
super.write(level, message);
}
}