|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google Inc. All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | +import { JsonParseMode, parseJsonAst, strings, tags } from '@angular-devkit/core'; |
| 9 | +import { |
| 10 | + Rule, SchematicContext, SchematicsException, Tree, |
| 11 | + apply, applyTemplates, chain, mergeWith, move, noop, url, |
| 12 | +} from '@angular-devkit/schematics'; |
| 13 | +import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; |
| 14 | +import { getWorkspace, updateWorkspace } from '../utility/config'; |
| 15 | +import { appendValueInAstArray, findPropertyInAstObject } from '../utility/json-utils'; |
| 16 | +import { parseName } from '../utility/parse-name'; |
| 17 | +import { buildDefaultPath, getProject } from '../utility/project'; |
| 18 | +import { getProjectTargets } from '../utility/project-targets'; |
| 19 | +import { |
| 20 | + BrowserBuilderOptions, |
| 21 | + BrowserBuilderTarget, |
| 22 | + WorkspaceSchema, |
| 23 | +} from '../utility/workspace-models'; |
| 24 | +import { Schema as WebWorkerOptions } from './schema'; |
| 25 | + |
| 26 | +function getProjectConfiguration( |
| 27 | + workspace: WorkspaceSchema, |
| 28 | + options: WebWorkerOptions, |
| 29 | +): BrowserBuilderOptions { |
| 30 | + const projectTargets = getProjectTargets(workspace, options.project); |
| 31 | + if (!projectTargets[options.target]) { |
| 32 | + throw new Error(`Target is not defined for this project.`); |
| 33 | + } |
| 34 | + |
| 35 | + const target = projectTargets[options.target] as BrowserBuilderTarget; |
| 36 | + |
| 37 | + return target.options; |
| 38 | +} |
| 39 | + |
| 40 | +function addConfig(options: WebWorkerOptions, root: string): Rule { |
| 41 | + return (host: Tree, context: SchematicContext) => { |
| 42 | + context.logger.debug('updating project configuration.'); |
| 43 | + const workspace = getWorkspace(host); |
| 44 | + const config = getProjectConfiguration(workspace, options); |
| 45 | + |
| 46 | + if (!!config.experimentalWebWorkerTsConfig) { |
| 47 | + // Don't do anything if the configuration is already there. |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + config.experimentalWebWorkerTsConfig = |
| 52 | + `${root.endsWith('/') ? root : root + '/'}tsconfig.worker.json`; |
| 53 | + |
| 54 | + const relativePathToWorkspaceRoot = root.split('/').map(x => '..').join('/'); |
| 55 | + const templateSource = apply(url('./other-files'), [ |
| 56 | + applyTemplates({ ...options, relativePathToWorkspaceRoot }), |
| 57 | + move(root), |
| 58 | + ]); |
| 59 | + |
| 60 | + // Add worker glob exclusion to tsconfig.app.json. |
| 61 | + const workerGlob = '**/*.worker.ts'; |
| 62 | + const tsConfigPath = config.tsConfig; |
| 63 | + const buffer = host.read(tsConfigPath); |
| 64 | + if (buffer) { |
| 65 | + const tsCfgAst = parseJsonAst(buffer.toString(), JsonParseMode.Loose); |
| 66 | + if (tsCfgAst.kind != 'object') { |
| 67 | + throw new SchematicsException('Invalid tsconfig. Was expecting an object'); |
| 68 | + } |
| 69 | + const filesAstNode = findPropertyInAstObject(tsCfgAst, 'exclude'); |
| 70 | + if (filesAstNode && filesAstNode.kind != 'array') { |
| 71 | + throw new SchematicsException('Invalid tsconfig "exclude" property; expected an array.'); |
| 72 | + } |
| 73 | + const recorder = host.beginUpdate(tsConfigPath); |
| 74 | + if (!filesAstNode) { |
| 75 | + // Do nothing if the files array does not exist. This means exclude or include are |
| 76 | + // set and we shouldn't mess with that. |
| 77 | + } else { |
| 78 | + if (filesAstNode.value.indexOf(workerGlob) == -1) { |
| 79 | + appendValueInAstArray(recorder, filesAstNode, workerGlob); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + host.commitUpdate(recorder); |
| 84 | + } |
| 85 | + |
| 86 | + // Add webworker lib to root tsconfig for editor support |
| 87 | + // TODO |
| 88 | + |
| 89 | + // The dom and webworker libs are mutually exclusive. |
| 90 | + // Overwrite the lib option for all known tsconfigs to prevent errors. |
| 91 | + // TODO |
| 92 | + |
| 93 | + return chain([ |
| 94 | + // Add tsconfig.worker.json. |
| 95 | + mergeWith(templateSource), |
| 96 | + // Add workspace configuration. |
| 97 | + updateWorkspace(workspace), |
| 98 | + ]); |
| 99 | + }; |
| 100 | +} |
| 101 | + |
| 102 | +function addSnippet(options: WebWorkerOptions): Rule { |
| 103 | + return (host: Tree, context: SchematicContext) => { |
| 104 | + context.logger.debug('Updating appmodule'); |
| 105 | + |
| 106 | + if (options.path === undefined) { |
| 107 | + return; |
| 108 | + } |
| 109 | + |
| 110 | + const siblingModules = host.getDir(options.path).subfiles |
| 111 | + // Find all files that start with the same name, are ts files, and aren't spec files. |
| 112 | + .filter(f => f.startsWith(options.name) && f.endsWith('.ts') && !f.endsWith('spec.ts')) |
| 113 | + // Sort alphabetically for consistency. |
| 114 | + .sort(); |
| 115 | + |
| 116 | + if (siblingModules.length === 0) { |
| 117 | + // No module to add in. |
| 118 | + return; |
| 119 | + } |
| 120 | + |
| 121 | + const siblingModulePath = `${options.path}/${siblingModules[0]}`; |
| 122 | + const workerCreationSnippet = tags.stripIndent` |
| 123 | + const worker = new Worker('./${options.name}.worker', { type: 'module' }); |
| 124 | + worker.onmessage = ({ data }) => { |
| 125 | + console.log('page got message: $\{data\}'); |
| 126 | + }; |
| 127 | + worker.postMessage('hello'); |
| 128 | + `; |
| 129 | + |
| 130 | + // Append the worker creation snippet. |
| 131 | + const originalContent = host.read(siblingModulePath); |
| 132 | + host.overwrite(siblingModulePath, originalContent + '\n' + workerCreationSnippet); |
| 133 | + |
| 134 | + return host; |
| 135 | + }; |
| 136 | +} |
| 137 | + |
| 138 | +export default function (options: WebWorkerOptions): Rule { |
| 139 | + return (host: Tree, context: SchematicContext) => { |
| 140 | + const project = getProject(host, options.project); |
| 141 | + if (!options.project) { |
| 142 | + throw new SchematicsException('Option "project" is required.'); |
| 143 | + } |
| 144 | + if (!project) { |
| 145 | + throw new SchematicsException(`Invalid project name (${options.project})`); |
| 146 | + } |
| 147 | + if (project.projectType !== 'application') { |
| 148 | + throw new SchematicsException(`Web Worker requires a project type of "application".`); |
| 149 | + } |
| 150 | + |
| 151 | + if (options.path === undefined) { |
| 152 | + options.path = buildDefaultPath(project); |
| 153 | + } |
| 154 | + const parsedPath = parseName(options.path, options.name); |
| 155 | + options.name = parsedPath.name; |
| 156 | + options.path = parsedPath.path; |
| 157 | + const root = project.root || project.sourceRoot || ''; |
| 158 | + |
| 159 | + const templateSource = apply(url('./files'), [ |
| 160 | + applyTemplates({ ...options, ...strings }), |
| 161 | + move(parsedPath.path), |
| 162 | + ]); |
| 163 | + |
| 164 | + context.addTask(new NodePackageInstallTask()); |
| 165 | + |
| 166 | + return chain([ |
| 167 | + // Add project configuration. |
| 168 | + addConfig(options, root), |
| 169 | + // Create the worker in a sibling module. |
| 170 | + options.snippet ? addSnippet(options) : noop(), |
| 171 | + // Add the worker. |
| 172 | + mergeWith(templateSource), |
| 173 | + ]); |
| 174 | + }; |
| 175 | +} |
0 commit comments