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

feat(@schematics/angular): update app-shell and ssr schematics to adopt new Server Rendering API #28571

Merged
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -29,7 +29,7 @@ import {
} from '../../utils/server-rendering/models';
import { prerenderPages } from '../../utils/server-rendering/prerender';
import { augmentAppWithServiceWorkerEsbuild } from '../../utils/service-worker';
import { INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options';
import { INDEX_HTML_CSR, INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options';
import { OutputMode } from './schema';

/**
Expand Down Expand Up @@ -154,7 +154,15 @@ export async function executePostBundleSteps(
// Update the index contents with the app shell under these conditions:
// - Replace 'index.html' with the app shell only if it hasn't been prerendered yet.
// - Always replace 'index.csr.html' with the app shell.
const filePath = appShellRoute && !indexHasBeenPrerendered ? indexHtmlOptions.output : path;
let filePath = path;
if (appShellRoute && !indexHasBeenPrerendered) {
if (outputMode !== OutputMode.Server && indexHtmlOptions.output === INDEX_HTML_CSR) {
filePath = 'index.html';
} else {
filePath = indexHtmlOptions.output;
}
}

additionalHtmlOutputFiles.set(
filePath,
createOutputFile(filePath, content, BuildOutputFileType.Browser),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ async function renderPages(
outputFiles: outputFilesForWorker,
assetFiles: assetFilesForWorker,
outputMode,
hasSsrEntry: !!outputFilesForWorker['/server.mjs'],
hasSsrEntry: !!outputFilesForWorker['server.mjs'],
} as RenderWorkerData,
execArgv: workerExecArgv,
});
Expand Down Expand Up @@ -319,7 +319,7 @@ async function getAllRoutes(
outputFiles: outputFilesForWorker,
assetFiles: assetFilesForWorker,
outputMode,
hasSsrEntry: !!outputFilesForWorker['/server.mjs'],
hasSsrEntry: !!outputFilesForWorker['server.mjs'],
} as RoutesExtractorWorkerData,
execArgv: workerExecArgv,
});
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/ssr/schematics/ng-add/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('@angular/ssr ng-add schematic', () => {
});

it('works', async () => {
const filePath = '/projects/test-app/server.ts';
const filePath = '/projects/test-app/src/server.ts';

expect(appTree.exists(filePath)).toBeFalse();
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export async function extractMessages(
buildOptions.budgets = undefined;
buildOptions.index = false;
buildOptions.serviceWorker = false;
buildOptions.server = undefined;
buildOptions.ssr = false;
buildOptions.appShell = false;
buildOptions.prerender = false;
Expand Down
176 changes: 62 additions & 114 deletions packages/schematics/angular/app-shell/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ import {
import { applyToUpdateRecorder } from '../utility/change';
import { getAppModulePath, isStandaloneApp } from '../utility/ng-ast-utils';
import { findBootstrapApplicationCall, getMainFilePath } from '../utility/standalone/util';
import { getWorkspace, updateWorkspace } from '../utility/workspace';
import { Builders } from '../utility/workspace-models';
import { getWorkspace } from '../utility/workspace';
import { Schema as AppShellOptions } from './schema';

const APP_SHELL_ROUTE = 'shell';
Expand Down Expand Up @@ -140,77 +139,6 @@ function validateProject(mainPath: string): Rule {
};
}

function addAppShellConfigToWorkspace(options: AppShellOptions): Rule {
return (host, context) => {
return updateWorkspace((workspace) => {
const project = workspace.projects.get(options.project);
if (!project) {
return;
}

const buildTarget = project.targets.get('build');
if (buildTarget?.builder === Builders.Application) {
// Application builder configuration.
const prodConfig = buildTarget.configurations?.production;
if (!prodConfig) {
throw new SchematicsException(
`A "production" configuration is not defined for the "build" builder.`,
);
}

prodConfig.appShell = true;

return;
}

// Webpack based builders configuration.
// Validation of targets is handled already in the main function.
// Duplicate keys means that we have configurations in both server and build builders.
const serverConfigKeys = project.targets.get('server')?.configurations ?? {};
const buildConfigKeys = project.targets.get('build')?.configurations ?? {};

const configurationNames = Object.keys({
...serverConfigKeys,
...buildConfigKeys,
});

const configurations: Record<string, {}> = {};
for (const key of configurationNames) {
if (!serverConfigKeys[key]) {
context.logger.warn(
`Skipped adding "${key}" configuration to "app-shell" target as it's missing from "server" target.`,
);

continue;
}

if (!buildConfigKeys[key]) {
context.logger.warn(
`Skipped adding "${key}" configuration to "app-shell" target as it's missing from "build" target.`,
);

continue;
}

configurations[key] = {
browserTarget: `${options.project}:build:${key}`,
serverTarget: `${options.project}:server:${key}`,
};
}

project.targets.add({
name: 'app-shell',
builder: Builders.AppShell,
defaultConfiguration: configurations['production'] ? 'production' : undefined,
options: {
route: APP_SHELL_ROUTE,
},
configurations,
});
});
};
}

function addRouterModule(mainPath: string): Rule {
return (host: Tree) => {
const modulePath = getAppModulePath(host, mainPath);
Expand Down Expand Up @@ -313,6 +241,7 @@ function addStandaloneServerRoute(options: AppShellOptions): Rule {
throw new SchematicsException(`Cannot find "${configFilePath}".`);
}

const recorder = host.beginUpdate(configFilePath);
let configSourceFile = getSourceFile(host, configFilePath);
if (!isImported(configSourceFile, 'ROUTES', '@angular/router')) {
const routesChange = insertImport(
Expand All @@ -322,10 +251,8 @@ function addStandaloneServerRoute(options: AppShellOptions): Rule {
'@angular/router',
);

const recorder = host.beginUpdate(configFilePath);
if (routesChange) {
applyToUpdateRecorder(recorder, [routesChange]);
host.commitUpdate(recorder);
}
}

Expand All @@ -340,45 +267,20 @@ function addStandaloneServerRoute(options: AppShellOptions): Rule {
}

// Add route to providers literal.
const newProvidersLiteral = ts.factory.updateArrayLiteralExpression(providersLiteral, [
...providersLiteral.elements,
ts.factory.createObjectLiteralExpression(
[
ts.factory.createPropertyAssignment('provide', ts.factory.createIdentifier('ROUTES')),
ts.factory.createPropertyAssignment('multi', ts.factory.createIdentifier('true')),
ts.factory.createPropertyAssignment(
'useValue',
ts.factory.createArrayLiteralExpression(
[
ts.factory.createObjectLiteralExpression(
[
ts.factory.createPropertyAssignment(
'path',
ts.factory.createIdentifier(`'${APP_SHELL_ROUTE}'`),
),
ts.factory.createPropertyAssignment(
'component',
ts.factory.createIdentifier('AppShellComponent'),
),
],
true,
),
],
true,
),
),
],
true,
),
]);

const recorder = host.beginUpdate(configFilePath);
recorder.remove(providersLiteral.getStart(), providersLiteral.getWidth());
const printer = ts.createPrinter();
recorder.insertRight(
providersLiteral.getStart(),
printer.printNode(ts.EmitHint.Unspecified, newProvidersLiteral, configSourceFile),
);
const updatedProvidersString = [
...providersLiteral.elements.map((element) => ' ' + element.getText()),
` {
provide: ROUTES,
multi: true,
useValue: [{
path: '${APP_SHELL_ROUTE}',
component: AppShellComponent
}]
}\n `,
];

recorder.insertRight(providersLiteral.getStart(), `[\n${updatedProvidersString.join(',\n')}]`);

// Add AppShellComponent import
const appShellImportChange = insertImport(
Expand All @@ -393,6 +295,52 @@ function addStandaloneServerRoute(options: AppShellOptions): Rule {
};
}

function addServerRoutingConfig(options: AppShellOptions): Rule {
return async (host: Tree) => {
const workspace = await getWorkspace(host);
const project = workspace.projects.get(options.project);
if (!project) {
throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`);
}

const configFilePath = join(project.sourceRoot ?? 'src', 'app/app.routes.server.ts');
if (!host.exists(configFilePath)) {
throw new SchematicsException(`Cannot find "${configFilePath}".`);
}

const sourceFile = getSourceFile(host, configFilePath);
const nodes = getSourceNodes(sourceFile);

// Find the serverRoutes variable declaration
const serverRoutesNode = nodes.find(
(node) =>
ts.isVariableDeclaration(node) &&
node.initializer &&
ts.isArrayLiteralExpression(node.initializer) &&
node.type &&
ts.isArrayTypeNode(node.type) &&
node.type.getText().includes('ServerRoute'),
) as ts.VariableDeclaration | undefined;

if (!serverRoutesNode) {
throw new SchematicsException(
`Cannot find the "ServerRoute" configuration in "${configFilePath}".`,
);
}
const recorder = host.beginUpdate(configFilePath);
const arrayLiteral = serverRoutesNode.initializer as ts.ArrayLiteralExpression;
const firstElementPosition =
arrayLiteral.elements[0]?.getStart() ?? arrayLiteral.getStart() + 1;
const newRouteString = `{
path: '${APP_SHELL_ROUTE}',
renderMode: RenderMode.AppShell
},\n`;
recorder.insertLeft(firstElementPosition, newRouteString);

host.commitUpdate(recorder);
};
}

export default function (options: AppShellOptions): Rule {
return async (tree) => {
const browserEntryPoint = await getMainFilePath(tree, options.project);
Expand All @@ -401,9 +349,9 @@ export default function (options: AppShellOptions): Rule {
return chain([
validateProject(browserEntryPoint),
schematic('server', options),
addAppShellConfigToWorkspace(options),
isStandalone ? noop() : addRouterModule(browserEntryPoint),
isStandalone ? addStandaloneServerRoute(options) : addServerRoutes(options),
addServerRoutingConfig(options),
schematic('component', {
name: 'app-shell',
module: 'app.module.server.ts',
Expand Down
Loading