Skip to content

Commit

Permalink
Add inversify lifecycle to frontend preload script (#12590)
Browse files Browse the repository at this point in the history
  • Loading branch information
msujew authored Sep 13, 2023
1 parent 6843880 commit 35865a9
Show file tree
Hide file tree
Showing 20 changed files with 374 additions and 248 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import * as os from 'os';
import * as fs from 'fs-extra';
import { ApplicationPackage } from '@theia/application-package';

Expand All @@ -30,33 +29,6 @@ export abstract class AbstractGenerator {
protected options: GeneratorOptions = {}
) { }

protected compileFrontendModuleImports(modules: Map<string, string>): string {
const splitFrontend = this.options.splitFrontend ?? this.options.mode !== 'production';
return this.compileModuleImports(modules, splitFrontend ? 'import' : 'require');
}

protected compileBackendModuleImports(modules: Map<string, string>): string {
return this.compileModuleImports(modules, 'require');
}

protected compileElectronMainModuleImports(modules?: Map<string, string>): string {
return modules && this.compileModuleImports(modules, 'require') || '';
}

protected compileModuleImports(modules: Map<string, string>, fn: 'import' | 'require'): string {
if (modules.size === 0) {
return '';
}
const lines = Array.from(modules.keys()).map(moduleName => {
const invocation = `${fn}('${modules.get(moduleName)}')`;
if (fn === 'require') {
return `Promise.resolve(${invocation})`;
}
return invocation;
}).map(statement => ` .then(function () { return ${statement}.then(load) })`);
return os.EOL + lines.join(os.EOL);
}

protected ifBrowser(value: string, defaultValue: string = ''): string {
return this.pck.ifBrowser(value, defaultValue);
}
Expand Down Expand Up @@ -87,8 +59,7 @@ export abstract class AbstractGenerator {
}

protected prettyStringify(object: object): string {
// eslint-disable-next-line no-null/no-null
return JSON.stringify(object, null, 4);
return JSON.stringify(object, undefined, 4);
}

}
85 changes: 46 additions & 39 deletions dev-packages/application-manager/src/generator/backend-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { EOL } from 'os';
import { AbstractGenerator } from './abstract-generator';

export class BackendGenerator extends AbstractGenerator {
Expand Down Expand Up @@ -53,45 +54,47 @@ const { Container } = require('inversify');
const { resolve } = require('path');
const { app } = require('electron');
// Fix the window reloading issue, see: https://github.com/electron/electron/issues/22119
app.allowRendererProcessReuse = false;
const config = ${this.prettyStringify(this.pck.props.frontend.config)};
const isSingleInstance = ${this.pck.props.backend.config.singleInstance === true ? 'true' : 'false'};
if (isSingleInstance && !app.requestSingleInstanceLock()) {
// There is another instance running, exit now. The other instance will request focus.
app.quit();
return;
}
const container = new Container();
container.load(electronMainApplicationModule);
container.bind(ElectronMainApplicationGlobals).toConstantValue({
THEIA_APP_PROJECT_PATH: resolve(__dirname, '..', '..'),
THEIA_BACKEND_MAIN_PATH: resolve(__dirname, 'main.js'),
THEIA_FRONTEND_HTML_PATH: resolve(__dirname, '..', '..', 'lib', 'frontend', 'index.html'),
});
function load(raw) {
return Promise.resolve(raw.default).then(module =>
container.load(module)
);
}
async function start() {
const application = container.get(ElectronMainApplication);
await application.start(config);
}
(async () => {
if (isSingleInstance && !app.requestSingleInstanceLock()) {
// There is another instance running, exit now. The other instance will request focus.
app.quit();
return;
}
const container = new Container();
container.load(electronMainApplicationModule);
container.bind(ElectronMainApplicationGlobals).toConstantValue({
THEIA_APP_PROJECT_PATH: resolve(__dirname, '..', '..'),
THEIA_BACKEND_MAIN_PATH: resolve(__dirname, 'main.js'),
THEIA_FRONTEND_HTML_PATH: resolve(__dirname, '..', '..', 'lib', 'frontend', 'index.html'),
});
function load(raw) {
return Promise.resolve(raw.default).then(module =>
container.load(module)
);
}
async function start() {
const application = container.get(ElectronMainApplication);
await application.start(config);
}
module.exports = Promise.resolve()${this.compileElectronMainModuleImports(electronMainModules)}
.then(start).catch(reason => {
try {
${Array.from(electronMainModules?.values() ?? [], jsModulePath => `\
await load(require('${jsModulePath}'));`).join(EOL)}
await start();
} catch (reason) {
console.error('Failed to start the electron application.');
if (reason) {
console.error(reason);
}
app.quit();
});
};
})();
`;
}

Expand Down Expand Up @@ -127,27 +130,31 @@ function defaultServeStatic(app) {
}
function load(raw) {
return Promise.resolve(raw.default).then(
module => container.load(module)
return Promise.resolve(raw).then(
module => container.load(module.default)
);
}
function start(port, host, argv = process.argv) {
async function start(port, host, argv = process.argv) {
if (!container.isBound(BackendApplicationServer)) {
container.bind(BackendApplicationServer).toConstantValue({ configure: defaultServeStatic });
}
return container.get(CliManager).initializeCli(argv).then(() => {
return container.get(BackendApplication).start(port, host);
});
await container.get(CliManager).initializeCli(argv);
return container.get(BackendApplication).start(port, host);
}
module.exports = (port, host, argv) => Promise.resolve()${this.compileBackendModuleImports(backendModules)}
.then(() => start(port, host, argv)).catch(error => {
module.exports = async (port, host, argv) => {
try {
${Array.from(backendModules.values(), jsModulePath => `\
await load(require('${jsModulePath}'));`).join(EOL)}
return await start(port, host, argv);
} catch (error) {
console.error('Failed to start the backend application:');
console.error(error);
process.exitCode = 1;
throw error;
});
}
}
`;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@

/* eslint-disable @typescript-eslint/indent */

import { EOL } from 'os';
import { AbstractGenerator, GeneratorOptions } from './abstract-generator';
import { existsSync, readFileSync } from 'fs';

export class FrontendGenerator extends AbstractGenerator {

async generate(options?: GeneratorOptions): Promise<void> {
await this.write(this.pck.frontend('index.html'), this.compileIndexHtml(this.pck.targetFrontendModules));
await this.write(this.pck.frontend('index.js'), this.compileIndexJs(this.pck.targetFrontendModules));
await this.write(this.pck.frontend('index.js'), this.compileIndexJs(this.pck.targetFrontendModules, this.pck.frontendPreloadModules));
await this.write(this.pck.frontend('secondary-window.html'), this.compileSecondaryWindowHtml());
await this.write(this.pck.frontend('secondary-index.js'), this.compileSecondaryIndexJs(this.pck.secondaryWindowModules));
if (this.pck.isElectron()) {
Expand Down Expand Up @@ -68,10 +69,7 @@ export class FrontendGenerator extends AbstractGenerator {
<title>${this.pck.props.frontend.config.applicationName}</title>`;
}

protected compileIndexJs(frontendModules: Map<string, string>): string {
const compiledModuleImports = this.compileFrontendModuleImports(frontendModules)
// fix the generated indentation
.replace(/^ /g, ' ');
protected compileIndexJs(frontendModules: Map<string, string>, frontendPreloadModules: Map<string, string>): string {
return `\
// @ts-check
${this.ifBrowser("require('es6-promise/auto');")}
Expand All @@ -89,40 +87,58 @@ self.MonacoEnvironment = {
}
}`)}
const preloader = require('@theia/core/lib/browser/preloader');
function load(container, jsModule) {
return Promise.resolve(jsModule)
.then(containerModule => container.load(containerModule.default));
}
// We need to fetch some data from the backend before the frontend starts (nls, os)
module.exports = preloader.preload().then(() => {
const { FrontendApplication } = require('@theia/core/lib/browser');
const { frontendApplicationModule } = require('@theia/core/lib/browser/frontend-application-module');
async function preload(parent) {
const container = new Container();
container.parent = parent;
try {
${Array.from(frontendPreloadModules.values(), jsModulePath => `\
await load(container, import('${jsModulePath}'));`).join(EOL)}
const { Preloader } = require('@theia/core/lib/browser/preload/preloader');
const preloader = container.get(Preloader);
await preloader.initialize();
} catch (reason) {
console.error('Failed to run preload scripts.');
if (reason) {
console.error(reason);
}
}
}
module.exports = (async () => {
const { messagingFrontendModule } = require('@theia/core/lib/${this.pck.isBrowser()
? 'browser/messaging/messaging-frontend-module'
: 'electron-browser/messaging/electron-messaging-frontend-module'}');
? 'browser/messaging/messaging-frontend-module'
: 'electron-browser/messaging/electron-messaging-frontend-module'}');
const container = new Container();
container.load(messagingFrontendModule);
await preload(container);
const { FrontendApplication } = require('@theia/core/lib/browser');
const { frontendApplicationModule } = require('@theia/core/lib/browser/frontend-application-module');
const { loggerFrontendModule } = require('@theia/core/lib/browser/logger-frontend-module');
const container = new Container();
container.load(frontendApplicationModule);
container.load(messagingFrontendModule);
container.load(loggerFrontendModule);
return Promise.resolve()${compiledModuleImports}
.then(start).catch(reason => {
console.error('Failed to start the frontend application.');
if (reason) {
console.error(reason);
}
});
function load(jsModule) {
return Promise.resolve(jsModule.default)
.then(containerModule => container.load(containerModule));
try {
${Array.from(frontendModules.values(), jsModulePath => `\
await load(container, import('${jsModulePath}'));`).join(EOL)}
await start();
} catch (reason) {
console.error('Failed to start the frontend application.');
if (reason) {
console.error(reason);
}
}
function start() {
(window['theia'] = window['theia'] || {}).container = container;
return container.get(FrontendApplication).start();
}
});
})();
`;
}

Expand Down Expand Up @@ -172,40 +188,26 @@ module.exports = preloader.preload().then(() => {
</html>`;
}

protected compileSecondaryModuleImports(secondaryWindowModules: Map<string, string>): string {
const lines = Array.from(secondaryWindowModules.entries())
.map(([moduleName, path]) => ` container.load(require('${path}').default);`);
return '\n' + lines.join('\n');
}

protected compileSecondaryIndexJs(secondaryWindowModules: Map<string, string>): string {
const compiledModuleImports = this.compileSecondaryModuleImports(secondaryWindowModules)
// fix the generated indentation
.replace(/^ /g, ' ');
return `\
// @ts-check
require('reflect-metadata');
const { Container } = require('inversify');
const preloader = require('@theia/core/lib/browser/preloader');
module.exports = Promise.resolve().then(() => {
const { frontendApplicationModule } = require('@theia/core/lib/browser/frontend-application-module');
const container = new Container();
container.load(frontendApplicationModule);
${compiledModuleImports}
${Array.from(secondaryWindowModules.values(), jsModulePath => `\
container.load(require('${jsModulePath}').default);`).join(EOL)}
});
`;
}

compilePreloadJs(): string {
const lines = Array.from(this.pck.preloadModules)
.map(([moduleName, path]) => `require('${path}').preload();`);
const imports = '\n' + lines.join('\n');

return `\
// @ts-check
${imports}
${Array.from(this.pck.preloadModules.values(), path => `require('${path}').preload();`).join(EOL)}
`;
}
}
Loading

0 comments on commit 35865a9

Please sign in to comment.