UNPKG

openfin-cli

Version:

Supports command line development in the OpenFin environment.

202 lines (201 loc) 8.29 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import crypto from 'crypto'; import dns from 'dns'; import fs from 'fs/promises'; import { connect, launch as launchOpenFinFromAdapter } from 'openfin-adapter'; import os from 'os'; import path from 'path'; import { reportUsage } from './report-usage.js'; import { fetch, formatTimeFromMs, isURL } from './utils.js'; import { manifestSchema } from './validateManifest.js'; if (typeof dns.setDefaultResultOrder === 'function') { dns.setDefaultResultOrder('ipv4first'); } let launchTime; export const openfinCli = (cli) => __awaiter(void 0, void 0, void 0, function* () { const { config, url, launch, devtoolsPort = 9090, runtimeVersion = 'stable', save, platform } = cli; let manifestUrl = config; let buildConfig; let configObject; try { if (url) { buildConfig = true; const manifestInfo = yield writeManifest(url.split(','), platform, devtoolsPort, runtimeVersion, save); manifestUrl = manifestInfo.filepath; configObject = manifestInfo.manifest; } if (launch) { if (!buildConfig && manifestUrl) { if (manifestUrl && isURL(manifestUrl)) { try { global.logger.debug(`Fetching manifest from: ${manifestUrl}`); const fetchedConfig = yield fetch(manifestUrl); configObject = manifestSchema.parse(fetchedConfig); global.logger.debug('Manifest', JSON.stringify(config)); } catch (error) { if (error instanceof Error) { global.logger.error(`Failed to fetch manifest from ${manifestUrl} with error: ${error.message}`); global.logger.debug(JSON.stringify(error)); process.exit(1); } else { throw error; } } } else { manifestUrl = path.resolve(manifestUrl); try { global.logger.debug(`Reading manifest from: ${manifestUrl}`); const configBuffer = yield fs.readFile(manifestUrl); configObject = JSON.parse(configBuffer.toString()); global.logger.debug('Manifest:', JSON.stringify(config)); } catch (error) { if (error instanceof Error) { global.logger.error(`Failed to get manifest from ${manifestUrl} with error: ${error.message}`); global.logger.debug(JSON.stringify(error)); process.exit(1); } else { throw error; } } } } if (!configObject) { throw new Error('No config object found'); } if (!manifestUrl) { throw new Error('No manifest url found'); } reportUsage('START', manifestUrl, configObject); launchOpenfin(manifestUrl, config, configObject); } } catch (error) { globalThis.logger.error('Failed:', JSON.stringify(error)); } }); const launchOpenfin = (manifestUrl, config, configObject) => __awaiter(void 0, void 0, void 0, function* () { try { global.logger.info(`Launching OpenFin with manifest: ${manifestUrl}`); launchTime = Date.now(); const port = yield launchOpenFinFromAdapter({ manifestUrl }); global.logger.debug('Application Launched'); global.logger.debug(`Connecting to devtool port: ${port}`); const fin = yield connect({ uuid: `adapter-connection-${crypto.randomUUID()}`, address: `ws://localhost:${port}`, nonPersistent: true, }); global.logger.debug(`Connected to devtool port: ${port}`); fin.once('disconnected', () => { global.logger.info(`Disconnected from application, exiting after ${formatTimeFromMs(Date.now() - launchTime)}`); process.exit(); }); global.logger.debug('Disconnect Listener Added'); } catch (error) { const err = error instanceof Error || error instanceof String ? error.toString() : JSON.stringify(error); reportUsage(err.toString(), config, configObject); // Maybe check what the error is and decide log level on that // Sometimes errors are thrown when they shouldn't be global.logger.warn('Error thrown launching/connecting to application instance', JSON.stringify(err)); } }); const writeManifest = (urls, isPlatform, devtoolsPort, runtime, manifestName) => __awaiter(void 0, void 0, void 0, function* () { const uuid = `app-${crypto.randomUUID()}`; const version = runtime; let manifest; const generateViewObjWithUrl = (url) => ({ type: 'component', componentName: 'view', componentState: { name: `view-${crypto.randomUUID()}`, url, }, }); const buildContent = () => { const content = []; urls.forEach((url) => { content.push(generateViewObjWithUrl(url)); }); return content; }; if (isPlatform) { const content = buildContent(); manifest = { runtime: { version, }, platform: { uuid, autoShow: false, }, snapshot: { windows: [ { saveWindowState: false, backgroundThrottling: true, layout: { content: [ { type: 'row', id: 'no-drop-target', content, }, ], }, }, ], }, }; } else { manifest = { devtools_port: devtoolsPort, startup_app: { name: uuid, url: urls[0], uuid, saveWindowState: false, autoShow: true, }, runtime: { version, }, }; } global.logger.debug('Stringifying manifest'); const manifestJson = JSON.stringify(manifest, null, 4); global.logger.debug(`Manifest stringified successfully ${manifestJson}`); let filepath; if (manifestName) { filepath = path.join(process.cwd(), manifestName); } else { filepath = path.join(os.tmpdir(), `${uuid}.json`); } try { global.logger.debug(`Writing manifest to: ${path.resolve(filepath)}`); yield fs.writeFile(filepath, manifestJson); global.logger.info(`Manifest written to: ${path.resolve(filepath)}`); } catch (error) { global.logger.error(`Failed to write manifest ${JSON.stringify(error)}`); } return { manifest, filepath, }; });