Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add inversify lifecycle to frontend preload script #12590

Merged
merged 7 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
31 changes: 20 additions & 11 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 @@ -84,8 +85,12 @@ async function start() {
await application.start(config);
}

module.exports = Promise.resolve()${this.compileElectronMainModuleImports(electronMainModules)}
.then(start).catch(reason => {
module.exports = async () => {
try {
${Array.from(electronMainModules?.values() ?? [], jsModulePath => `\
await load(container, import('${jsModulePath}'));`).join(EOL)}
await start();
} catch (reason) {
console.error('Failed to start the electron application.');
if (reason) {
console.error(reason);
Expand Down Expand Up @@ -127,27 +132,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)}
`;
}
}
40 changes: 12 additions & 28 deletions dev-packages/application-package/src/application-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export class ApplicationPackage {
}

protected _frontendModules: Map<string, string> | undefined;
protected _frontendPreloadModules: Map<string, string> | undefined;
protected _frontendElectronModules: Map<string, string> | undefined;
protected _secondaryWindowModules: Map<string, string> | undefined;
protected _backendModules: Map<string, string> | undefined;
Expand Down Expand Up @@ -135,53 +136,36 @@ export class ApplicationPackage {
return new ExtensionPackage(raw, this.registry, options);
}

get frontendPreloadModules(): Map<string, string> {
return this._frontendPreloadModules ??= this.computeModules('frontendPreload');
}

get frontendModules(): Map<string, string> {
if (!this._frontendModules) {
this._frontendModules = this.computeModules('frontend');
}
return this._frontendModules;
return this._frontendModules ??= this.computeModules('frontend');
}

get frontendElectronModules(): Map<string, string> {
if (!this._frontendElectronModules) {
this._frontendElectronModules = this.computeModules('frontendElectron', 'frontend');
}
return this._frontendElectronModules;
return this._frontendElectronModules ??= this.computeModules('frontendElectron', 'frontend');
}

get secondaryWindowModules(): Map<string, string> {
if (!this._secondaryWindowModules) {
this._secondaryWindowModules = this.computeModules('secondaryWindow');
}
return this._secondaryWindowModules;
return this._secondaryWindowModules ??= this.computeModules('secondaryWindow');
}

get backendModules(): Map<string, string> {
if (!this._backendModules) {
this._backendModules = this.computeModules('backend');
}
return this._backendModules;
return this._backendModules ??= this.computeModules('backend');
}

get backendElectronModules(): Map<string, string> {
if (!this._backendElectronModules) {
this._backendElectronModules = this.computeModules('backendElectron', 'backend');
}
return this._backendElectronModules;
return this._backendElectronModules ??= this.computeModules('backendElectron', 'backend');
}

get electronMainModules(): Map<string, string> {
if (!this._electronMainModules) {
this._electronMainModules = this.computeModules('electronMain');
}
return this._electronMainModules;
return this._electronMainModules ??= this.computeModules('electronMain');
}

get preloadModules(): Map<string, string> {
if (!this._preloadModules) {
this._preloadModules = this.computeModules('preload');
}
return this._preloadModules;
return this._preloadModules ??= this.computeModules('preload');
}

protected computeModules<P extends keyof Extension, S extends keyof Extension = P>(primary: P, secondary?: S): Map<string, string> {
Expand Down
1 change: 1 addition & 0 deletions dev-packages/application-package/src/extension-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as semver from 'semver';
import { NpmRegistry, PublishedNodePackage, NodePackage } from './npm-registry';

export interface Extension {
frontendPreload?: string;
frontend?: string;
frontendElectron?: string;
secondaryWindow?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
},
"theiaExtensions": [
{
"frontendPreload": "lib/browser/preload/preload-module",
"preload": "lib/electron-browser/preload"
},
{
Expand Down
50 changes: 50 additions & 0 deletions packages/core/src/browser/preload/i18n-preload-contribution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// *****************************************************************************
// Copyright (C) 2023 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { PreloadContribution } from './preloader';
import { FrontendApplicationConfigProvider } from '../frontend-application-config-provider';
import { nls } from '../../common/nls';
import { inject, injectable } from 'inversify';
import { LocalizationServer } from '../../common/i18n/localization-server';

@injectable()
export class I18nPreloadContribution implements PreloadContribution {

@inject(LocalizationServer)
protected readonly localizationServer: LocalizationServer;

async initialize(): Promise<void> {
const defaultLocale = FrontendApplicationConfigProvider.get().defaultLocale;
if (defaultLocale && !nls.locale) {
Object.assign(nls, {
locale: defaultLocale
});
}
if (nls.locale) {
const localization = await this.localizationServer.loadLocalization(nls.locale);
if (localization.languagePack) {
nls.localization = localization;
} else {
// In case the localization that we've loaded doesn't localize Theia completely (languagePack is false)
// We simply reset the locale to the default again
Object.assign(nls, {
locale: defaultLocale || undefined
});
}
}
}

}
Loading
Loading