_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/schematics/angular/application/files/standalone-files/src/app/app.config.ts.template_0_556
import { ApplicationConfig, <% if(!experimentalZoneless) { %>provideZoneChangeDetection<% } else { %>provideExperimentalZonelessChangeDetection<% } %> } from '@angular/core';<% if (routing) { %> import { provideRouter } from '@angular/router'; import { routes } from './app.routes';<% } %> export const appConfig: ApplicationConfig = { providers: [<% if(experimentalZoneless) { %>provideExperimentalZonelessChangeDetection()<% } else { %>provideZoneChangeDetection({ eventCoalescing: true })<% } %><% if (routing) {%>, provideRouter(routes)<% } %>] };
{ "end_byte": 556, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/standalone-files/src/app/app.config.ts.template" }
angular-cli/packages/schematics/angular/application/files/standalone-files/src/app/app.component.ts.template_0_568
import { Component } from '@angular/core';<% if(routing) { %> import { RouterOutlet } from '@angular/router';<% } %> @Component({ selector: '<%= selector %>', imports: [<% if(routing) { %>RouterOutlet<% } %>],<% if(inlineTemplate) { %> template: ` <h1>Welcome to {{title}}!</h1> <% if (routing) { %><router-outlet /><% } %> `,<% } else { %> templateUrl: './app.component.html',<% } if(inlineStyle) { %> styles: [],<% } else { %> styleUrl: './app.component.<%= style %>'<% } %> }) export class AppComponent { title = '<%= name %>'; }
{ "end_byte": 568, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/standalone-files/src/app/app.component.ts.template" }
angular-cli/packages/schematics/angular/application/files/common-files/tsconfig.app.json.template_0_490
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "<%= relativePathToWorkspaceRoot %>/tsconfig.json", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/app", "types": [] }, "files": [ "src/main.ts" ], "include": [ "src/**/*.d.ts" ] }
{ "end_byte": 490, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/tsconfig.app.json.template" }
angular-cli/packages/schematics/angular/application/files/common-files/tsconfig.spec.json.template_0_500
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "<%= relativePathToWorkspaceRoot %>/tsconfig.json", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/spec", "types": [ "jasmine" ] }, "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] }
{ "end_byte": 500, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/tsconfig.spec.json.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/index.html.template_0_327
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= utils.classify(name) %></title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <<%= selector %>></<%= selector %>> </body> </html>
{ "end_byte": 327, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/index.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/styles.__style__.template_0_80
/* You can add global styles to this file, and also import other style files */
{ "end_byte": 80, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/styles.__style__.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_0_4367
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * * * The content below * * * * * * * * * * * --> <!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * --> <!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * Delete the template below * * * * * * * * * --> <!-- * * * * * * * to get started with your project! * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <style> :host { --bright-blue: oklch(51.01% 0.274 263.83); --electric-violet: oklch(53.18% 0.28 296.97); --french-violet: oklch(47.66% 0.246 305.88); --vivid-pink: oklch(69.02% 0.277 332.77); --hot-red: oklch(61.42% 0.238 15.34); --orange-red: oklch(63.32% 0.24 31.68); --gray-900: oklch(19.37% 0.006 300.98); --gray-700: oklch(36.98% 0.014 302.71); --gray-400: oklch(70.9% 0.015 304.04); --red-to-pink-to-purple-vertical-gradient: linear-gradient( 180deg, var(--orange-red) 0%, var(--vivid-pink) 50%, var(--electric-violet) 100% ); --red-to-pink-to-purple-horizontal-gradient: linear-gradient( 90deg, var(--orange-red) 0%, var(--vivid-pink) 50%, var(--electric-violet) 100% ); --pill-accent: var(--bright-blue); font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; box-sizing: border-box; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h1 { font-size: 3.125rem; color: var(--gray-900); font-weight: 500; line-height: 100%; letter-spacing: -0.125rem; margin: 0; font-family: "Inter Tight", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } p { margin: 0; color: var(--gray-700); } main { width: 100%; min-height: 100%; display: flex; justify-content: center; align-items: center; padding: 1rem; box-sizing: inherit; position: relative; } .angular-logo { max-width: 9.2rem; } .content { display: flex; justify-content: space-around; width: 100%; max-width: 700px; margin-bottom: 3rem; } .content h1 { margin-top: 1.75rem; } .content p { margin-top: 1.5rem; } .divider { width: 1px; background: var(--red-to-pink-to-purple-vertical-gradient); margin-inline: 0.5rem; } .pill-group { display: flex; flex-direction: column; align-items: start; flex-wrap: wrap; gap: 1.25rem; } .pill { display: flex; align-items: center; --pill-accent: var(--bright-blue); background: color-mix(in srgb, var(--pill-accent) 5%, transparent); color: var(--pill-accent); padding-inline: 0.75rem; padding-block: 0.375rem; border-radius: 2.75rem; border: 0; transition: background 0.3s ease; font-family: var(--inter-font); font-size: 0.875rem; font-style: normal; font-weight: 500; line-height: 1.4rem; letter-spacing: -0.00875rem; text-decoration: none; } .pill:hover { background: color-mix(in srgb, var(--pill-accent) 15%, transparent); } .pill-group .pill:nth-child(6n + 1) { --pill-accent: var(--bright-blue); } .pill-group .pill:nth-child(6n + 2) { --pill-accent: var(--french-violet); } .pill-group .pill:nth-child(6n + 3), .pill-group .pill:nth-child(6n + 4), .pill-group .pill:nth-child(6n + 5) { --pill-accent: var(--hot-red); } .pill-group svg { margin-inline-start: 0.25rem; } .social-links { display: flex; align-items: center; gap: 0.73rem; margin-top: 1.5rem; } .social-links path { transition: fill 0.3s ease; fill: var(--gray-400); } .social-links a:hover svg path { fill: var(--gray-900); } @media screen and (max-width: 650px) { .content { flex-direction: column; width: max-content; } .divider { height: 1px; width: 100%; background: var(--red-to-pink-to-purple-horizontal-gradient); margin-block: 1.5rem; } } </style>
{ "end_byte": 4367, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_4369_4656
<main class="main"> <div class="content"> <div class="left-side"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 982 239" fill="none" class="angular-logo" > <g clip-path="url(#a)"> <path fill="url(#b)"
{ "end_byte": 4656, "start_byte": 4369, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_4669_7816
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455
{ "end_byte": 7816, "start_byte": 4669, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_7817_9024
12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
{ "end_byte": 9024, "start_byte": 7817, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_9025_9080
/> <path fill="url(#c)"
{ "end_byte": 9080, "start_byte": 9025, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_9093_12240
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455
{ "end_byte": 12240, "start_byte": 9093, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_12241_13448
12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
{ "end_byte": 13448, "start_byte": 12241, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_13449_18515
/> </g> <defs> <radialGradient id="c" cx="0" cy="0" r="1" gradientTransform="rotate(118.122 171.182 60.81) scale(205.794)" gradientUnits="userSpaceOnUse" > <stop stop-color="#FF41F8" /> <stop offset=".707" stop-color="#FF41F8" stop-opacity=".5" /> <stop offset="1" stop-color="#FF41F8" stop-opacity="0" /> </radialGradient> <linearGradient id="b" x1="0" x2="982" y1="192" y2="192" gradientUnits="userSpaceOnUse" > <stop stop-color="#F0060B" /> <stop offset="0" stop-color="#F0070C" /> <stop offset=".526" stop-color="#CC26D5" /> <stop offset="1" stop-color="#7702FF" /> </linearGradient> <clipPath id="a"><path fill="#fff" d="M0 0h982v239H0z" /></clipPath> </defs> </svg> <h1>Hello, {{ title }}</h1> <p>Congratulations! Your app is running. 🎉</p> </div> <div class="divider" role="separator" aria-label="Divider"></div> <div class="right-side"> <div class="pill-group"> @for (item of [ { title: 'Explore the Docs', link: 'https://angular.dev' }, { title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials' }, { title: 'CLI Docs', link: 'https://angular.dev/tools/cli' }, { title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service' }, { title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools' }, ]; track item.title) { <a class="pill" [href]="item.link" target="_blank" rel="noopener" > <span>{{ item.title }}</span> <svg xmlns="http://www.w3.org/2000/svg" height="14" viewBox="0 -960 960 960" width="14" fill="currentColor" > <path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z" /> </svg> </a> } </div> <div class="social-links"> <a href="https://github.com/angular/angular" aria-label="Github" target="_blank" rel="noopener" > <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg" alt="Github" > <path d="M12.3047 0C5.50634 0 0 5.50942 0 12.3047C0 17.7423 3.52529 22.3535 8.41332 23.9787C9.02856 24.0946 9.25414 23.7142 9.25414 23.3871C9.25414 23.0949 9.24389 22.3207 9.23876 21.2953C5.81601 22.0377 5.09414 19.6444 5.09414 19.6444C4.53427 18.2243 3.72524 17.8449 3.72524 17.8449C2.61064 17.082 3.81137 17.0973 3.81137 17.0973C5.04697 17.1835 5.69604 18.3647 5.69604 18.3647C6.79321 20.2463 8.57636 19.7029 9.27978 19.3881C9.39052 18.5924 9.70736 18.0499 10.0591 17.7423C7.32641 17.4347 4.45429 16.3765 4.45429 11.6618C4.45429 10.3185 4.9311 9.22133 5.72065 8.36C5.58222 8.04931 5.16694 6.79833 5.82831 5.10337C5.82831 5.10337 6.85883 4.77319 9.2121 6.36459C10.1965 6.09082 11.2424 5.95546 12.2883 5.94931C13.3342 5.95546 14.3801 6.09082 15.3644 6.36459C17.7023 4.77319 18.7328 5.10337 18.7328 5.10337C19.3942 6.79833 18.9789 8.04931 18.8559 8.36C19.6403 9.22133 20.1171 10.3185 20.1171 11.6618C20.1171 16.3888 17.2409 17.4296 14.5031 17.7321C14.9338 18.1012 15.3337 18.8559 15.3337 20.0084C15.3337 21.6552 15.3183 22.978 15.3183 23.3779C15.3183 23.7009 15.5336 24.0854 16.1642 23.9623C21.0871 22.3484 24.6094 17.7341 24.6094 12.3047C24.6094 5.50942 19.0999 0 12.3047 0Z" /> </svg> </a> <a href="https://twitter.com/angular" aria-label="Twitter" target="_blank" rel="noopener" > <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" alt="Twitter" > <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" /> </svg> </a> <a href="https://www.youtube.com/channel/UCbn1OgGei-DV7aSRo_HaAiw" aria-label="Youtube" target="_blank" rel="noopener" > <svg width="29" height="20" viewBox="0 0 29 20" fill="none" xmlns="http://www.w3.org/2000/svg" alt="Youtube" > <path fill-rule="evenodd" clip-rule="evenodd"
{ "end_byte": 18515, "start_byte": 13449, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_18516_19367
d="M27.4896 1.52422C27.9301 1.96749 28.2463 2.51866 28.4068 3.12258C29.0004 5.35161 29.0004 10 29.0004 10C29.0004 10 29.0004 14.6484 28.4068 16.8774C28.2463 17.4813 27.9301 18.0325 27.4896 18.4758C27.0492 18.9191 26.5 19.2389 25.8972 19.4032C23.6778 20 14.8068 20 14.8068 20C14.8068 20 5.93586 20 3.71651 19.4032C3.11363 19.2389 2.56449 18.9191 2.12405 18.4758C1.68361 18.0325 1.36732 17.4813 1.20683 16.8774C0.613281 14.6484 0.613281 10 0.613281 10C0.613281 10 0.613281 5.35161 1.20683 3.12258C1.36732 2.51866 1.68361 1.96749 2.12405 1.52422C2.56449 1.08095 3.11363 0.76113 3.71651 0.596774C5.93586 0 14.8068 0 14.8068 0C14.8068 0 23.6778 0 25.8972 0.596774C26.5 0.76113 27.0492 1.08095 27.4896 1.52422ZM19.3229 10L11.9036 5.77905V14.221L19.3229 10Z" /> </svg> </a> </div> </div> </div> </main>
{ "end_byte": 19367, "start_byte": 18516, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template_19369_19927
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * * * The content above * * * * * * * * * * * * --> <!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * * --> <!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * * End of Placeholder * * * * * * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <% if (routing) { %> <router-outlet /><% } %>
{ "end_byte": 19927, "start_byte": 19369, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/files/common-files/src/app/app.component.html.template" }
angular-cli/packages/schematics/angular/service/index.ts_0_651
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Schema as ServiceOptions } from './schema'; export default function (options: ServiceOptions): Rule { // This schematic uses an older method to implement the flat option const flat = options.flat; options.flat = true; return generateFromFiles(options, { 'if-flat': (s: string) => (flat ? '' : s), }); }
{ "end_byte": 651, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service/index.ts" }
angular-cli/packages/schematics/angular/service/index_spec.ts_0_2785
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ServiceOptions } from './schema'; describe('Service Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ServiceOptions = { name: 'foo', flat: false, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create a service', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('service', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.service.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.service.ts'); }); it('service should be tree-shakeable', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('service', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.service.ts'); expect(content).toMatch(/providedIn: 'root'/); }); it('should respect the skipTests flag', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('service', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.service.ts'); expect(files).not.toContain('/projects/bar/src/app/foo/foo.service.spec.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('service', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo/foo.service.ts'); }); });
{ "end_byte": 2785, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service/index_spec.ts" }
angular-cli/packages/schematics/angular/service/files/__name@dasherize@if-flat__/__name@dasherize__.service.spec.ts.template_0_433
import { TestBed } from '@angular/core/testing'; import { <%= classify(name) %>Service } from './<%= dasherize(name) %>.service'; describe('<%= classify(name) %>Service', () => { let service: <%= classify(name) %>Service; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(<%= classify(name) %>Service); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "end_byte": 433, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service/files/__name@dasherize@if-flat__/__name@dasherize__.service.spec.ts.template" }
angular-cli/packages/schematics/angular/service/files/__name@dasherize@if-flat__/__name@dasherize__.service.ts.template_0_150
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class <%= classify(name) %>Service { constructor() { } }
{ "end_byte": 150, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service/files/__name@dasherize@if-flat__/__name@dasherize__.service.ts.template" }
angular-cli/packages/schematics/angular/guard/index.ts_0_1898
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, SchematicsException } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Implement as GuardInterface, Schema as GuardOptions } from './schema'; export default function (options: GuardOptions): Rule { if (!options.implements) { throw new SchematicsException('Option "implements" is required.'); } if (options.implements.length > 1 && options.functional) { throw new SchematicsException( 'Can only specify one value for implements when generating a functional guard.', ); } if (options.functional) { const guardType = options.implements[0] + 'Fn'; return generateFromFiles({ ...options, templateFilesDirectory: './type-files' }, { guardType }); } else { const implementations = options.implements .map((implement) => (implement === 'CanDeactivate' ? 'CanDeactivate<unknown>' : implement)) .join(', '); const commonRouterNameImports = ['ActivatedRouteSnapshot', 'RouterStateSnapshot']; const routerNamedImports: string[] = [...options.implements, 'MaybeAsync', 'GuardResult']; if (options.implements.includes(GuardInterface.CanMatch)) { routerNamedImports.push('Route', 'UrlSegment'); if (options.implements.length > 1) { routerNamedImports.push(...commonRouterNameImports); } } else { routerNamedImports.push(...commonRouterNameImports); } routerNamedImports.sort(); const routerImports = routerNamedImports.join(', '); return generateFromFiles( { ...options, templateFilesDirectory: './implements-files' }, { implementations, routerImports, }, ); } }
{ "end_byte": 1898, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/index.ts" }
angular-cli/packages/schematics/angular/guard/index_spec.ts_0_8362
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as GuardOptions } from './schema'; describe('Guard Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: GuardOptions = { name: 'foo', flat: true, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create a (deprecated) class-based guard with --no-functional', async () => { const tree = await schematicRunner.runSchematic( 'guard', { ...defaultOptions, functional: false }, appTree, ); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo.guard.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.guard.ts'); }); it('should respect the skipTests flag', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const files = tree.files; expect(files).not.toContain('/projects/bar/src/app/foo.guard.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.guard.ts'); }); it('should respect the flat flag', async () => { const options = { ...defaultOptions, flat: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.guard.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.guard.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('guard', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo.guard.ts'); }); it('should respect the implements value', async () => { const options = { ...defaultOptions, implements: ['CanActivate'], functional: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); expect(fileString).toContain('CanActivate'); expect(fileString).toContain('canActivate'); expect(fileString).not.toContain('CanActivateChild'); expect(fileString).not.toContain('canActivateChild'); expect(fileString).not.toContain('CanMatch'); expect(fileString).not.toContain('canMatch'); }); it('should generate a functional guard by default', async () => { const options = { ...defaultOptions, implements: ['CanActivate'] }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); expect(fileString).toContain('export const fooGuard: CanActivateFn = (route, state) => {'); expect(fileString).not.toContain('CanActivateChild'); expect(fileString).not.toContain('canActivateChild'); expect(fileString).not.toContain('CanMatch'); expect(fileString).not.toContain('canMatch'); }); it('should generate a helper function to execute the guard in a test', async () => { const options = { ...defaultOptions, implements: ['CanActivate'] }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.spec.ts'); expect(fileString).toContain('const executeGuard: CanActivateFn = (...guardParameters) => '); expect(fileString).toContain( 'TestBed.runInInjectionContext(() => fooGuard(...guardParameters));', ); }); it('should generate CanDeactivateFn with unknown functional guard', async () => { const options = { ...defaultOptions, implements: ['CanDeactivate'] }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); expect(fileString).toContain( 'export const fooGuard: CanDeactivateFn<unknown> = ' + '(component, currentRoute, currentState, nextState) => {', ); }); it('should respect the implements values in (deprecated) class-based guards', async () => { const implementationOptions = ['CanActivate', 'CanDeactivate', 'CanActivateChild']; const options = { ...defaultOptions, implements: implementationOptions, functional: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); // Should contain all implementations implementationOptions.forEach((implementation: string) => { expect(fileString).toContain(implementation); const functionName = `${implementation.charAt(0).toLowerCase()}${implementation.slice(1)}`; expect(fileString).toContain(functionName); }); }); it('should add correct imports based on CanMatch implementation in (deprecated) class-based guards', async () => { const implementationOptions = ['CanMatch']; const options = { ...defaultOptions, implements: implementationOptions, functional: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); const expectedImports = `import { CanMatch, GuardResult, MaybeAsync, Route, UrlSegment } from '@angular/router';`; expect(fileString).toContain(expectedImports); }); it('should add correct imports based on CanActivate implementation in (deprecated) class-based guards', async () => { const implementationOptions = ['CanActivate']; const options = { ...defaultOptions, implements: implementationOptions, functional: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); const expectedImports = `import { ActivatedRouteSnapshot, CanActivate, GuardResult, ` + `MaybeAsync, RouterStateSnapshot } from '@angular/router';`; expect(fileString).toContain(expectedImports); }); it('should add correct imports based on canActivate functional guard', async () => { const options = { ...defaultOptions, implements: ['CanActivate'] }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); const expectedImports = `import { CanActivateFn } from '@angular/router';`; expect(fileString).toContain(expectedImports); }); it('should add correct imports if multiple implementations was selected in (deprecated) class-based guards', async () => { const implementationOptions = ['CanActivate', 'CanMatch', 'CanActivateChild']; const options = { ...defaultOptions, implements: implementationOptions, functional: false }; const tree = await schematicRunner.runSchematic('guard', options, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts'); const expectedImports = `import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, CanMatch, GuardResult, ` + `MaybeAsync, Route, RouterStateSnapshot, UrlSegment } from '@angular/router';`; expect(fileString).toContain(expectedImports); }); });
{ "end_byte": 8362, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/index_spec.ts" }
angular-cli/packages/schematics/angular/guard/implements-files/__name@dasherize__.guard.ts.template_0_1020
import { Injectable } from '@angular/core'; import { <%= routerImports %> } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class <%= classify(name) %>Guard implements <%= implementations %> { <% if (implements.includes('CanActivate')) { %>canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): MaybeAsync<GuardResult> { return true; } <% } %><% if (implements.includes('CanActivateChild')) { %>canActivateChild( childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): MaybeAsync<GuardResult> { return true; } <% } %><% if (implements.includes('CanDeactivate')) { %>canDeactivate( component: unknown, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): MaybeAsync<GuardResult> { return true; } <% } %><% if (implements.includes('CanMatch')) { %>canMatch( route: Route, segments: UrlSegment[]): MaybeAsync<GuardResult> { return true; }<% } %> }
{ "end_byte": 1020, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/implements-files/__name@dasherize__.guard.ts.template" }
angular-cli/packages/schematics/angular/guard/implements-files/__name@dasherize__.guard.spec.ts.template_0_417
import { TestBed } from '@angular/core/testing'; import { <%= classify(name) %>Guard } from './<%= dasherize(name) %>.guard'; describe('<%= classify(name) %>Guard', () => { let guard: <%= classify(name) %>Guard; beforeEach(() => { TestBed.configureTestingModule({}); guard = TestBed.inject(<%= classify(name) %>Guard); }); it('should be created', () => { expect(guard).toBeTruthy(); }); });
{ "end_byte": 417, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/implements-files/__name@dasherize__.guard.spec.ts.template" }
angular-cli/packages/schematics/angular/guard/type-files/__name@dasherize__.guard.ts.template_0_505
import { <%= guardType %> } from '@angular/router'; export const <%= camelize(name) %>Guard: <%= guardType %><% if (guardType === 'CanDeactivateFn') { %><unknown><% } %> = <% if (guardType === 'CanMatchFn') { %>(route, segments)<% } %><% if (guardType === 'CanActivateFn') { %>(route, state)<% } %><% if (guardType === 'CanActivateChildFn') { %>(childRoute, state)<% } %><% if (guardType === 'CanDeactivateFn') { %>(component, currentRoute, currentState, nextState)<% } %> => { return true; };
{ "end_byte": 505, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/type-files/__name@dasherize__.guard.ts.template" }
angular-cli/packages/schematics/angular/guard/type-files/__name@dasherize__.guard.spec.ts.template_0_536
import { TestBed } from '@angular/core/testing'; import { <%= guardType %> } from '@angular/router'; import { <%= camelize(name) %>Guard } from './<%= dasherize(name) %>.guard'; describe('<%= camelize(name) %>Guard', () => { const executeGuard: <%= guardType %> = (...guardParameters) => TestBed.runInInjectionContext(() => <%= camelize(name) %>Guard(...guardParameters)); beforeEach(() => { TestBed.configureTestingModule({}); }); it('should be created', () => { expect(executeGuard).toBeTruthy(); }); });
{ "end_byte": 536, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/guard/type-files/__name@dasherize__.guard.spec.ts.template" }
angular-cli/packages/schematics/angular/e2e/index.ts_0_2916
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, SchematicsException, apply, applyTemplates, chain, mergeWith, move, strings, url, } from '@angular-devkit/schematics'; import { AngularBuilder, DependencyType, ExistingBehavior, addDependency, addRootProvider, updateWorkspace, } from '@schematics/angular/utility'; import { posix as path } from 'path'; import { JSONFile } from '../utility/json-file'; import { latestVersions } from '../utility/latest-versions'; import { Schema as E2eOptions } from './schema'; /** * The list of development dependencies used by the E2E protractor-based builder. * The versions are sourced from the latest versions `../utility/latest-versions/package.json` * file which is automatically updated via renovate. */ const E2E_DEV_DEPENDENCIES = Object.freeze([ 'protractor', 'jasmine-spec-reporter', 'ts-node', '@types/node', ]); function addScriptsToPackageJson(): Rule { return (host) => { const pkgJson = new JSONFile(host, 'package.json'); const e2eScriptPath = ['scripts', 'e2e']; if (!pkgJson.get(e2eScriptPath)) { pkgJson.modify(e2eScriptPath, 'ng e2e', false); } }; } export default function (options: E2eOptions): Rule { const { relatedAppName } = options; return updateWorkspace((workspace) => { const project = workspace.projects.get(relatedAppName); if (!project) { throw new SchematicsException(`Project name "${relatedAppName}" doesn't not exist.`); } const e2eRootPath = path.join(project.root, 'e2e'); project.targets.add({ name: 'e2e', builder: AngularBuilder.Protractor, defaultConfiguration: 'development', options: { protractorConfig: path.join(e2eRootPath, 'protractor.conf.js'), }, configurations: { production: { devServerTarget: `${relatedAppName}:serve:production`, }, development: { devServerTarget: `${relatedAppName}:serve:development`, }, }, }); return chain([ mergeWith( apply(url('./files'), [ applyTemplates({ utils: strings, ...options, relativePathToWorkspaceRoot: path.relative(path.join('/', e2eRootPath), '/'), }), move(e2eRootPath), ]), ), addRootProvider( relatedAppName, ({ code, external }) => code`${external('provideProtractorTestingSupport', '@angular/platform-browser')}()`, ), ...E2E_DEV_DEPENDENCIES.map((name) => addDependency(name, latestVersions[name], { type: DependencyType.Dev, existing: ExistingBehavior.Skip, }), ), addScriptsToPackageJson(), ]); }); }
{ "end_byte": 2916, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/index.ts" }
angular-cli/packages/schematics/angular/e2e/index_spec.ts_0_3034
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as E2eOptions } from './schema'; describe('Application Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const defaultOptions: E2eOptions = { relatedAppName: 'foo', }; const defaultAppOptions: ApplicationOptions = { name: 'foo', inlineStyle: true, inlineTemplate: true, routing: false, skipPackageJson: false, minimal: true, }; let applicationTree: UnitTestTree; beforeEach(async () => { const workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions); applicationTree = await schematicRunner.runSchematic( 'application', defaultAppOptions, workspaceTree, ); }); it('should create all files of e2e in an application', async () => { const tree = await schematicRunner.runSchematic('private-e2e', defaultOptions, applicationTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/e2e/protractor.conf.js', '/projects/foo/e2e/tsconfig.json', '/projects/foo/e2e/src/app.e2e-spec.ts', '/projects/foo/e2e/src/app.po.ts', ]), ); }); describe('workspace config', () => { it('should add e2e targets for the app', async () => { const tree = await schematicRunner.runSchematic( 'private-e2e', defaultOptions, applicationTree, ); const workspace = JSON.parse(tree.readContent('/angular.json')); const targets = workspace.projects.foo.architect; expect(targets.e2e).toBeDefined(); }); it('should set the e2e options', async () => { const tree = await schematicRunner.runSchematic( 'private-e2e', defaultOptions, applicationTree, ); const workspace = JSON.parse(tree.readContent('/angular.json')); const { options, configurations } = workspace.projects.foo.architect.e2e; expect(options.protractorConfig).toEqual('projects/foo/e2e/protractor.conf.js'); expect(configurations.development.devServerTarget).toEqual('foo:serve:development'); }); }); it('should add an e2e script in package.json', async () => { const tree = await schematicRunner.runSchematic('private-e2e', defaultOptions, applicationTree); const pkg = JSON.parse(tree.readContent('/package.json')); expect(pkg.scripts['e2e']).toBe('ng e2e'); }); });
{ "end_byte": 3034, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/index_spec.ts" }
angular-cli/packages/schematics/angular/e2e/files/protractor.conf.js.template_0_904
// @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); /** * @type { import("protractor").Config } */ exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], capabilities: { browserName: 'chrome' }, directConnect: true, SELENIUM_PROMISE_MANAGER: false, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: StacktraceOption.PRETTY } })); } };
{ "end_byte": 904, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/files/protractor.conf.js.template" }
angular-cli/packages/schematics/angular/e2e/files/tsconfig.json.template_0_499
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "<%= relativePathToWorkspaceRoot %>/tsconfig.json", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/e2e", "module": "commonjs", "target": "es2019", "types": [ "jasmine", "node" ] } }
{ "end_byte": 499, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/files/tsconfig.json.template" }
angular-cli/packages/schematics/angular/e2e/files/src/app.e2e-spec.ts.template_0_663
import { browser, logging } from 'protractor'; import { AppPage } from './app.po'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', async () => { await page.navigateTo(); expect(await page.getTitleText()).toEqual('Hello, <%= relatedAppName %>'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); });
{ "end_byte": 663, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/files/src/app.e2e-spec.ts.template" }
angular-cli/packages/schematics/angular/e2e/files/src/app.po.ts.template_0_254
import { browser, by, element } from 'protractor'; export class AppPage { async navigateTo(): Promise<unknown> { return browser.get(browser.baseUrl); } async getTitleText(): Promise<string> { return element(by.css('h1')).getText(); } }
{ "end_byte": 254, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/e2e/files/src/app.po.ts.template" }
angular-cli/packages/schematics/angular/ng-new/index.ts_0_2723
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, SchematicContext, Tree, apply, chain, empty, mergeWith, move, noop, schematic, } from '@angular-devkit/schematics'; import { NodePackageInstallTask, RepositoryInitializerTask, } from '@angular-devkit/schematics/tasks'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as NgNewOptions } from './schema'; export default function (options: NgNewOptions): Rule { if (!options.directory) { // If scoped project (i.e. "@foo/bar"), convert directory to "foo/bar". options.directory = options.name.startsWith('@') ? options.name.slice(1) : options.name; } const workspaceOptions: WorkspaceOptions = { name: options.name, version: options.version, newProjectRoot: options.newProjectRoot, minimal: options.minimal, strict: options.strict, packageManager: options.packageManager, }; const applicationOptions: ApplicationOptions = { projectRoot: '', name: options.name, inlineStyle: options.inlineStyle, inlineTemplate: options.inlineTemplate, prefix: options.prefix, viewEncapsulation: options.viewEncapsulation, routing: options.routing, style: options.style, skipTests: options.skipTests, skipPackageJson: false, // always 'skipInstall' here, so that we do it after the move skipInstall: true, strict: options.strict, minimal: options.minimal, standalone: options.standalone, ssr: options.ssr, serverRouting: options.serverRouting, experimentalZoneless: options.experimentalZoneless, }; return chain([ mergeWith( apply(empty(), [ schematic('workspace', workspaceOptions), options.createApplication ? schematic('application', applicationOptions) : noop, move(options.directory), ]), ), (_host: Tree, context: SchematicContext) => { let packageTask; if (!options.skipInstall) { packageTask = context.addTask( new NodePackageInstallTask({ workingDirectory: options.directory, packageManager: options.packageManager, }), ); } if (!options.skipGit) { const commit = typeof options.commit == 'object' ? options.commit : options.commit ? {} : false; context.addTask( new RepositoryInitializerTask(options.directory, commit), packageTask ? [packageTask] : [], ); } }, ]); }
{ "end_byte": 2723, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/ng-new/index.ts" }
angular-cli/packages/schematics/angular/ng-new/index_spec.ts_0_3535
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import { Schema as NgNewOptions } from './schema'; describe('Ng New Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: NgNewOptions = { name: 'foo', directory: 'bar', version: '6.0.0', }; it('should create files of a workspace', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('ng-new', options); const files = tree.files; expect(files).toContain('/bar/angular.json'); }); it('should create files of an application', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('ng-new', options); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/bar/tsconfig.app.json', '/bar/src/main.ts', '/bar/src/app/app.config.ts', ]), ); expect(files).not.toEqual(jasmine.arrayContaining(['/bar/src/app/app.module.ts'])); }); it('should create module files of a standalone=false application', async () => { const options = { ...defaultOptions, standalone: false }; const tree = await schematicRunner.runSchematic('ng-new', options); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/bar/tsconfig.app.json', '/bar/src/main.ts', '/bar/src/app/app.module.ts', ]), ); }); it('should should set the prefix in angular.json and in app.component.ts', async () => { const options = { ...defaultOptions, prefix: 'pre' }; const tree = await schematicRunner.runSchematic('ng-new', options); const content = tree.readContent('/bar/angular.json'); expect(content).toMatch(/"prefix": "pre"/); }); it('should set up the app module when standalone=false', async () => { const options: NgNewOptions = { name: 'foo', version: '6.0.0', standalone: false, }; const tree = await schematicRunner.runSchematic('ng-new', options); const moduleContent = tree.readContent('/foo/src/app/app.module.ts'); expect(moduleContent).toMatch(/declarations:\s*\[\s*AppComponent\s*\]/m); }); it('createApplication=false should create an empty workspace', async () => { const options = { ...defaultOptions, createApplication: false }; const tree = await schematicRunner.runSchematic('ng-new', options); const files = tree.files; expect(files).toContain('/bar/angular.json'); expect(files).not.toContain('/bar/src'); }); it('minimal=true should not create an e2e target', async () => { const options = { ...defaultOptions, minimal: true }; const tree = await schematicRunner.runSchematic('ng-new', options); const confContent = JSON.parse(tree.readContent('/bar/angular.json')); expect(confContent.projects.foo.e2e).toBeUndefined(); }); it('should add packageManager option in angular.json', async () => { const tree = await schematicRunner.runSchematic('ng-new', { ...defaultOptions, packageManager: 'npm', }); const { cli } = JSON.parse(tree.readContent('/bar/angular.json')); expect(cli.packageManager).toBe('npm'); }); });
{ "end_byte": 3535, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/ng-new/index_spec.ts" }
angular-cli/packages/schematics/angular/interceptor/index.ts_0_940
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Schema as InterceptorOptions } from './schema'; export default function (options: InterceptorOptions): Rule { // This schematic uses an older method to implement the flat option const flat = options.flat; options.flat = true; const extraTemplateValues = { 'if-flat': (s: string) => (flat ? '' : s), }; return options.functional ? generateFromFiles( { ...options, templateFilesDirectory: './functional-files' }, extraTemplateValues, ) : generateFromFiles( { ...options, templateFilesDirectory: './class-files' }, extraTemplateValues, ); }
{ "end_byte": 940, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/index.ts" }
angular-cli/packages/schematics/angular/interceptor/index_spec.ts_0_3459
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ServiceOptions } from './schema'; describe('Interceptor Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ServiceOptions = { name: 'foo', flat: false, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create an interceptor', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('interceptor', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.interceptor.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.interceptor.ts'); }); it('should respect the skipTests flag', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('interceptor', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.interceptor.ts'); expect(files).not.toContain('/projects/bar/src/app/foo/foo.interceptor.spec.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('interceptor', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo/foo.interceptor.ts'); }); it('should create a functional interceptor', async () => { const tree = await schematicRunner.runSchematic( 'interceptor', { ...defaultOptions, functional: true }, appTree, ); const fileString = tree.readContent('/projects/bar/src/app/foo/foo.interceptor.ts'); expect(fileString).toContain( 'export const fooInterceptor: HttpInterceptorFn = (req, next) => {', ); }); it('should create a helper function to run a functional interceptor in a test', async () => { const tree = await schematicRunner.runSchematic( 'interceptor', { ...defaultOptions, functional: true }, appTree, ); const fileString = tree.readContent('/projects/bar/src/app/foo/foo.interceptor.spec.ts'); expect(fileString).toContain('const interceptor: HttpInterceptorFn = (req, next) => '); expect(fileString).toContain('TestBed.runInInjectionContext(() => fooInterceptor(req, next));'); }); });
{ "end_byte": 3459, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/index_spec.ts" }
angular-cli/packages/schematics/angular/interceptor/class-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.spec.ts.template_0_507
import { TestBed } from '@angular/core/testing'; import { <%= classify(name) %>Interceptor } from './<%= dasherize(name) %>.interceptor'; describe('<%= classify(name) %>Interceptor', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [ <%= classify(name) %>Interceptor ] })); it('should be created', () => { const interceptor: <%= classify(name) %>Interceptor = TestBed.inject(<%= classify(name) %>Interceptor); expect(interceptor).toBeTruthy(); }); });
{ "end_byte": 507, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/class-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.spec.ts.template" }
angular-cli/packages/schematics/angular/interceptor/class-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.ts.template_0_426
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class <%= classify(name) %>Interceptor implements HttpInterceptor { constructor() {} intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { return next.handle(request); } }
{ "end_byte": 426, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/class-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.ts.template" }
angular-cli/packages/schematics/angular/interceptor/functional-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.spec.ts.template_0_545
import { TestBed } from '@angular/core/testing'; import { HttpInterceptorFn } from '@angular/common/http'; import { <%= camelize(name) %>Interceptor } from './<%= dasherize(name) %>.interceptor'; describe('<%= camelize(name) %>Interceptor', () => { const interceptor: HttpInterceptorFn = (req, next) => TestBed.runInInjectionContext(() => <%= camelize(name) %>Interceptor(req, next)); beforeEach(() => { TestBed.configureTestingModule({}); }); it('should be created', () => { expect(interceptor).toBeTruthy(); }); });
{ "end_byte": 545, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/functional-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.spec.ts.template" }
angular-cli/packages/schematics/angular/interceptor/functional-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.ts.template_0_166
import { HttpInterceptorFn } from '@angular/common/http'; export const <%= camelize(name) %>Interceptor: HttpInterceptorFn = (req, next) => { return next(req); };
{ "end_byte": 166, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interceptor/functional-files/__name@dasherize@if-flat__/__name@dasherize__.interceptor.ts.template" }
angular-cli/packages/schematics/angular/web-worker/index.ts_0_4500
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { join, normalize, tags } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree, apply, applyTemplates, chain, mergeWith, move, noop, strings, url, } from '@angular-devkit/schematics'; import { parseName } from '../utility/parse-name'; import { relativePathToWorkspaceRoot } from '../utility/paths'; import { buildDefaultPath, getWorkspace, updateWorkspace } from '../utility/workspace'; import { Schema as WebWorkerOptions } from './schema'; function addSnippet(options: WebWorkerOptions): Rule { return (host: Tree, context: SchematicContext) => { context.logger.debug('Updating appmodule'); if (options.path === undefined) { return; } const fileRegExp = new RegExp(`^${options.name}.*\\.ts`); const siblingModules = host .getDir(options.path) .subfiles // Find all files that start with the same name, are ts files, // and aren't spec or module files. .filter((f) => fileRegExp.test(f) && !/(module|spec)\.ts$/.test(f)) // Sort alphabetically for consistency. .sort(); if (siblingModules.length === 0) { // No module to add in. return; } const siblingModulePath = `${options.path}/${siblingModules[0]}`; const logMessage = 'console.log(`page got message: ${data}`);'; const workerCreationSnippet = tags.stripIndent` if (typeof Worker !== 'undefined') { // Create a new const worker = new Worker(new URL('./${options.name}.worker', import.meta.url)); worker.onmessage = ({ data }) => { ${logMessage} }; worker.postMessage('hello'); } else { // Web Workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } `; // Append the worker creation snippet. const originalContent = host.readText(siblingModulePath); host.overwrite(siblingModulePath, originalContent + '\n' + workerCreationSnippet); return host; }; } export default function (options: WebWorkerOptions): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); if (!options.project) { throw new SchematicsException('Option "project" is required.'); } const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Invalid project name (${options.project})`); } const projectType = project.extensions['projectType']; if (projectType !== 'application') { throw new SchematicsException(`Web Worker requires a project type of "application".`); } if (options.path === undefined) { options.path = buildDefaultPath(project); } const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; const templateSourceWorkerCode = apply(url('./files/worker'), [ applyTemplates({ ...options, ...strings }), move(parsedPath.path), ]); const root = project.root || ''; const templateSourceWorkerConfig = apply(url('./files/worker-tsconfig'), [ applyTemplates({ ...options, relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(root), }), move(root), ]); return chain([ // Add project configuration. updateWorkspace((workspace) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const project = workspace.projects.get(options.project)!; const buildTarget = project.targets.get('build'); const testTarget = project.targets.get('test'); if (!buildTarget) { throw new Error(`Build target is not defined for this project.`); } const workerConfigPath = join(normalize(root), 'tsconfig.worker.json'); (buildTarget.options ??= {}).webWorkerTsConfig ??= workerConfigPath; if (testTarget) { (testTarget.options ??= {}).webWorkerTsConfig ??= workerConfigPath; } }), // Create the worker in a sibling module. options.snippet ? addSnippet(options) : noop(), // Add the worker. mergeWith(templateSourceWorkerCode), mergeWith(templateSourceWorkerConfig), ]); }; }
{ "end_byte": 4500, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/web-worker/index.ts" }
angular-cli/packages/schematics/angular/web-worker/index_spec.ts_0_3487
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { parse as parseJson } from 'jsonc-parser'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as WebWorkerOptions } from './schema'; describe('Web Worker Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: WebWorkerOptions = { project: 'bar', name: 'app', snippet: true, }; let appTree: UnitTestTree; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '8.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: true, skipTests: false, skipPackageJson: false, }; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should put the worker file in the project root', async () => { const tree = await schematicRunner.runSchematic('web-worker', defaultOptions, appTree); const path = '/projects/bar/src/app/app.worker.ts'; expect(tree.exists(path)).toEqual(true); }); it('should put the tsconfig.worker.json file in the project root', async () => { const tree = await schematicRunner.runSchematic('web-worker', defaultOptions, appTree); const path = '/projects/bar/tsconfig.worker.json'; expect(tree.exists(path)).toEqual(true); const { compilerOptions } = parseJson(tree.readContent(path).toString()); expect(compilerOptions.outDir).toBe('../../out-tsc/worker'); }); it('should add the webWorkerTsConfig option to workspace', async () => { const tree = await schematicRunner.runSchematic('web-worker', defaultOptions, appTree); const { projects } = JSON.parse(tree.readContent('/angular.json')); expect(projects.bar.architect.build.options.webWorkerTsConfig).toBe( 'projects/bar/tsconfig.worker.json', ); }); it('should add snippet to sibling file', async () => { const tree = await schematicRunner.runSchematic('web-worker', defaultOptions, appTree); const appComponent = tree.readContent('/projects/bar/src/app/app.component.ts'); expect(appComponent).toContain(`new Worker(new URL('./${defaultOptions.name}.worker`); expect(appComponent).toContain('console.log(`page got message: ${data}`)'); }); it(`should add 'tsconfig.worker.json' outside of 'src' directory in root app`, async () => { const rootAppOptions = { ...appOptions, projectRoot: '', name: 'foo' }; const workerOptions = { ...defaultOptions, project: 'foo' }; appTree = await schematicRunner.runSchematic('application', rootAppOptions, appTree); const tree = await schematicRunner.runSchematic('web-worker', workerOptions, appTree); const path = '/tsconfig.worker.json'; expect(tree.exists(path)).toEqual(true); const { compilerOptions } = parseJson(tree.readContent(path).toString()); expect(compilerOptions.outDir).toBe('./out-tsc/worker'); }); });
{ "end_byte": 3487, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/web-worker/index_spec.ts" }
angular-cli/packages/schematics/angular/web-worker/files/worker-tsconfig/tsconfig.worker.json.template_0_400
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ { "extends": "<%= relativePathToWorkspaceRoot %>/tsconfig.json", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/worker", "lib": [ "es2018", "webworker" ], "types": [] }, "include": [ "src/**/*.worker.ts" ] }
{ "end_byte": 400, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/web-worker/files/worker-tsconfig/tsconfig.worker.json.template" }
angular-cli/packages/schematics/angular/web-worker/files/worker/__name@dasherize__.worker.ts.template_0_157
/// <reference lib="webworker" /> addEventListener('message', ({ data }) => { const response = `worker response to ${data}`; postMessage(response); });
{ "end_byte": 157, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/web-worker/files/worker/__name@dasherize__.worker.ts.template" }
angular-cli/packages/schematics/angular/resolver/index.ts_0_607
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Schema } from './schema'; export default function (options: Schema): Rule { return options.functional ? generateFromFiles({ ...options, templateFilesDirectory: './functional-files' }) : generateFromFiles({ ...options, templateFilesDirectory: './class-files' }); }
{ "end_byte": 607, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/index.ts" }
angular-cli/packages/schematics/angular/resolver/index_spec.ts_0_3937
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema } from './schema'; describe('resolver Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: Schema = { name: 'foo', flat: true, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create a (deprecated) class-based resolver with --no-functional', async () => { const tree = await schematicRunner.runSchematic( 'resolver', { ...defaultOptions, functional: false }, appTree, ); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo.resolver.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.resolver.ts'); const fileString = tree.readContent('/projects/bar/src/app/foo.resolver.ts'); expect(fileString).toContain('export class FooResolver implements Resolve<boolean>'); }); it('should respect the skipTests flag', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('resolver', options, appTree); const files = tree.files; expect(files).not.toContain('/projects/bar/src/app/foo.resolver.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.resolver.ts'); }); it('should respect the flat flag', async () => { const options = { ...defaultOptions, flat: false }; const tree = await schematicRunner.runSchematic('resolver', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.resolver.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.resolver.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('resolver', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo.resolver.ts'); }); it('should create a functional resolver', async () => { const tree = await schematicRunner.runSchematic('resolver', defaultOptions, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.resolver.ts'); expect(fileString).toContain( 'export const fooResolver: ResolveFn<boolean> = (route, state) => {', ); }); it('should create a helper function to run a functional resolver in a test', async () => { const tree = await schematicRunner.runSchematic('resolver', defaultOptions, appTree); const fileString = tree.readContent('/projects/bar/src/app/foo.resolver.spec.ts'); expect(fileString).toContain( 'const executeResolver: ResolveFn<boolean> = (...resolverParameters) => ', ); expect(fileString).toContain( 'TestBed.runInInjectionContext(() => fooResolver(...resolverParameters));', ); }); });
{ "end_byte": 3937, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/index_spec.ts" }
angular-cli/packages/schematics/angular/resolver/class-files/__name@dasherize__.resolver.spec.ts.template_0_441
import { TestBed } from '@angular/core/testing'; import { <%= classify(name) %>Resolver } from './<%= dasherize(name) %>.resolver'; describe('<%= classify(name) %>Resolver', () => { let resolver: <%= classify(name) %>Resolver; beforeEach(() => { TestBed.configureTestingModule({}); resolver = TestBed.inject(<%= classify(name) %>Resolver); }); it('should be created', () => { expect(resolver).toBeTruthy(); }); });
{ "end_byte": 441, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/class-files/__name@dasherize__.resolver.spec.ts.template" }
angular-cli/packages/schematics/angular/resolver/class-files/__name@dasherize__.resolver.ts.template_0_416
import { Injectable } from '@angular/core'; import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class <%= classify(name) %>Resolver implements Resolve<boolean> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return of(true); } }
{ "end_byte": 416, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/class-files/__name@dasherize__.resolver.ts.template" }
angular-cli/packages/schematics/angular/resolver/functional-files/__name@dasherize__.resolver.spec.ts.template_0_555
import { TestBed } from '@angular/core/testing'; import { ResolveFn } from '@angular/router'; import { <%= camelize(name) %>Resolver } from './<%= dasherize(name) %>.resolver'; describe('<%= camelize(name) %>Resolver', () => { const executeResolver: ResolveFn<boolean> = (...resolverParameters) => TestBed.runInInjectionContext(() => <%= camelize(name) %>Resolver(...resolverParameters)); beforeEach(() => { TestBed.configureTestingModule({}); }); it('should be created', () => { expect(executeResolver).toBeTruthy(); }); });
{ "end_byte": 555, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/functional-files/__name@dasherize__.resolver.spec.ts.template" }
angular-cli/packages/schematics/angular/resolver/functional-files/__name@dasherize__.resolver.ts.template_0_149
import { ResolveFn } from '@angular/router'; export const <%= camelize(name) %>Resolver: ResolveFn<boolean> = (route, state) => { return true; };
{ "end_byte": 149, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/resolver/functional-files/__name@dasherize__.resolver.ts.template" }
angular-cli/packages/schematics/angular/service-worker/index.ts_0_5788
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { join, normalize, tags } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree, apply, applyTemplates, chain, mergeWith, move, url, } from '@angular-devkit/schematics'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { addDependency, addRootProvider, readWorkspace, writeWorkspace } from '../utility'; import { addSymbolToNgModuleMetadata, insertImport } from '../utility/ast-utils'; import { applyToUpdateRecorder } from '../utility/change'; import { getPackageJsonDependency } from '../utility/dependencies'; import { getAppModulePath, isStandaloneApp } from '../utility/ng-ast-utils'; import { relativePathToWorkspaceRoot } from '../utility/paths'; import { targetBuildNotFoundError } from '../utility/project-targets'; import { findAppConfig } from '../utility/standalone/app_config'; import { findBootstrapApplicationCall } from '../utility/standalone/util'; import { Builders } from '../utility/workspace-models'; import { Schema as ServiceWorkerOptions } from './schema'; function addDependencies(): Rule { return (host: Tree) => { const coreDep = getPackageJsonDependency(host, '@angular/core'); if (!coreDep) { throw new SchematicsException('Could not find "@angular/core" version.'); } return addDependency('@angular/service-worker', coreDep.version); }; } function updateAppModule(mainPath: string): Rule { return (host: Tree, context: SchematicContext) => { context.logger.debug('Updating appmodule'); const modulePath = getAppModulePath(host, mainPath); context.logger.debug(`module path: ${modulePath}`); addImport(host, modulePath, 'ServiceWorkerModule', '@angular/service-worker'); addImport(host, modulePath, 'isDevMode', '@angular/core'); // register SW in application module const importText = tags.stripIndent` ServiceWorkerModule.register('ngsw-worker.js', { enabled: !isDevMode(), // Register the ServiceWorker as soon as the application is stable // or after 30 seconds (whichever comes first). registrationStrategy: 'registerWhenStable:30000' }) `; const moduleSource = getTsSourceFile(host, modulePath); const metadataChanges = addSymbolToNgModuleMetadata( moduleSource, modulePath, 'imports', importText, ); if (metadataChanges) { const recorder = host.beginUpdate(modulePath); applyToUpdateRecorder(recorder, metadataChanges); host.commitUpdate(recorder); } return host; }; } function addProvideServiceWorker(projectName: string, mainPath: string): Rule { return (host: Tree) => { const bootstrapCall = findBootstrapApplicationCall(host, mainPath); const appConfig = findAppConfig(bootstrapCall, host, mainPath)?.filePath || mainPath; addImport(host, appConfig, 'isDevMode', '@angular/core'); return addRootProvider( projectName, ({ code, external }) => code`${external('provideServiceWorker', '@angular/service-worker')}('ngsw-worker.js', { enabled: !isDevMode(), registrationStrategy: 'registerWhenStable:30000' })`, ); }; } function getTsSourceFile(host: Tree, path: string): ts.SourceFile { const content = host.readText(path); const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); return source; } export default function (options: ServiceWorkerOptions): Rule { return async (host: Tree) => { const workspace = await readWorkspace(host); const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Invalid project name (${options.project})`); } if (project.extensions.projectType !== 'application') { throw new SchematicsException(`Service worker requires a project type of "application".`); } const buildTarget = project.targets.get('build'); if (!buildTarget) { throw targetBuildNotFoundError(); } const buildOptions = buildTarget.options as Record<string, string | boolean>; let browserEntryPoint: string | undefined; const ngswConfigPath = join(normalize(project.root), 'ngsw-config.json'); if (buildTarget.builder === Builders.Application) { browserEntryPoint = buildOptions.browser as string; const productionConf = buildTarget.configurations?.production; if (productionConf) { productionConf.serviceWorker = ngswConfigPath; } } else { browserEntryPoint = buildOptions.main as string; buildOptions.serviceWorker = true; buildOptions.ngswConfigPath = ngswConfigPath; } await writeWorkspace(host, workspace); return chain([ addDependencies(), mergeWith( apply(url('./files'), [ applyTemplates({ ...options, relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(project.root), }), move(project.root), ]), ), isStandaloneApp(host, browserEntryPoint) ? addProvideServiceWorker(options.project, browserEntryPoint) : updateAppModule(browserEntryPoint), ]); }; } function addImport(host: Tree, filePath: string, symbolName: string, moduleName: string): void { const moduleSource = getTsSourceFile(host, filePath); const change = insertImport(moduleSource, filePath, symbolName, moduleName); if (change) { const recorder = host.beginUpdate(filePath); applyToUpdateRecorder(recorder, [change]); host.commitUpdate(recorder); } }
{ "end_byte": 5788, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service-worker/index.ts" }
angular-cli/packages/schematics/angular/service-worker/index_spec.ts_0_8843
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Builders } from '../utility/workspace-models'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ServiceWorkerOptions } from './schema'; describe('Service Worker Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ServiceWorkerOptions = { project: 'bar', target: 'build', }; let appTree: UnitTestTree; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should add `serviceWorker` option to build target', async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const configText = tree.readContent('/angular.json'); const buildConfig = JSON.parse(configText).projects.bar.architect.build; expect(buildConfig.configurations.production.serviceWorker).toBe( 'projects/bar/ngsw-config.json', ); }); it('should add the necessary dependency', async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const pkgText = tree.readContent('/package.json'); const pkg = JSON.parse(pkgText); const version = pkg.dependencies['@angular/core']; expect(pkg.dependencies['@angular/service-worker']).toEqual(version); }); it('should put the ngsw-config.json file in the project root', async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const path = '/projects/bar/ngsw-config.json'; expect(tree.exists(path)).toEqual(true); const { projects } = JSON.parse(tree.readContent('/angular.json')); expect(projects.bar.architect.build.configurations.production.serviceWorker).toBe( 'projects/bar/ngsw-config.json', ); }); it('should add $schema in ngsw-config.json with correct relative path', async () => { const pathToNgswConfigSchema = 'node_modules/@angular/service-worker/config/schema.json'; const name = 'foo'; const rootAppOptions: ApplicationOptions = { ...appOptions, name, projectRoot: '', }; const rootSWOptions: ServiceWorkerOptions = { ...defaultOptions, project: name, }; const rootAppTree = await schematicRunner.runSchematic('application', rootAppOptions, appTree); const treeInRoot = await schematicRunner.runSchematic( 'service-worker', rootSWOptions, rootAppTree, ); const pkgTextInRoot = treeInRoot.readContent('/ngsw-config.json'); const configInRoot = JSON.parse(pkgTextInRoot); expect(configInRoot.$schema).toBe(`./${pathToNgswConfigSchema}`); const treeNotInRoot = await schematicRunner.runSchematic( 'service-worker', defaultOptions, appTree, ); const pkgTextNotInRoot = treeNotInRoot.readContent('/projects/bar/ngsw-config.json'); const configNotInRoot = JSON.parse(pkgTextNotInRoot); expect(configNotInRoot.$schema).toBe(`../../${pathToNgswConfigSchema}`); }); it('should generate ngsw-config.json in root when the application is at root level', async () => { const name = 'foo'; const rootAppOptions: ApplicationOptions = { ...appOptions, name, projectRoot: '', }; const rootSWOptions: ServiceWorkerOptions = { ...defaultOptions, project: name, }; let tree = await schematicRunner.runSchematic('application', rootAppOptions, appTree); tree = await schematicRunner.runSchematic('service-worker', rootSWOptions, tree); expect(tree.exists('/ngsw-config.json')).toBe(true); }); it(`should add the 'provideServiceWorker' to providers`, async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const content = tree.readContent('/projects/bar/src/app/app.config.ts'); expect(tags.oneLine`${content}`).toContain(tags.oneLine` provideServiceWorker('ngsw-worker.js', { enabled: !isDevMode(), registrationStrategy: 'registerWhenStable:30000' }) `); }); it(`should import 'isDevMode' from '@angular/core'`, async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const content = tree.readContent('/projects/bar/src/app/app.config.ts'); expect(content).toContain( `import { ApplicationConfig, provideZoneChangeDetection, isDevMode } from '@angular/core';`, ); }); it(`should import 'provideServiceWorker' from '@angular/service-worker'`, async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const content = tree.readContent('/projects/bar/src/app/app.config.ts'); expect(content).toContain(`import { provideServiceWorker } from '@angular/service-worker';`); }); describe('standalone=false', () => { const name = 'buz'; const nonStandaloneAppOptions: ApplicationOptions = { ...appOptions, name, standalone: false, }; const nonStandaloneSWOptions: ServiceWorkerOptions = { ...defaultOptions, project: name, }; beforeEach(async () => { appTree = await schematicRunner.runSchematic('application', nonStandaloneAppOptions, appTree); }); it('should import ServiceWorkerModule', async () => { const tree = await schematicRunner.runSchematic( 'service-worker', nonStandaloneSWOptions, appTree, ); const pkgText = tree.readContent('/projects/buz/src/app/app.module.ts'); expect(pkgText).toMatch(/import \{ ServiceWorkerModule \} from '@angular\/service-worker'/); }); it('should add the SW import to the NgModule imports', async () => { const tree = await schematicRunner.runSchematic( 'service-worker', nonStandaloneSWOptions, appTree, ); const pkgText = tree.readContent('/projects/buz/src/app/app.module.ts'); expect(pkgText).toMatch( new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: !isDevMode\\(\\),\\n' + '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', ), ); }); }); describe('Legacy browser builder', () => { function convertBuilderToLegacyBrowser(): void { const config = JSON.parse(appTree.readContent('/angular.json')); const build = config.projects.bar.architect.build; build.builder = Builders.Browser; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2)); } beforeEach(() => { convertBuilderToLegacyBrowser(); }); it('should add `serviceWorker` option to build target', async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const configText = tree.readContent('/angular.json'); const buildConfig = JSON.parse(configText).projects.bar.architect.build; expect(buildConfig.options.serviceWorker).toBeTrue(); }); it('should add `ngswConfigPath` option to build target', async () => { const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree); const configText = tree.readContent('/angular.json'); const buildConfig = JSON.parse(configText).projects.bar.architect.build; expect(buildConfig.options.ngswConfigPath).toBe('projects/bar/ngsw-config.json'); }); }); });
{ "end_byte": 8843, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service-worker/index_spec.ts" }
angular-cli/packages/schematics/angular/service-worker/files/ngsw-config.json.template_0_672
{ "$schema": "<%= relativePathToWorkspaceRoot %>/node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.csr.html", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" ] } } ] }
{ "end_byte": 672, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/service-worker/files/ngsw-config.json.template" }
angular-cli/packages/schematics/angular/utility/eol.ts_0_555
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EOL } from 'node:os'; const CRLF = '\r\n'; const LF = '\n'; export function getEOL(content: string): string { const newlines = content.match(/(?:\r?\n)/g); if (newlines?.length) { const crlf = newlines.filter((l) => l === CRLF).length; const lf = newlines.length - crlf; return crlf > lf ? CRLF : LF; } return EOL; }
{ "end_byte": 555, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/eol.ts" }
angular-cli/packages/schematics/angular/utility/validation.ts_0_1181
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicsException } from '@angular-devkit/schematics'; // Must start with a letter, and must contain only alphanumeric characters or dashes. // When adding a dash the segment after the dash must also start with a letter. export const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*((:?-[0-9]+)*|(:?-[a-zA-Z][.0-9a-zA-Z]*(:?-[0-9]+)*)*)$/; // See: https://github.com/tc39/proposal-regexp-unicode-property-escapes/blob/fe6d07fad74cd0192d154966baa1e95e7cda78a1/README.md#other-examples const ecmaIdentifierNameRegExp = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u; export function validateHtmlSelector(selector: string): void { if (selector && !htmlSelectorRe.test(selector)) { throw new SchematicsException(`Selector "${selector}" is invalid.`); } } export function validateClassName(className: string): void { if (!ecmaIdentifierNameRegExp.test(className)) { throw new SchematicsException(`Class name "${className}" is invalid.`); } }
{ "end_byte": 1181, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/validation.ts" }
angular-cli/packages/schematics/angular/utility/dependencies.ts_0_1780
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Tree } from '@angular-devkit/schematics'; import { JSONFile } from './json-file'; const PKG_JSON_PATH = '/package.json'; export enum NodeDependencyType { Default = 'dependencies', Dev = 'devDependencies', Peer = 'peerDependencies', Optional = 'optionalDependencies', } export interface NodeDependency { type: NodeDependencyType; name: string; version: string; overwrite?: boolean; } const ALL_DEPENDENCY_TYPE = [ NodeDependencyType.Default, NodeDependencyType.Dev, NodeDependencyType.Optional, NodeDependencyType.Peer, ]; export function addPackageJsonDependency( tree: Tree, dependency: NodeDependency, pkgJsonPath = PKG_JSON_PATH, ): void { const json = new JSONFile(tree, pkgJsonPath); const { overwrite, type, name, version } = dependency; const path = [type, name]; if (overwrite || !json.get(path)) { json.modify(path, version); } } export function removePackageJsonDependency( tree: Tree, name: string, pkgJsonPath = PKG_JSON_PATH, ): void { const json = new JSONFile(tree, pkgJsonPath); for (const depType of ALL_DEPENDENCY_TYPE) { json.remove([depType, name]); } } export function getPackageJsonDependency( tree: Tree, name: string, pkgJsonPath = PKG_JSON_PATH, ): NodeDependency | null { const json = new JSONFile(tree, pkgJsonPath); for (const depType of ALL_DEPENDENCY_TYPE) { const version = json.get([depType, name]); if (typeof version === 'string') { return { type: depType, name: name, version, }; } } return null; }
{ "end_byte": 1780, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependencies.ts" }
angular-cli/packages/schematics/angular/utility/find-module_spec.ts_0_7720
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EmptyTree, Tree } from '@angular-devkit/schematics'; import { ModuleOptions, buildRelativePath, findModule, findModuleFromOptions } from './find-module'; describe('find-module', () => { describe('findModule', () => { let host: Tree; const modulePath = '/foo/src/app/app.module.ts'; beforeEach(() => { host = new EmptyTree(); host.create(modulePath, 'app module'); }); it('should find a module', () => { const foundModule = findModule(host, 'foo/src/app/bar'); expect(foundModule).toEqual(modulePath); }); it('should not find a module in another sub dir', () => { host.create('/foo/src/app/buzz/buzz.module.ts', 'app module'); const foundModule = findModule(host, 'foo/src/app/bar'); expect(foundModule).toEqual(modulePath); }); it('should ignore routing modules', () => { host.create('/foo/src/app/app-routing.module.ts', 'app module'); const foundModule = findModule(host, 'foo/src/app/bar'); expect(foundModule).toEqual(modulePath); }); it('should work with weird paths', () => { host.create('/foo/src/app/app-routing.module.ts', 'app module'); const foundModule = findModule(host, 'foo//src//app/bar/'); expect(foundModule).toEqual(modulePath); }); it('should throw if no modules found', () => { host.create('/foo/src/app/oops.module.ts', 'app module'); expect(() => findModule(host, 'foo/src/app/bar')).toThrowError( /More than one module matches/, ); }); it('should throw if only routing modules were found', () => { host = new EmptyTree(); host.create('/foo/src/app/anything-routing.module.ts', 'anything routing module'); expect(() => findModule(host, 'foo/src/app/anything-routing')).toThrowError( /Could not find a non Routing NgModule/, ); }); it('should throw if two modules found', () => { host = new EmptyTree(); expect(() => findModule(host, 'foo/src/app/bar')).toThrowError(/Could not find an NgModule/); }); it('should accept custom ext for module', () => { const host = new EmptyTree(); const modulePath = '/foo/src/app/app_module.ts'; host.create(modulePath, 'app module'); // Should find module if given a custom ext const foundModule = findModule(host, 'foo/src/app/bar', '_module.ts'); expect(foundModule).toBe(modulePath); // Should not find module if using default ext expect(() => findModule(host, 'foo/src/app/bar')).toThrowError(/Could not find an NgModule/); }); it('should not find module if ext is invalid', () => { expect(() => findModule(host, 'foo/src/app/bar', '-module.ts')).toThrowError( /Could not find an NgModule/, ); expect(() => findModule(host, 'foo/src/app/bar', '_module.ts')).toThrowError( /Could not find an NgModule/, ); }); }); describe('findModuleFromOptions', () => { let tree: Tree; let options: ModuleOptions; beforeEach(() => { tree = new EmptyTree(); options = { name: 'foo' }; }); it('should find a module', () => { tree.create('/projects/my-proj/src/app.module.ts', ''); options.module = 'app.module.ts'; options.path = '/projects/my-proj/src'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/app.module.ts'); }); it('should find a module when name has underscore', () => { tree.create('/projects/my-proj/src/feature_module/app_test.module.ts', ''); options.path = '/projects/my-proj/src'; options.name = 'feature_module/new_component'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/feature_module/app_test.module.ts'); }); it('should find a module when name has uppercase', () => { tree.create('/projects/my-proj/src/featureModule/appTest.module.ts', ''); options.path = '/projects/my-proj/src'; options.name = 'featureModule/newComponent'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/featureModule/appTest.module.ts'); }); it('should find a module if flat is true', () => { tree.create('/projects/my-proj/src/module/app_test.module.ts', ''); options.path = '/projects/my-proj/src'; options.flat = true; options.name = '/module/directive'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/module/app_test.module.ts'); }); it('should find a module in a sub dir', () => { tree.create('/projects/my-proj/src/admin/foo.module.ts', ''); options.name = 'other/test'; options.module = 'admin/foo'; options.path = '/projects/my-proj/src'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/admin/foo.module.ts'); }); it('should find a module in a sub dir (2)', () => { tree.create('/projects/my-proj/src/admin/foo.module.ts', ''); options.name = 'admin/hello'; options.module = 'foo'; options.path = '/projects/my-proj/src'; const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toEqual('/projects/my-proj/src/admin/foo.module.ts'); }); it('should find a module using custom ext', () => { tree.create('/projects/my-proj/src/app_module.ts', ''); options.module = 'app'; options.path = '/projects/my-proj/src'; options.moduleExt = '_module.ts'; // Should find module using custom moduleExt const modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toBe('/projects/my-proj/src/app_module.ts'); // Should not find module if using invalid ext options.moduleExt = '-module.ts'; expect(() => findModuleFromOptions(tree, options) as string).toThrowError( /Specified module 'app' does not exist/, ); // Should not find module if using default ext options.moduleExt = undefined; // use default ext expect(() => findModuleFromOptions(tree, options) as string).toThrowError( /Specified module 'app' does not exist/, ); }); it('should ignore custom ext if module or ${module}.ts exists', () => { tree.create('/projects/my-proj/src/app.module.ts', ''); options.path = '/projects/my-proj/src'; options.moduleExt = '_module.ts'; let modPath; // moduleExt ignored because exact path is found options.module = 'app.module.ts'; modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toBe('/projects/my-proj/src/app.module.ts'); // moduleExt ignored because module + .ts is found options.module = 'app.module'; modPath = findModuleFromOptions(tree, options) as string; expect(modPath).toBe('/projects/my-proj/src/app.module.ts'); }); }); describe('buildRelativePath', () => { it('works', () => { expect(buildRelativePath('/test/module', '/test/service')).toEqual('./service'); expect(buildRelativePath('/test/module', '/other/service')).toEqual('../other/service'); expect(buildRelativePath('/module', '/test/service')).toEqual('./test/service'); expect(buildRelativePath('/test/service', '/module')).toEqual('../module'); }); }); });
{ "end_byte": 7720, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/find-module_spec.ts" }
angular-cli/packages/schematics/angular/utility/change.ts_0_4347
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { UpdateRecorder } from '@angular-devkit/schematics'; export interface Host { write(path: string, content: string): Promise<void>; read(path: string): Promise<string>; } export interface Change { apply(host: Host): Promise<void>; // The file this change should be applied to. Some changes might not apply to // a file (maybe the config). readonly path: string | null; // The order this change should be applied. Normally the position inside the file. // Changes are applied from the bottom of a file to the top. readonly order: number; // The description of this change. This will be outputted in a dry or verbose run. readonly description: string; } /** * An operation that does nothing. */ export class NoopChange implements Change { description = 'No operation.'; order = Infinity; path = null; apply() { return Promise.resolve(); } } /** * Will add text to the source code. */ export class InsertChange implements Change { order: number; description: string; constructor( public path: string, public pos: number, public toAdd: string, ) { if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Inserted ${toAdd} into position ${pos} of ${path}`; this.order = pos; } /** * This method does not insert spaces if there is none in the original string. */ apply(host: Host) { return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos); return host.write(this.path, `${prefix}${this.toAdd}${suffix}`); }); } } /** * Will remove text from the source code. */ export class RemoveChange implements Change { order: number; description: string; constructor( public path: string, private pos: number, public toRemove: string, ) { if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Removed ${toRemove} into position ${pos} of ${path}`; this.order = pos; } apply(host: Host): Promise<void> { return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.toRemove.length); // TODO: throw error if toRemove doesn't match removed string. return host.write(this.path, `${prefix}${suffix}`); }); } } /** * Will replace text from the source code. */ export class ReplaceChange implements Change { order: number; description: string; constructor( public path: string, private pos: number, public oldText: string, public newText: string, ) { if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Replaced ${oldText} into position ${pos} of ${path} with ${newText}`; this.order = pos; } apply(host: Host): Promise<void> { return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.oldText.length); const text = content.substring(this.pos, this.pos + this.oldText.length); if (text !== this.oldText) { return Promise.reject(new Error(`Invalid replace: "${text}" != "${this.oldText}".`)); } // TODO: throw error if oldText doesn't match removed string. return host.write(this.path, `${prefix}${this.newText}${suffix}`); }); } } export function applyToUpdateRecorder(recorder: UpdateRecorder, changes: Change[]): void { for (const change of changes) { if (change instanceof InsertChange) { recorder.insertLeft(change.pos, change.toAdd); } else if (change instanceof RemoveChange) { recorder.remove(change.order, change.toRemove.length); } else if (change instanceof ReplaceChange) { recorder.remove(change.order, change.oldText.length); recorder.insertLeft(change.order, change.newText); } else if (!(change instanceof NoopChange)) { throw new Error('Unknown Change type encountered when updating a recorder.'); } } }
{ "end_byte": 4347, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/change.ts" }
angular-cli/packages/schematics/angular/utility/paths_spec.ts_0_1101
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { relativePathToWorkspaceRoot } from './paths'; describe('paths', () => { describe('relativePathToWorkspaceRoot', () => { it(`should handle root '/'`, () => { const result = relativePathToWorkspaceRoot('/'); expect(result).toBe('.'); }); it(`should handle an empty path`, () => { const result = relativePathToWorkspaceRoot(''); expect(result).toBe('.'); }); it(`should handle an undefined path`, () => { const result = relativePathToWorkspaceRoot(undefined); expect(result).toBe('.'); }); it(`should handle path with trailing '/'`, () => { const result = relativePathToWorkspaceRoot('foo/bar/'); expect(result).toBe('../..'); }); it(`should handle path without trailing '/'`, () => { const result = relativePathToWorkspaceRoot('foo/bar'); expect(result).toBe('../..'); }); }); });
{ "end_byte": 1101, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/paths_spec.ts" }
angular-cli/packages/schematics/angular/utility/dependencies_spec.ts_0_3017
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EmptyTree } from '@angular-devkit/schematics'; import { UnitTestTree } from '@angular-devkit/schematics/testing'; import { NodeDependency, NodeDependencyType, addPackageJsonDependency, getPackageJsonDependency, } from './dependencies'; describe('dependencies', () => { describe('addDependency', () => { let tree: UnitTestTree; const pkgJsonPath = '/package.json'; let dependency: NodeDependency; beforeEach(() => { tree = new UnitTestTree(new EmptyTree()); tree.create(pkgJsonPath, '{}'); dependency = { type: NodeDependencyType.Default, name: 'my-pkg', version: '1.2.3', }; }); [ { type: NodeDependencyType.Default, key: 'dependencies' }, { type: NodeDependencyType.Dev, key: 'devDependencies' }, { type: NodeDependencyType.Optional, key: 'optionalDependencies' }, { type: NodeDependencyType.Peer, key: 'peerDependencies' }, ].forEach((type) => { describe(`Type: ${type.toString()}`, () => { beforeEach(() => { dependency.type = type.type; }); it('should add a dependency', () => { addPackageJsonDependency(tree, dependency); const pkgJson = JSON.parse(tree.readContent(pkgJsonPath)); expect(pkgJson[type.key][dependency.name]).toEqual(dependency.version); }); it('should handle an existing dependency (update version)', () => { addPackageJsonDependency(tree, { ...dependency, version: '0.0.0' }); addPackageJsonDependency(tree, { ...dependency, overwrite: true }); const pkgJson = JSON.parse(tree.readContent(pkgJsonPath)); expect(pkgJson[type.key][dependency.name]).toEqual(dependency.version); }); }); }); it('should throw when missing package.json', () => { expect(() => addPackageJsonDependency(new EmptyTree(), dependency)).toThrow(); }); }); describe('getDependency', () => { let tree: UnitTestTree; beforeEach(() => { const pkgJsonPath = '/package.json'; const pkgJsonContent = JSON.stringify( { dependencies: { 'my-pkg': '1.2.3', }, }, null, 2, ); tree = new UnitTestTree(new EmptyTree()); tree.create(pkgJsonPath, pkgJsonContent); }); it('should get a dependency', () => { const dep = getPackageJsonDependency(tree, 'my-pkg') as NodeDependency; expect(dep.type).toEqual(NodeDependencyType.Default); expect(dep.name).toEqual('my-pkg'); expect(dep.version).toEqual('1.2.3'); }); it('should return null if dependency does not exist', () => { const dep = getPackageJsonDependency(tree, 'missing-pkg') as NodeDependency; expect(dep).toBeNull(); }); }); });
{ "end_byte": 3017, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependencies_spec.ts" }
angular-cli/packages/schematics/angular/utility/dependency_spec.ts_0_1040
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EmptyTree, Rule, SchematicContext, TaskConfigurationGenerator, Tree, callRule, chain, } from '@angular-devkit/schematics'; import { DependencyType, ExistingBehavior, InstallBehavior, addDependency } from './dependency'; interface LogEntry { type: 'warn'; message: string; } async function testRule( rule: Rule, tree: Tree, ): Promise<{ tasks: TaskConfigurationGenerator[]; logs: LogEntry[] }> { const tasks: TaskConfigurationGenerator[] = []; const logs: LogEntry[] = []; const context = { addTask(task: TaskConfigurationGenerator) { tasks.push(task); }, logger: { warn(message: string): void { logs.push({ type: 'warn', message }); }, }, }; await callRule(rule, tree, context as unknown as SchematicContext).toPromise(); return { tasks, logs }; }
{ "end_byte": 1040, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependency_spec.ts" }
angular-cli/packages/schematics/angular/utility/dependency_spec.ts_1042_9247
describe('addDependency', () => { it('adds a package to "dependencies" by default', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: {}, }), ); const rule = addDependency('@angular/core', '^14.0.0'); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ dependencies: { '@angular/core': '^14.0.0' }, }); }); it('warns if a package is already present with a different specifier by default', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/core': '^13.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0'); const { logs } = await testRule(rule, tree); expect(logs).toContain( jasmine.objectContaining({ type: 'warn', message: 'Package dependency "@angular/core" already exists with a different specifier. ' + '"^13.0.0" will be replaced with "^14.0.0".', }), ); }); it('warns if a package is already present with a different specifier with replace behavior', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/core': '^13.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0', { existing: ExistingBehavior.Replace }); const { logs } = await testRule(rule, tree); expect(logs).toContain( jasmine.objectContaining({ type: 'warn', message: 'Package dependency "@angular/core" already exists with a different specifier. ' + '"^13.0.0" will be replaced with "^14.0.0".', }), ); }); it('replaces the specifier if a package is already present with a different specifier with replace behavior', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/core': '^13.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0', { existing: ExistingBehavior.Replace }); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ dependencies: { '@angular/core': '^14.0.0' }, }); }); it('does not replace the specifier if a package is already present with a different specifier with skip behavior', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/core': '^13.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0', { existing: ExistingBehavior.Skip }); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ dependencies: { '@angular/core': '^13.0.0' }, }); }); it('adds a package version with other packages in alphabetical order', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/common': '^14.0.0', '@angular/router': '^14.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0'); await testRule(rule, tree); expect( Object.entries((tree.readJson('/package.json') as { dependencies: {} }).dependencies), ).toEqual([ ['@angular/common', '^14.0.0'], ['@angular/core', '^14.0.0'], ['@angular/router', '^14.0.0'], ]); }); it('adds a dependency section if not present', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0'); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ dependencies: { '@angular/core': '^14.0.0' }, }); }); it('adds a package to "devDependencies" when "type" is "dev"', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: {}, devDependencies: {}, }), ); const rule = addDependency('@angular/core', '^14.0.0', { type: DependencyType.Dev }); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ dependencies: {}, devDependencies: { '@angular/core': '^14.0.0' }, }); }); it('adds a package to "peerDependencies" when "type" is "peer"', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ devDependencies: {}, peerDependencies: {}, }), ); const rule = addDependency('@angular/core', '^14.0.0', { type: DependencyType.Peer }); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({ devDependencies: {}, peerDependencies: { '@angular/core': '^14.0.0' }, }); }); it('uses specified manifest when provided via "manifestPath" option', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); tree.create('/abc/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', }); await testRule(rule, tree); expect(tree.readJson('/package.json')).toEqual({}); expect(tree.readJson('/abc/package.json')).toEqual({ dependencies: { '@angular/core': '^14.0.0' }, }); }); it('schedules a package install task', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0'); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('schedules a package install task with working directory when "packageJsonPath" is used', async () => { const tree = new EmptyTree(); tree.create('/abc/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', }); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/abc' }), }, ]); }); it('schedules a package install task when install behavior is auto', async () => { const tree = new EmptyTree(); tree.create('/abc/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', install: InstallBehavior.Auto, }); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/abc' }), }, ]); }); it('schedules a package install task when install behavior is always', async () => { const tree = new EmptyTree(); tree.create('/abc/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', install: InstallBehavior.Always, }); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/abc' }), }, ]); }); it('does not schedule a package install task when install behavior is none', async () => { const tree = new EmptyTree(); tree.create('/abc/package.json', JSON.stringify({})); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', install: InstallBehavior.None, }); const { tasks } = await testRule(rule, tree); expect(tasks).toEqual([]); });
{ "end_byte": 9247, "start_byte": 1042, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependency_spec.ts" }
angular-cli/packages/schematics/angular/utility/dependency_spec.ts_9251_14674
it('does not schedule a package install task if version is the same', async () => { const tree = new EmptyTree(); tree.create( '/package.json', JSON.stringify({ dependencies: { '@angular/core': '^14.0.0' }, }), ); const rule = addDependency('@angular/core', '^14.0.0'); const { tasks } = await testRule(rule, tree); expect(tasks).toEqual([]); }); it('only schedules one package install task for the same manifest path by default', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0'), addDependency('@angular/common', '^14.0.0'), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('only schedules one package install task for the same manifest path with auto install behavior', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0', { install: InstallBehavior.Auto }), addDependency('@angular/common', '^14.0.0', { install: InstallBehavior.Auto }), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('only schedules one package install task for the same manifest path with mixed auto/none install behavior', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0', { install: InstallBehavior.Auto }), addDependency('@angular/common', '^14.0.0', { install: InstallBehavior.None }), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('only schedules one package install task for the same manifest path with mixed always then auto install behavior', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0', { install: InstallBehavior.Always }), addDependency('@angular/common', '^14.0.0', { install: InstallBehavior.Auto }), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('schedules multiple package install tasks for the same manifest path with mixed auto then always install behavior', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0', { install: InstallBehavior.Auto }), addDependency('@angular/common', '^14.0.0', { install: InstallBehavior.Always }), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, ]); }); it('schedules a package install task for each manifest path present', async () => { const tree = new EmptyTree(); tree.create('/package.json', JSON.stringify({})); tree.create('/abc/package.json', JSON.stringify({})); const rule = chain([ addDependency('@angular/core', '^14.0.0'), addDependency('@angular/common', '^14.0.0', { packageJsonPath: '/abc/package.json' }), ]); const { tasks } = await testRule(rule, tree); expect(tasks.map((task) => task.toConfiguration())).toEqual([ { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/' }), }, { name: 'node-package', options: jasmine.objectContaining({ command: 'install', workingDirectory: '/abc' }), }, ]); }); it('throws an error when the default manifest path does not exist', async () => { const tree = new EmptyTree(); const rule = addDependency('@angular/core', '^14.0.0'); await expectAsync(testRule(rule, tree)).toBeRejectedWithError( undefined, `Path "/package.json" does not exist.`, ); }); it('throws an error when the specified manifest path does not exist', async () => { const tree = new EmptyTree(); const rule = addDependency('@angular/core', '^14.0.0', { packageJsonPath: '/abc/package.json', }); await expectAsync(testRule(rule, tree)).toBeRejectedWithError( undefined, `Path "/abc/package.json" does not exist.`, ); }); });
{ "end_byte": 14674, "start_byte": 9251, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependency_spec.ts" }
angular-cli/packages/schematics/angular/utility/workspace.ts_0_5739
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, workspaces } from '@angular-devkit/core'; import { Rule, Tree, noop } from '@angular-devkit/schematics'; import { ProjectType } from './workspace-models'; const DEFAULT_WORKSPACE_PATH = '/angular.json'; // re-export the workspace definition types for convenience export type WorkspaceDefinition = workspaces.WorkspaceDefinition; export type ProjectDefinition = workspaces.ProjectDefinition; export type TargetDefinition = workspaces.TargetDefinition; /** * A {@link workspaces.WorkspaceHost} backed by a Schematics {@link Tree} instance. */ export class TreeWorkspaceHost implements workspaces.WorkspaceHost { constructor(private readonly tree: Tree) {} async readFile(path: string): Promise<string> { return this.tree.readText(path); } async writeFile(path: string, data: string): Promise<void> { if (this.tree.exists(path)) { this.tree.overwrite(path, data); } else { this.tree.create(path, data); } } async isDirectory(path: string): Promise<boolean> { // approximate a directory check return !this.tree.exists(path) && this.tree.getDir(path).subfiles.length > 0; } async isFile(path: string): Promise<boolean> { return this.tree.exists(path); } } /** * Updates the workspace file (`angular.json`) found within the root of the schematic's tree. * The workspace object model can be directly modified within the provided updater function * with changes being written to the workspace file after the updater function returns. * The spacing and overall layout of the file (including comments) will be maintained where * possible when updating the file. * * @param updater An update function that can be used to modify the object model for the * workspace. A {@link WorkspaceDefinition} is provided as the first argument to the function. */ export function updateWorkspace( updater: (workspace: WorkspaceDefinition) => void | Rule | PromiseLike<void | Rule>, ): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); const result = await updater(workspace); await workspaces.writeWorkspace(workspace, new TreeWorkspaceHost(host)); return result || noop; }; } // TODO: This should be renamed `readWorkspace` once deep imports are restricted (already exported from `utility` with that name) /** * Reads a workspace file (`angular.json`) from the provided {@link Tree} instance. * * @param tree A schematics {@link Tree} instance used to access the workspace file. * @param path The path where a workspace file should be found. If a file is specified, the file * path will be used. If a directory is specified, the file `angular.json` will be used from * within the specified directory. Defaults to `/angular.json`. * @returns A {@link WorkspaceDefinition} representing the workspace found at the specified path. */ export async function getWorkspace( tree: Tree, path = DEFAULT_WORKSPACE_PATH, ): Promise<WorkspaceDefinition> { const host = new TreeWorkspaceHost(tree); const { workspace } = await workspaces.readWorkspace(path, host); return workspace; } /** * Writes a workspace file (`angular.json`) to the provided {@link Tree} instance. * The spacing and overall layout of an exisitng file (including comments) will be maintained where * possible when writing the file. * * @param tree A schematics {@link Tree} instance used to access the workspace file. * @param workspace The {@link WorkspaceDefinition} to write. * @param path The path where a workspace file should be written. If a file is specified, the file * path will be used. If not provided, the definition's underlying file path stored during reading * will be used. */ export async function writeWorkspace( tree: Tree, workspace: WorkspaceDefinition, path?: string, ): Promise<void> { const host = new TreeWorkspaceHost(tree); return workspaces.writeWorkspace(workspace, host, path); } /** * Build a default project path for generating. * @param project The project which will have its default path generated. */ export function buildDefaultPath(project: workspaces.ProjectDefinition): string { const root = project.sourceRoot ? `/${project.sourceRoot}/` : `/${project.root}/src/`; const projectDirName = project.extensions['projectType'] === ProjectType.Application ? 'app' : 'lib'; return `${root}${projectDirName}`; } export async function createDefaultPath(tree: Tree, projectName: string): Promise<string> { const workspace = await getWorkspace(tree); const project = workspace.projects.get(projectName); if (!project) { throw new Error(`Project "${projectName}" does not exist.`); } return buildDefaultPath(project); } export function* allWorkspaceTargets( workspace: workspaces.WorkspaceDefinition, ): Iterable<[string, workspaces.TargetDefinition, string, workspaces.ProjectDefinition]> { for (const [projectName, project] of workspace.projects) { for (const [targetName, target] of project.targets) { yield [targetName, target, projectName, project]; } } } export function* allTargetOptions( target: workspaces.TargetDefinition, skipBaseOptions = false, ): Iterable<[string | undefined, Record<string, json.JsonValue | undefined>]> { if (!skipBaseOptions && target.options) { yield [undefined, target.options]; } if (!target.configurations) { return; } for (const [name, options] of Object.entries(target.configurations)) { if (options !== undefined) { yield [name, options]; } } }
{ "end_byte": 5739, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/workspace.ts" }
angular-cli/packages/schematics/angular/utility/add-declaration-to-ng-module.ts_0_1998
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, Tree, strings } from '@angular-devkit/schematics'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { addDeclarationToModule, addSymbolToNgModuleMetadata } from './ast-utils'; import { InsertChange } from './change'; import { buildRelativePath } from './find-module'; export interface DeclarationToNgModuleOptions { module?: string; path?: string; name: string; flat?: boolean; export?: boolean; type: string; skipImport?: boolean; standalone?: boolean; } export function addDeclarationToNgModule(options: DeclarationToNgModuleOptions): Rule { return (host: Tree) => { const modulePath = options.module; if (options.skipImport || options.standalone || !modulePath) { return host; } const sourceText = host.readText(modulePath); const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true); const filePath = `/${options.path}/` + (options.flat ? '' : strings.dasherize(options.name) + '/') + strings.dasherize(options.name) + (options.type ? '.' : '') + strings.dasherize(options.type); const importPath = buildRelativePath(modulePath, filePath); const classifiedName = strings.classify(options.name) + strings.classify(options.type); const changes = addDeclarationToModule(source, modulePath, classifiedName, importPath); if (options.export) { changes.push(...addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName)); } const recorder = host.beginUpdate(modulePath); for (const change of changes) { if (change instanceof InsertChange) { recorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(recorder); return host; }; }
{ "end_byte": 1998, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/add-declaration-to-ng-module.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_0_1304
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { HostTree } from '@angular-devkit/schematics'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { Change, InsertChange } from '../utility/change'; import { getFileContent } from '../utility/test'; import { addDeclarationToModule, addExportToModule, addProviderToModule, addRouteDeclarationToModule, addSymbolToNgModuleMetadata, findNodes, hasTopLevelIdentifier, insertAfterLastOccurrence, insertImport, } from './ast-utils'; function getTsSource(path: string, content: string): ts.SourceFile { return ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); } function applyChanges(path: string, content: string, changes: Change[]): string { const tree = new HostTree(); tree.create(path, content); const exportRecorder = tree.beginUpdate(path); for (const change of changes) { if (change instanceof InsertChange) { exportRecorder.insertLeft(change.pos, change.toAdd); } } tree.commitUpdate(exportRecorder); return getFileContent(tree, path); }
{ "end_byte": 1304, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_1306_9008
describe('ast utils', () => { let modulePath: string; let moduleContent: string; beforeEach(() => { modulePath = '/src/app/app.module.ts'; moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `; }); it('should add export to module', () => { const source = getTsSource(modulePath, moduleContent); const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/exports: \[\n(\s*) {2}FooComponent\n\1\]/); }); it('should add export to module if not indented', () => { moduleContent = tags.stripIndents`${moduleContent}`; const source = getTsSource(modulePath, moduleContent); const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/exports: \[\n(\s*) {2}FooComponent\n\1\]/); }); it('should add declarations to module if not indented', () => { moduleContent = tags.stripIndents`${moduleContent}`; const source = getTsSource(modulePath, moduleContent); const changes = addDeclarationToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/declarations: \[\nAppComponent,\nFooComponent\n\]/); }); it('should add declarations to module when PropertyAssignment is StringLiteral', () => { moduleContent = tags.stripIndents` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ "declarations": [ AppComponent ], "imports": [ BrowserModule ], "providers": [], "bootstrap": [AppComponent] })`; const source = getTsSource(modulePath, moduleContent); const changes = addDeclarationToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/"declarations": \[\nAppComponent,\nFooComponent\n\]/); }); it('should add metadata', () => { const source = getTsSource(modulePath, moduleContent); const changes = addSymbolToNgModuleMetadata(source, modulePath, 'imports', 'HelloWorld'); expect(changes).not.toBeNull(); const output = applyChanges(modulePath, moduleContent, changes || []); expect(output).toMatch(/imports: \[[^\]]+,\n(\s*) {2}HelloWorld\n\1\]/); }); it('should add metadata (comma)', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addSymbolToNgModuleMetadata(source, modulePath, 'imports', 'HelloWorld'); expect(changes).not.toBeNull(); const output = applyChanges(modulePath, moduleContent, changes || []); expect(output).toMatch(/imports: \[[^\]]+,\n(\s*) {2}HelloWorld,\n\1\]/); }); it('should add metadata (missing)', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @NgModule({ declarations: [ AppComponent ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addSymbolToNgModuleMetadata(source, modulePath, 'imports', 'HelloWorld'); expect(changes).not.toBeNull(); const output = applyChanges(modulePath, moduleContent, changes || []); expect(output).toMatch(/imports: \[\n(\s*) {2}HelloWorld\n\1\]/); }); it('should add metadata (empty)', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @NgModule({ declarations: [ AppComponent ], providers: [], imports: [], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addSymbolToNgModuleMetadata(source, modulePath, 'imports', 'HelloWorld'); expect(changes).not.toBeNull(); const output = applyChanges(modulePath, moduleContent, changes || []); expect(output).toMatch(/imports: \[\n(\s*) {2}HelloWorld\n\1\],\n/); }); it(`should handle NgModule with newline after '@'`, () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @ NgModule({imports: [BrowserModule], declarations: []}) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/exports: \[FooComponent\]/); }); it('should handle NgModule with no newlines', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @NgModule({imports: [BrowserModule], declarations: []}) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/); expect(output).toMatch(/exports: \[FooComponent\]/); }); it('should add into providers metadata in new line ', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @NgModule({ imports: [BrowserModule], declarations: [], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addProviderToModule(source, modulePath, 'LogService', './log.service'); const output = applyChanges(modulePath, moduleContent, changes); expect(output).toMatch(/import { LogService } from '.\/log.service';/); expect(output).toMatch(/\},\r?\n\s*LogService\r?\n\s*\]/); });
{ "end_byte": 9008, "start_byte": 1306, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_9012_10435
describe('insertAfterLastOccurrence', () => { const filePath = './src/foo.ts'; it('should work for the default scenario', () => { const fileContent = `const arr = ['foo'];`; const source = getTsSource(filePath, fileContent); const arrayNode = findNodes(source.getChildren()[0], ts.SyntaxKind.ArrayLiteralExpression); const elements = (arrayNode.pop() as ts.ArrayLiteralExpression).elements; const change = insertAfterLastOccurrence( elements as unknown as ts.Node[], `, 'bar'`, filePath, elements.pos, ts.SyntaxKind.StringLiteral, ); const output = applyChanges(filePath, fileContent, [change]); expect(output).toMatch(/const arr = \['foo', 'bar'\];/); }); it('should work without occurrences', () => { const fileContent = `const arr = [];`; const source = getTsSource(filePath, fileContent); const arrayNode = findNodes(source.getChildren()[0], ts.SyntaxKind.ArrayLiteralExpression); const elements = (arrayNode.pop() as ts.ArrayLiteralExpression).elements; const change = insertAfterLastOccurrence( elements as unknown as ts.Node[], `'bar'`, filePath, elements.pos, ts.SyntaxKind.StringLiteral, ); const output = applyChanges(filePath, fileContent, [change]); expect(output).toMatch(/const arr = \['bar'\];/); }); });
{ "end_byte": 10435, "start_byte": 9012, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_10439_19492
describe('addRouteDeclarationToModule', () => { it('should throw an error when there is no router module', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [BrowserModule], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const change = () => addRouteDeclarationToModule(source, './src/app', ''); expect(change).toThrowError(/Couldn't find a route declaration in \.\/src\/app/); }); it(`should throw an error when router module doesn't have arguments`, () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot() ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const change = () => addRouteDeclarationToModule(source, './src/app', ''); expect(change).toThrowError( `The router module method doesn't have arguments at line 11 in ./src/app`, ); }); it(`should throw an error when the provided var (array) to router module doesn't exist`, () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const change = () => addRouteDeclarationToModule(source, './src/app', ''); expect(change).toThrowError( `No route declaration array was found that corresponds to router module at line 11 in ./src/app`, ); }); it(`should throw an error, if the provided first argument of router module is not an identifier`, () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(42) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const change = () => addRouteDeclarationToModule(source, './src/app', ''); expect(change).toThrowError( `No route declaration array was found that corresponds to router module at line 11 in ./src/app`, ); }); it('should add a route to the routes array', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; const routes = []; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'foo', component: FooComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch(/const routes = \[{ path: 'foo', component: FooComponent }\]/); }); it('should add a route to the routes array when there are multiple declarations', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; const routes = [ { path: 'foo', component: FooComponent } ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'bar', component: BarComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch( /const routes = \[\r?\n?\s*{ path: 'foo', component: FooComponent },\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]/, ); }); it('should add a route before the last wildcard path', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; const routes = [ { path: '**', component: FooComponent } ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'bar', component: BarComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch( /const routes = \[\r?\n?\s*{ path: 'bar', component: BarComponent },\r?\n?\s*{ path: '\*\*', component: FooComponent }\r?\n?\s*\]/, ); }); it('should add a route to the routes to the correct array when having guards', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; const routes = [ { path: 'foo', component: FooComponent, canMatch: [Guard] } ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'bar', component: BarComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); /* eslint-disable max-len */ expect(output).toMatch( /const routes = \[\r?\n?\s*{ path: 'foo', component: FooComponent, canMatch: \[Guard\] },\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]/, ); /* eslint-enable max-len */ }); it('should add a route to the routes to the correct array when having nested object literal', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; const routes = [ { path: 'foo', component: FooComponent, data: { path: 'test' }} ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'bar', component: BarComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch( // eslint-disable-next-line max-len /const routes = \[\r?\n?\s*{ path: 'foo', component: FooComponent, data: { path: 'test' }},\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]/, ); });
{ "end_byte": 19492, "start_byte": 10439, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_19498_26623
it('should add a route to the routes argument of RouteModule', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot([]) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'foo', component: FooComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch( /RouterModule\.forRoot\(\[{ path: 'foo', component: FooComponent }\]\)/, ); }); it('should add a route to the routes argument of RouterModule when there are multiple declarations', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot([{ path: 'foo', component: FooComponent }]) ], bootstrap: [AppComponent] }) export class AppModule { } `; const source = getTsSource(modulePath, moduleContent); const changes = addRouteDeclarationToModule( source, './src/app', `{ path: 'bar', component: BarComponent }`, ); const output = applyChanges(modulePath, moduleContent, [changes]); expect(output).toMatch( // eslint-disable-next-line max-len /RouterModule\.forRoot\(\[\r?\n?\s*{ path: 'foo', component: FooComponent },\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]\)/, ); }); it('should error if sourcefile is empty', () => { const change = () => addRouteDeclarationToModule( getTsSource(modulePath, ''), './src/app', `{ path: 'foo', component: FooComponent }`, ); expect(change).toThrowError(/Couldn't find a route declaration in \.\/src\/app/); }); }); describe('findNodes', () => { const filePath = './src/foo.ts'; const fileContent = ` const a = { nodeAtDepth0: { nodeAtDepth1: { nodeAtDepth2: { nodeAtDepth3: 'foo' }, }, }, }; `; let recursive: boolean; describe('when `recursive` is not set', () => { beforeEach(() => { recursive = false; }); it('should return node excluding nested nodes', () => { const source = getTsSource(filePath, fileContent); const paNodes = findNodes(source, ts.SyntaxKind.PropertyAssignment, Infinity, recursive); expect(paNodes.length).toEqual(1); }); }); describe('when `recursive` is set', () => { beforeEach(() => { recursive = true; }); it('should return node including all nested nodes', () => { const source = getTsSource(filePath, fileContent); const paNodes = findNodes(source, ts.SyntaxKind.PropertyAssignment, Infinity, recursive); expect(paNodes.length).toEqual(4); }); }); }); describe('insertImport', () => { const filePath = './src/foo.ts'; it('should insert a new import into a file', () => { const fileContent = ''; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'Component', '@angular/core'); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(`import { Component } from '@angular/core';`); }); it('should insert a new import under an alias into a file', () => { const fileContent = ''; const source = getTsSource(filePath, fileContent); const change = insertImport( source, filePath, 'Component', '@angular/core', false, 'NgComponent', ); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(`import { Component as NgComponent } from '@angular/core';`); }); it('should reuse imports from the same module without an alias', () => { const fileContent = `import { Pipe } from '@angular/core';`; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'Component', '@angular/core'); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(`import { Pipe, Component } from '@angular/core';`); }); it('should reuse imports from the same module with an alias', () => { const fileContent = `import { Pipe } from '@angular/core';`; const source = getTsSource(filePath, fileContent); const change = insertImport( source, filePath, 'Component', '@angular/core', false, 'NgComponent', ); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(`import { Pipe, Component as NgComponent } from '@angular/core';`); }); it('should reuse imports for the same symbol', () => { const fileContent = `import { Component } from '@angular/core';`; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'Component', '@angular/core'); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(fileContent); }); it('should not insert a new import if the symbol is imported under an alias', () => { const fileContent = `import { Component as NgComponent } from '@angular/core';`; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'Component', '@angular/core'); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(fileContent); }); it('should insert a new default import into a file', () => { const fileContent = ''; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'core', '@angular/core', true); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(`import core from '@angular/core';`); }); it('should not insert an import if there is a namespace import', () => { const fileContent = `import * as foo from '@angular/core';`; const source = getTsSource(filePath, fileContent); const change = insertImport(source, filePath, 'Component', '@angular/core'); const result = applyChanges(filePath, fileContent, [change]).trim(); expect(result).toBe(fileContent); }); });
{ "end_byte": 26623, "start_byte": 19498, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils_spec.ts_26627_29224
describe('hasTopLevelIdentifier', () => { const filePath = './src/foo.ts'; it('should find top-level class declaration with a specific name', () => { const fileContent = `class FooClass {}`; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'FooClass')).toBe(true); expect(hasTopLevelIdentifier(source, 'Foo')).toBe(false); }); it('should find top-level interface declaration with a specific name', () => { const fileContent = `interface FooInterface {}`; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'FooInterface')).toBe(true); expect(hasTopLevelIdentifier(source, 'Foo')).toBe(false); }); it('should find top-level variable declaration with a specific name', () => { const fileContent = ` const singleVar = 1; const fooVar = 1, barVar = 2; `; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'singleVar')).toBe(true); expect(hasTopLevelIdentifier(source, 'fooVar')).toBe(true); expect(hasTopLevelIdentifier(source, 'barVar')).toBe(true); expect(hasTopLevelIdentifier(source, 'bar')).toBe(false); }); it('should find top-level imports with a specific name', () => { const fileContent = ` import { FooInterface } from '@foo/interfaces'; class FooClass implements FooInterface {} `; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'FooInterface')).toBe(true); expect(hasTopLevelIdentifier(source, 'Foo')).toBe(false); }); it('should find top-level aliased imports with a specific name', () => { const fileContent = ` import { FooInterface as AliasedFooInterface } from '@foo/interfaces'; class FooClass implements AliasedFooInterface {} `; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'AliasedFooInterface')).toBe(true); expect(hasTopLevelIdentifier(source, 'FooInterface')).toBe(false); expect(hasTopLevelIdentifier(source, 'Foo')).toBe(false); }); it('should be able to skip imports from a certain module', () => { const fileContent = ` import { FooInterface } from '@foo/interfaces'; class FooClass implements FooInterface {} `; const source = getTsSource(filePath, fileContent); expect(hasTopLevelIdentifier(source, 'FooInterface', '@foo/interfaces')).toBe(false); }); }); });
{ "end_byte": 29224, "start_byte": 26627, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils_spec.ts" }
angular-cli/packages/schematics/angular/utility/dependency.ts_0_6141
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, SchematicContext } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import * as path from 'path'; const installTasks = new WeakMap<SchematicContext, Set<string>>(); interface MinimalPackageManifest { dependencies?: Record<string, string>; devDependencies?: Record<string, string>; peerDependencies?: Record<string, string>; } /** * An enum used to specify the type of a dependency found within a package manifest * file (`package.json`). */ export enum DependencyType { Default = 'dependencies', Dev = 'devDependencies', Peer = 'peerDependencies', } /** * An enum used to specify the dependency installation behavior for the {@link addDependency} * schematics rule. The installation behavior affects if and when {@link NodePackageInstallTask} * will be scheduled when using the rule. */ export enum InstallBehavior { /** * No installation will occur as a result of the rule when specified. * * NOTE: This does not prevent other rules from scheduling a {@link NodePackageInstallTask} * which may install the dependency. */ None, /** * Automatically determine the need to schedule a {@link NodePackageInstallTask} based on * previous usage of the {@link addDependency} within the schematic. */ Auto, /** * Always schedule a {@link NodePackageInstallTask} when the rule is executed. */ Always, } /** * An enum used to specify the existing dependency behavior for the {@link addDependency} * schematics rule. The existing behavior affects whether the named dependency will be added * to the `package.json` when the dependency is already present with a differing specifier. */ export enum ExistingBehavior { /** * The dependency will not be added or otherwise changed if it already exists. */ Skip, /** * The dependency's existing specifier will be replaced with the specifier provided in the * {@link addDependency} call. A warning will also be shown during schematic execution to * notify the user of the replacement. */ Replace, } /** * Adds a package as a dependency to a `package.json`. By default the `package.json` located * at the schematic's root will be used. The `manifestPath` option can be used to explicitly specify * a `package.json` in different location. The type of the dependency can also be specified instead * of the default of the `dependencies` section by using the `type` option for either `devDependencies` * or `peerDependencies`. * * When using this rule, {@link NodePackageInstallTask} does not need to be included directly by * a schematic. A package manager install task will be automatically scheduled as needed. * * @param name The name of the package to add. * @param specifier The package specifier for the package to add. Typically a SemVer range. * @param options An optional object that can contain the `type` of the dependency * and/or a path (`packageJsonPath`) of a manifest file (`package.json`) to modify. * @returns A Schematics {@link Rule} */ export function addDependency( name: string, specifier: string, options: { /** * The type of the dependency determines the section of the `package.json` to which the * dependency will be added. Defaults to {@link DependencyType.Default} (`dependencies`). */ type?: DependencyType; /** * The path of the package manifest file (`package.json`) that will be modified. * Defaults to `/package.json`. */ packageJsonPath?: string; /** * The dependency installation behavior to use to determine whether a * {@link NodePackageInstallTask} should be scheduled after adding the dependency. * Defaults to {@link InstallBehavior.Auto}. */ install?: InstallBehavior; /** * The behavior to use when the dependency already exists within the `package.json`. * Defaults to {@link ExistingBehavior.Replace}. */ existing?: ExistingBehavior; } = {}, ): Rule { const { type = DependencyType.Default, packageJsonPath = '/package.json', install = InstallBehavior.Auto, existing = ExistingBehavior.Replace, } = options; return (tree, context) => { const manifest = tree.readJson(packageJsonPath) as MinimalPackageManifest; const dependencySection = manifest[type]; if (!dependencySection) { // Section is not present. The dependency can be added to a new object literal for the section. manifest[type] = { [name]: specifier }; } else { const existingSpecifier = dependencySection[name]; if (existingSpecifier === specifier) { // Already present with same specifier return; } if (existingSpecifier) { // Already present but different specifier if (existing === ExistingBehavior.Skip) { return; } // ExistingBehavior.Replace is the only other behavior currently context.logger.warn( `Package dependency "${name}" already exists with a different specifier. ` + `"${existingSpecifier}" will be replaced with "${specifier}".`, ); } // Add new dependency in alphabetical order const entries = Object.entries(dependencySection); entries.push([name, specifier]); entries.sort((a, b) => a[0].localeCompare(b[0])); manifest[type] = Object.fromEntries(entries); } tree.overwrite(packageJsonPath, JSON.stringify(manifest, null, 2)); const installPaths = installTasks.get(context) ?? new Set<string>(); if ( install === InstallBehavior.Always || (install === InstallBehavior.Auto && !installPaths.has(packageJsonPath)) ) { context.addTask( new NodePackageInstallTask({ workingDirectory: path.dirname(packageJsonPath) }), ); installPaths.add(packageJsonPath); installTasks.set(context, installPaths); } }; }
{ "end_byte": 6141, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/dependency.ts" }
angular-cli/packages/schematics/angular/utility/parse-name.ts_0_606
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Path, basename, dirname, join, normalize } from '@angular-devkit/core'; export interface Location { name: string; path: Path; } export function parseName(path: string, name: string): Location { const nameWithoutPath = basename(normalize(name)); const namePath = dirname(join(normalize(path), name)); return { name: nameWithoutPath, path: normalize('/' + namePath), }; }
{ "end_byte": 606, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/parse-name.ts" }
angular-cli/packages/schematics/angular/utility/ng-ast-utils.ts_0_2983
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicsException, Tree } from '@angular-devkit/schematics'; import { dirname, join } from 'node:path/posix'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { findNode, getSourceNodes } from '../utility/ast-utils'; import { findBootstrapApplicationCall } from './standalone/util'; export function findBootstrapModuleCall(host: Tree, mainPath: string): ts.CallExpression | null { const mainText = host.readText(mainPath); const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true); const allNodes = getSourceNodes(source); let bootstrapCall: ts.CallExpression | null = null; for (const node of allNodes) { let bootstrapCallNode: ts.Node | null = null; bootstrapCallNode = findNode(node, ts.SyntaxKind.Identifier, 'bootstrapModule'); // Walk up the parent until CallExpression is found. while ( bootstrapCallNode && bootstrapCallNode.parent && bootstrapCallNode.parent.kind !== ts.SyntaxKind.CallExpression ) { bootstrapCallNode = bootstrapCallNode.parent; } if ( bootstrapCallNode !== null && bootstrapCallNode.parent !== undefined && bootstrapCallNode.parent.kind === ts.SyntaxKind.CallExpression ) { bootstrapCall = bootstrapCallNode.parent as ts.CallExpression; break; } } return bootstrapCall; } function findBootstrapModulePath(host: Tree, mainPath: string): string { const bootstrapCall = findBootstrapModuleCall(host, mainPath); if (!bootstrapCall) { throw new SchematicsException('Bootstrap call not found'); } const bootstrapModule = bootstrapCall.arguments[0]; const mainText = host.readText(mainPath); const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true); const allNodes = getSourceNodes(source); const bootstrapModuleRelativePath = allNodes .filter(ts.isImportDeclaration) .filter((imp) => { return findNode(imp, ts.SyntaxKind.Identifier, bootstrapModule.getText()); }) .map((imp) => { const modulePathStringLiteral = imp.moduleSpecifier as ts.StringLiteral; return modulePathStringLiteral.text; })[0]; return bootstrapModuleRelativePath; } export function getAppModulePath(host: Tree, mainPath: string): string { const moduleRelativePath = findBootstrapModulePath(host, mainPath); const mainDir = dirname(mainPath); const modulePath = join(mainDir, `${moduleRelativePath}.ts`); return modulePath; } export function isStandaloneApp(host: Tree, mainPath: string): boolean { try { findBootstrapApplicationCall(host, mainPath); return true; } catch (error) { if (error instanceof SchematicsException) { return false; } throw error; } }
{ "end_byte": 2983, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ng-ast-utils.ts" }
angular-cli/packages/schematics/angular/utility/latest-versions.ts_0_814
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // We could have used TypeScripts' `resolveJsonModule` to make the `latestVersion` object typesafe, // but ts_library doesn't support JSON inputs. const dependencies = require('./latest-versions/package.json')['dependencies']; export const latestVersions: Record<string, string> & { Angular: string; DevkitBuildAngular: string; AngularSSR: string; } = { ...dependencies, // As Angular CLI works with same minor versions of Angular Framework, a tilde match for the current Angular: dependencies['@angular/core'], DevkitBuildAngular: '^0.0.0-PLACEHOLDER', AngularSSR: '^0.0.0-PLACEHOLDER', };
{ "end_byte": 814, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/latest-versions.ts" }
angular-cli/packages/schematics/angular/utility/workspace-models.ts_0_5396
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export enum ProjectType { Application = 'application', Library = 'library', } /** * An enum of the official Angular builders. * Each enum value provides the fully qualified name of the associated builder. * This enum can be used when analyzing the `builder` fields of project configurations from the * `angular.json` workspace file. */ export enum Builders { Application = '@angular-devkit/build-angular:application', AppShell = '@angular-devkit/build-angular:app-shell', Server = '@angular-devkit/build-angular:server', Browser = '@angular-devkit/build-angular:browser', SsrDevServer = '@angular-devkit/build-angular:ssr-dev-server', Prerender = '@angular-devkit/build-angular:prerender', BrowserEsbuild = '@angular-devkit/build-angular:browser-esbuild', Karma = '@angular-devkit/build-angular:karma', TsLint = '@angular-devkit/build-angular:tslint', NgPackagr = '@angular-devkit/build-angular:ng-packagr', DevServer = '@angular-devkit/build-angular:dev-server', ExtractI18n = '@angular-devkit/build-angular:extract-i18n', Protractor = '@angular-devkit/build-angular:private-protractor', BuildApplication = '@angular/build:application', } export interface FileReplacements { replace: string; with: string; } export interface BrowserBuilderBaseOptions { main: string; tsConfig: string; fileReplacements?: FileReplacements[]; outputPath?: string; index?: string; polyfills: string; assets?: (object | string)[]; styles?: (object | string)[]; scripts?: (object | string)[]; sourceMap?: boolean; } export type OutputHashing = 'all' | 'media' | 'none' | 'bundles'; export interface BrowserBuilderOptions extends BrowserBuilderBaseOptions { serviceWorker?: boolean; optimization?: boolean; outputHashing?: OutputHashing; resourcesOutputPath?: string; namedChunks?: boolean; aot?: boolean; extractLicenses?: boolean; vendorChunk?: boolean; buildOptimizer?: boolean; ngswConfigPath?: string; budgets?: { type: string; maximumWarning?: string; maximumError?: string; }[]; webWorkerTsConfig?: string; } export interface ServeBuilderOptions { buildTarget: string; } export interface LibraryBuilderOptions { tsConfig: string; project: string; } export interface ServerBuilderOptions { outputPath: string; tsConfig: string; main: string; fileReplacements?: FileReplacements[]; optimization?: | boolean | { scripts?: boolean; styles?: boolean; }; sourceMap?: | boolean | { scripts?: boolean; styles?: boolean; hidden?: boolean; vendor?: boolean; }; } export interface AppShellBuilderOptions { browserTarget: string; serverTarget: string; route: string; } export interface TestBuilderOptions extends Partial<BrowserBuilderBaseOptions> { karmaConfig: string; } export interface ExtractI18nOptions { browserTarget: string; } export interface E2EOptions { protractorConfig: string; devServerTarget: string; } export interface BuilderTarget<TBuilder extends Builders, TOptions> { builder: TBuilder; options: TOptions; configurations?: { production: Partial<TOptions>; [key: string]: Partial<TOptions>; }; } export type LibraryBuilderTarget = BuilderTarget<Builders.NgPackagr, LibraryBuilderOptions>; export type BrowserBuilderTarget = BuilderTarget<Builders.Browser, BrowserBuilderOptions>; export type ServerBuilderTarget = BuilderTarget<Builders.Server, ServerBuilderOptions>; export type AppShellBuilderTarget = BuilderTarget<Builders.AppShell, AppShellBuilderOptions>; export type TestBuilderTarget = BuilderTarget<Builders.Karma, TestBuilderOptions>; export type ServeBuilderTarget = BuilderTarget<Builders.DevServer, ServeBuilderOptions>; export type ExtractI18nBuilderTarget = BuilderTarget<Builders.ExtractI18n, ExtractI18nOptions>; export type E2EBuilderTarget = BuilderTarget<Builders.Protractor, E2EOptions>; interface WorkspaceCLISchema { warnings?: Record<string, boolean>; schematicCollections?: string[]; } export interface WorkspaceSchema { version: 1; cli?: WorkspaceCLISchema; projects: { [key: string]: WorkspaceProject<ProjectType.Application | ProjectType.Library>; }; } export interface WorkspaceProject<TProjectType extends ProjectType = ProjectType.Application> { /** * Project type. */ projectType: ProjectType; root: string; sourceRoot: string; prefix: string; cli?: WorkspaceCLISchema; /** * Tool options. */ architect?: WorkspaceTargets<TProjectType>; /** * Tool options. */ targets?: WorkspaceTargets<TProjectType>; } export interface WorkspaceTargets<TProjectType extends ProjectType = ProjectType.Application> { build?: TProjectType extends ProjectType.Library ? LibraryBuilderTarget : BrowserBuilderTarget; server?: ServerBuilderTarget; test?: TestBuilderTarget; serve?: ServeBuilderTarget; e2e?: E2EBuilderTarget; 'app-shell'?: AppShellBuilderTarget; 'extract-i18n'?: ExtractI18nBuilderTarget; // TODO(hans): change this any to unknown when google3 supports TypeScript 3.0. // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; }
{ "end_byte": 5396, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/workspace-models.ts" }
angular-cli/packages/schematics/angular/utility/generate-from-files.ts_0_1696
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, Tree, apply, applyTemplates, chain, filter, mergeWith, move, noop, strings, url, } from '@angular-devkit/schematics'; import { parseName } from './parse-name'; import { validateClassName } from './validation'; import { createDefaultPath } from './workspace'; export interface GenerateFromFilesOptions { flat?: boolean; name: string; path?: string; prefix?: string; project: string; skipTests?: boolean; templateFilesDirectory?: string; } export function generateFromFiles( options: GenerateFromFilesOptions, extraTemplateValues: Record<string, string | ((v: string) => string)> = {}, ): Rule { return async (host: Tree) => { options.path ??= await createDefaultPath(host, options.project); options.prefix ??= ''; options.flat ??= true; const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; validateClassName(strings.classify(options.name)); const templateFilesDirectory = options.templateFilesDirectory ?? './files'; const templateSource = apply(url(templateFilesDirectory), [ options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(), applyTemplates({ ...strings, ...options, ...extraTemplateValues, }), move(parsedPath.path + (options.flat ? '' : '/' + strings.dasherize(options.name))), ]); return chain([mergeWith(templateSource)]); }; }
{ "end_byte": 1696, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/generate-from-files.ts" }
angular-cli/packages/schematics/angular/utility/workspace_spec.ts_0_4033
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EmptyTree, Rule, SchematicContext, Tree, callRule } from '@angular-devkit/schematics'; import { getWorkspace as readWorkspace, updateWorkspace, writeWorkspace } from './workspace'; const TEST_WORKSPACE_CONTENT = JSON.stringify({ version: 1, projects: { test: { root: '', }, }, }); async function testRule(rule: Rule, tree: Tree): Promise<void> { await callRule(rule, tree, {} as unknown as SchematicContext).toPromise(); } describe('readWorkspace', () => { it('reads a workspace using the default path value', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); const workspace = await readWorkspace(tree); expect(workspace.projects.has('test')).toBeTrue(); }); it('reads a workspace when specifying a directory path', async () => { const tree = new EmptyTree(); tree.create('/xyz/angular.json', TEST_WORKSPACE_CONTENT); const workspace = await readWorkspace(tree, '/xyz/'); expect(workspace.projects.has('test')).toBeTrue(); }); it('reads a workspace when specifying a file path', async () => { const tree = new EmptyTree(); tree.create('/xyz/angular.json', TEST_WORKSPACE_CONTENT); const workspace = await readWorkspace(tree, '/xyz/angular.json'); expect(workspace.projects.has('test')).toBeTrue(); }); it('throws if workspace file does not exist when using the default path value', async () => { const tree = new EmptyTree(); await expectAsync(readWorkspace(tree)).toBeRejectedWithError(); }); it('throws if workspace file does not exist when specifying a file path', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); await expectAsync(readWorkspace(tree, 'abc.json')).toBeRejectedWithError(); }); }); describe('writeWorkspace', () => { it('writes a workspace using the default path value', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); const workspace = await readWorkspace(tree); workspace.extensions['x-abc'] = 1; await writeWorkspace(tree, workspace); expect(tree.readJson('/angular.json')).toEqual(jasmine.objectContaining({ 'x-abc': 1 })); }); it('writes a workspace when specifying a path', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); const workspace = await readWorkspace(tree); workspace.extensions['x-abc'] = 1; await writeWorkspace(tree, workspace, '/xyz/angular.json'); expect(tree.readJson('/xyz/angular.json')).toEqual(jasmine.objectContaining({ 'x-abc': 1 })); }); }); describe('updateWorkspace', () => { it('updates a workspace using the default path value', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); const rule = updateWorkspace((workspace) => { workspace.projects.add({ name: 'abc', root: 'src', }); }); await testRule(rule, tree); expect(tree.read('angular.json')?.toString()).toContain('"abc"'); }); it('throws if workspace file does not exist', async () => { const tree = new EmptyTree(); const rule = updateWorkspace((workspace) => { workspace.projects.add({ name: 'abc', root: 'src', }); }); await expectAsync(testRule(rule, tree)).toBeRejectedWithError(); }); it('allows executing a returned followup rule', async () => { const tree = new EmptyTree(); tree.create('/angular.json', TEST_WORKSPACE_CONTENT); const rule = updateWorkspace(() => { return (tree) => tree.create('/followup.txt', '12345'); }); await testRule(rule, tree); expect(tree.read('/followup.txt')?.toString()).toContain('12345'); }); });
{ "end_byte": 4033, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/workspace_spec.ts" }
angular-cli/packages/schematics/angular/utility/json-file.ts_0_2681
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue } from '@angular-devkit/core'; import { Tree } from '@angular-devkit/schematics'; import { Node, ParseError, applyEdits, findNodeAtLocation, getNodeValue, modify, parseTree, printParseErrorCode, } from 'jsonc-parser'; import { getEOL } from './eol'; export type InsertionIndex = (properties: string[]) => number; export type JSONPath = (string | number)[]; /** @private */ export class JSONFile { content: string; private eol: string; constructor( private readonly host: Tree, private readonly path: string, ) { this.content = this.host.readText(this.path); this.eol = getEOL(this.content); } private _jsonAst: Node | undefined; private get JsonAst(): Node | undefined { if (this._jsonAst) { return this._jsonAst; } const errors: ParseError[] = []; this._jsonAst = parseTree(this.content, errors, { allowTrailingComma: true }); if (errors.length) { const { error, offset } = errors[0]; throw new Error( `Failed to parse "${this.path}" as JSON AST Object. ${printParseErrorCode( error, )} at location: ${offset}.`, ); } return this._jsonAst; } get(jsonPath: JSONPath): unknown { const jsonAstNode = this.JsonAst; if (!jsonAstNode) { return undefined; } if (jsonPath.length === 0) { return getNodeValue(jsonAstNode); } const node = findNodeAtLocation(jsonAstNode, jsonPath); return node === undefined ? undefined : getNodeValue(node); } modify( jsonPath: JSONPath, value: JsonValue | undefined, insertInOrder?: InsertionIndex | false, ): void { let getInsertionIndex: InsertionIndex | undefined; if (insertInOrder === undefined) { const property = jsonPath.slice(-1)[0]; getInsertionIndex = (properties) => [...properties, property].sort().findIndex((p) => p === property); } else if (insertInOrder !== false) { getInsertionIndex = insertInOrder; } const edits = modify(this.content, jsonPath, value, { getInsertionIndex, formattingOptions: { eol: this.eol, insertSpaces: true, tabSize: 2, }, }); this.content = applyEdits(this.content, edits); this.host.overwrite(this.path, this.content); this._jsonAst = undefined; } remove(jsonPath: JSONPath): void { if (this.get(jsonPath) !== undefined) { this.modify(jsonPath, undefined); } } }
{ "end_byte": 2681, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/json-file.ts" }
angular-cli/packages/schematics/angular/utility/index.ts_0_660
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // Workspace related rules and types export { type ProjectDefinition, type TargetDefinition, type WorkspaceDefinition, getWorkspace as readWorkspace, updateWorkspace, writeWorkspace, } from './workspace'; export { Builders as AngularBuilder } from './workspace-models'; export * from './standalone'; // Package dependency related rules and types export { DependencyType, ExistingBehavior, InstallBehavior, addDependency } from './dependency';
{ "end_byte": 660, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/index.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils.ts_0_7565
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { Change, InsertChange, NoopChange } from './change'; import { getEOL } from './eol'; /** * Add Import `import { symbolName } from fileName` if the import doesn't exit * already. Assumes fileToEdit can be resolved and accessed. * @param fileToEdit File we want to add import to. * @param symbolName Item to import. * @param fileName Path to the file. * @param isDefault If true, import follows style for importing default exports. * @param alias Alias that the symbol should be inserted under. * @return Change */ export function insertImport( source: ts.SourceFile, fileToEdit: string, symbolName: string, fileName: string, isDefault = false, alias?: string, ): Change { const rootNode = source; const allImports = findNodes(rootNode, ts.isImportDeclaration); const importExpression = alias ? `${symbolName} as ${alias}` : symbolName; // get nodes that map to import statements from the file fileName const relevantImports = allImports.filter((node) => { return ts.isStringLiteralLike(node.moduleSpecifier) && node.moduleSpecifier.text === fileName; }); if (relevantImports.length > 0) { const hasNamespaceImport = relevantImports.some((node) => { return node.importClause?.namedBindings?.kind === ts.SyntaxKind.NamespaceImport; }); // if imports * from fileName, don't add symbolName if (hasNamespaceImport) { return new NoopChange(); } const imports = relevantImports.flatMap((node) => { return node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings) ? node.importClause.namedBindings.elements : []; }); // insert import if it's not there if (!imports.some((node) => (node.propertyName || node.name).text === symbolName)) { const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() || findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart(); return insertAfterLastOccurrence(imports, `, ${importExpression}`, fileToEdit, fallbackPos); } return new NoopChange(); } // no such import declaration exists const useStrict = findNodes(rootNode, ts.isStringLiteral).filter((n) => n.text === 'use strict'); let fallbackPos = 0; if (useStrict.length > 0) { fallbackPos = useStrict[0].end; } const open = isDefault ? '' : '{ '; const close = isDefault ? '' : ' }'; const eol = getEOL(rootNode.getText()); // if there are no imports or 'use strict' statement, insert import at beginning of file const insertAtBeginning = allImports.length === 0 && useStrict.length === 0; const separator = insertAtBeginning ? '' : `;${eol}`; const toInsert = `${separator}import ${open}${importExpression}${close}` + ` from '${fileName}'${insertAtBeginning ? `;${eol}` : ''}`; return insertAfterLastOccurrence( allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral, ); } /** * Find all nodes from the AST in the subtree of node of SyntaxKind kind. * @param node * @param kind * @param max The maximum number of items to return. * @param recursive Continue looking for nodes of kind recursive until end * the last child even when node of kind has been found. * @return all nodes of kind, or [] if none is found */ export function findNodes( node: ts.Node, kind: ts.SyntaxKind, max?: number, recursive?: boolean, ): ts.Node[]; /** * Find all nodes from the AST in the subtree that satisfy a type guard. * @param node * @param guard * @param max The maximum number of items to return. * @param recursive Continue looking for nodes of kind recursive until end * the last child even when node of kind has been found. * @return all nodes that satisfy the type guard, or [] if none is found */ export function findNodes<T extends ts.Node>( node: ts.Node, guard: (node: ts.Node) => node is T, max?: number, recursive?: boolean, ): T[]; export function findNodes<T extends ts.Node>( node: ts.Node, kindOrGuard: ts.SyntaxKind | ((node: ts.Node) => node is T), max = Infinity, recursive = false, ): T[] { if (!node || max == 0) { return []; } const test = typeof kindOrGuard === 'function' ? kindOrGuard : (node: ts.Node): node is T => node.kind === kindOrGuard; const arr: T[] = []; if (test(node)) { arr.push(node); max--; } if (max > 0 && (recursive || !test(node))) { for (const child of node.getChildren()) { findNodes(child, test, max, recursive).forEach((node) => { if (max > 0) { arr.push(node); } max--; }); if (max <= 0) { break; } } } return arr; } /** * Get all the nodes from a source. * @param sourceFile The source file object. * @returns {Array<ts.Node>} An array of all the nodes in the source. */ export function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] { const nodes: ts.Node[] = [sourceFile]; const result: ts.Node[] = []; while (nodes.length > 0) { const node = nodes.shift(); if (node) { result.push(node); if (node.getChildCount(sourceFile) >= 0) { nodes.unshift(...node.getChildren()); } } } return result; } export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.Node | null { if (node.kind === kind && node.getText() === text) { return node; } let foundNode: ts.Node | null = null; ts.forEachChild(node, (childNode) => { foundNode = foundNode || findNode(childNode, kind, text); }); return foundNode; } /** * Helper for sorting nodes. * @return function to sort nodes in increasing order of position in sourceFile */ function nodesByPosition(first: ts.Node, second: ts.Node): number { return first.getStart() - second.getStart(); } /** * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]` * or after the last of occurence of `syntaxKind` if the last occurence is a sub child * of ts.SyntaxKind[nodes[i].kind] and save the changes in file. * * @param nodes insert after the last occurence of nodes * @param toInsert string to insert * @param file file to insert changes into * @param fallbackPos position to insert if toInsert happens to be the first occurence * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after * @return Change instance * @throw Error if toInsert is first occurence but fall back is not set */ export function insertAfterLastOccurrence( nodes: ts.Node[] | ts.NodeArray<ts.Node>, toInsert: string, file: string, fallbackPos: number, syntaxKind?: ts.SyntaxKind, ): Change { let lastItem: ts.Node | undefined; for (const node of nodes) { if (!lastItem || lastItem.getStart() < node.getStart()) { lastItem = node; } } if (syntaxKind && lastItem) { lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop(); } if (!lastItem && fallbackPos == undefined) { throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`); } const lastItemPosition: number = lastItem ? lastItem.getEnd() : fallbackPos; return new InsertChange(file, lastItemPosition, toInsert); }
{ "end_byte": 7565, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils.ts_7567_15754
function _angularImportsFromNode(node: ts.ImportDeclaration): { [name: string]: string } { const ms = node.moduleSpecifier; let modulePath: string; switch (ms.kind) { case ts.SyntaxKind.StringLiteral: modulePath = (ms as ts.StringLiteral).text; break; default: return {}; } if (!modulePath.startsWith('@angular/')) { return {}; } if (node.importClause) { if (node.importClause.name) { // This is of the form `import Name from 'path'`. Ignore. return {}; } else if (node.importClause.namedBindings) { const nb = node.importClause.namedBindings; if (nb.kind == ts.SyntaxKind.NamespaceImport) { // This is of the form `import * as name from 'path'`. Return `name.`. return { [nb.name.text + '.']: modulePath, }; } else { // This is of the form `import {a,b,c} from 'path'` const namedImports = nb; return namedImports.elements .map((is: ts.ImportSpecifier) => (is.propertyName ? is.propertyName.text : is.name.text)) .reduce((acc: { [name: string]: string }, curr: string) => { acc[curr] = modulePath; return acc; }, {}); } } return {}; } else { // This is of the form `import 'path';`. Nothing to do. return {}; } } export function getDecoratorMetadata( source: ts.SourceFile, identifier: string, module: string, ): ts.Node[] { const angularImports = findNodes(source, ts.isImportDeclaration) .map((node) => _angularImportsFromNode(node)) .reduce((acc, current) => { for (const key of Object.keys(current)) { acc[key] = current[key]; } return acc; }, {}); return getSourceNodes(source) .filter((node) => { return ( node.kind == ts.SyntaxKind.Decorator && (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression ); }) .map((node) => (node as ts.Decorator).expression as ts.CallExpression) .filter((expr) => { if (expr.expression.kind == ts.SyntaxKind.Identifier) { const id = expr.expression as ts.Identifier; return id.text == identifier && angularImports[id.text] === module; } else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { // This covers foo.NgModule when importing * as foo. const paExpr = expr.expression as ts.PropertyAccessExpression; // If the left expression is not an identifier, just give up at that point. if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) { return false; } const id = paExpr.name.text; const moduleId = (paExpr.expression as ts.Identifier).text; return id === identifier && angularImports[moduleId + '.'] === module; } return false; }) .filter( (expr) => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression, ) .map((expr) => expr.arguments[0] as ts.ObjectLiteralExpression); } export function getMetadataField( node: ts.ObjectLiteralExpression, metadataField: string, ): ts.ObjectLiteralElement[] { return ( node.properties .filter(ts.isPropertyAssignment) // Filter out every fields that's not "metadataField". Also handles string literals // (but not expressions). .filter(({ name }) => { return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.text === metadataField; }) ); } export function addSymbolToNgModuleMetadata( source: ts.SourceFile, ngModulePath: string, metadataField: string, symbolName: string, importPath: string | null = null, ): Change[] { const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core'); const node = nodes[0]; // Find the decorator declaration. if (!node || !ts.isObjectLiteralExpression(node)) { return []; } // Get all the children property assignment of object literals. const matchingProperties = getMetadataField(node, metadataField); if (matchingProperties.length == 0) { // We haven't found the field in the metadata declaration. Insert a new field. let position: number; let toInsert: string; if (node.properties.length == 0) { position = node.getEnd() - 1; toInsert = `\n ${metadataField}: [\n${tags.indentBy(4)`${symbolName}`}\n ]\n`; } else { const childNode = node.properties[node.properties.length - 1]; position = childNode.getEnd(); // Get the indentation of the last element, if any. const text = childNode.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = `,${matches[0]}${metadataField}: [${matches[1]}` + `${tags.indentBy(matches[2].length + 2)`${symbolName}`}${matches[0]}]`; } else { toInsert = `, ${metadataField}: [${symbolName}]`; } } if (importPath !== null) { return [ new InsertChange(ngModulePath, position, toInsert), insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath), ]; } else { return [new InsertChange(ngModulePath, position, toInsert)]; } } const assignment = matchingProperties[0]; // If it's not an array, nothing we can do really. if ( !ts.isPropertyAssignment(assignment) || !ts.isArrayLiteralExpression(assignment.initializer) ) { return []; } let expression: ts.Expression | ts.ArrayLiteralExpression; const assignmentInit = assignment.initializer; const elements = assignmentInit.elements; if (elements.length) { const symbolsArray = elements.map((node) => tags.oneLine`${node.getText()}`); if (symbolsArray.includes(tags.oneLine`${symbolName}`)) { return []; } expression = elements[elements.length - 1]; } else { expression = assignmentInit; } let toInsert: string; let position = expression.getEnd(); if (ts.isArrayLiteralExpression(expression)) { // We found the field but it's empty. Insert it just before the `]`. position--; toInsert = `\n${tags.indentBy(4)`${symbolName}`}\n `; } else { // Get the indentation of the last element, if any. const text = expression.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = `,${matches[1]}${tags.indentBy(matches[2].length)`${symbolName}`}`; } else { toInsert = `, ${symbolName}`; } } if (importPath !== null) { return [ new InsertChange(ngModulePath, position, toInsert), insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath), ]; } return [new InsertChange(ngModulePath, position, toInsert)]; } /** * Custom function to insert a declaration (component, pipe, directive) * into NgModule declarations. It also imports the component. */ export function addDeclarationToModule( source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string, ): Change[] { return addSymbolToNgModuleMetadata( source, modulePath, 'declarations', classifiedName, importPath, ); } /** * Custom function to insert an NgModule into NgModule imports. It also imports the module. */ export function addImportToModule( source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string, ): Change[] { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); } /** * Custom function to insert a provider into NgModule. It also imports it. */ export function addProviderToModule( source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string, ): Change[] { return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); } /** * Custom function to insert an export into NgModule. It also imports it. */ export function addExportToModule( source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string, ): Change[] { return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath); }
{ "end_byte": 15754, "start_byte": 7567, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils.ts" }
angular-cli/packages/schematics/angular/utility/ast-utils.ts_15756_22222
/** * Custom function to insert an export into NgModule. It also imports it. */ export function addBootstrapToModule( source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string, ): Change[] { return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath); } /** * Determine if an import already exists. */ export function isImported( source: ts.SourceFile, classifiedName: string, importPath: string, ): boolean { const allNodes = getSourceNodes(source); const matchingNodes = allNodes .filter(ts.isImportDeclaration) .filter( (imp) => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath, ) .filter((imp) => { if (!imp.importClause) { return false; } const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter( (n) => n.getText() === classifiedName, ); return nodes.length > 0; }); return matchingNodes.length > 0; } /** * Returns the RouterModule declaration from NgModule metadata, if any. */ export function getRouterModuleDeclaration(source: ts.SourceFile): ts.Expression | undefined { const result = getDecoratorMetadata(source, 'NgModule', '@angular/core'); const node = result[0]; if (!node || !ts.isObjectLiteralExpression(node)) { return undefined; } const matchingProperties = getMetadataField(node, 'imports'); if (!matchingProperties) { return; } const assignment = matchingProperties[0] as ts.PropertyAssignment; if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { return; } const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression; return arrLiteral.elements .filter((el) => el.kind === ts.SyntaxKind.CallExpression) .find((el) => (el as ts.Identifier).getText().startsWith('RouterModule')); } /** * Adds a new route declaration to a router module (i.e. has a RouterModule declaration) */ export function addRouteDeclarationToModule( source: ts.SourceFile, fileToAdd: string, routeLiteral: string, ): Change { const routerModuleExpr = getRouterModuleDeclaration(source); if (!routerModuleExpr) { throw new Error( `Couldn't find a route declaration in ${fileToAdd}.\n` + `Use the '--module' option to specify a different routing module.`, ); } const scopeConfigMethodArgs = (routerModuleExpr as ts.CallExpression).arguments; if (!scopeConfigMethodArgs.length) { const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart()); throw new Error( `The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`, ); } let routesArr: ts.ArrayLiteralExpression | undefined; const routesArg = scopeConfigMethodArgs[0]; // Check if the route declarations array is // an inlined argument of RouterModule or a standalone variable if (ts.isArrayLiteralExpression(routesArg)) { routesArr = routesArg; } else { const routesVarName = routesArg.getText(); let routesVar; if (routesArg.kind === ts.SyntaxKind.Identifier) { routesVar = source.statements.filter(ts.isVariableStatement).find((v) => { return v.declarationList.declarations[0].name.getText() === routesVarName; }); } if (!routesVar) { const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart()); throw new Error( `No route declaration array was found that corresponds ` + `to router module at line ${line} in ${fileToAdd}`, ); } routesArr = findNodes( routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1, )[0] as ts.ArrayLiteralExpression; } const occurrencesCount = routesArr.elements.length; const text = routesArr.getFullText(source); let route: string = routeLiteral; let insertPos = routesArr.elements.pos; if (occurrencesCount > 0) { const lastRouteLiteral = [...routesArr.elements].pop() as ts.Expression; const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) && lastRouteLiteral.properties.some( (n) => ts.isPropertyAssignment(n) && ts.isIdentifier(n.name) && n.name.text === 'path' && ts.isStringLiteral(n.initializer) && n.initializer.text === '**', ); const indentation = text.match(/\r?\n(\r?)\s*/) || []; const routeText = `${indentation[0] || ' '}${routeLiteral}`; // Add the new route before the wildcard route // otherwise we'll always redirect to the wildcard route if (lastRouteIsWildcard) { insertPos = lastRouteLiteral.pos; route = `${routeText},`; } else { insertPos = lastRouteLiteral.end; route = `,${routeText}`; } } return new InsertChange(fileToAdd, insertPos, route); } /** Asserts if the specified node is a named declaration (e.g. class, interface). */ function isNamedNode( node: ts.Node & { name?: ts.Node }, ): node is ts.Node & { name: ts.Identifier } { return !!node.name && ts.isIdentifier(node.name); } /** * Determines if a SourceFile has a top-level declaration whose name matches a specific symbol. * Can be used to avoid conflicts when inserting new imports into a file. * @param sourceFile File in which to search. * @param symbolName Name of the symbol to search for. * @param skipModule Path of the module that the symbol may have been imported from. Used to * avoid false positives where the same symbol we're looking for may have been imported. */ export function hasTopLevelIdentifier( sourceFile: ts.SourceFile, symbolName: string, skipModule: string | null = null, ): boolean { for (const node of sourceFile.statements) { if (isNamedNode(node) && node.name.text === symbolName) { return true; } if ( ts.isVariableStatement(node) && node.declarationList.declarations.some((decl) => { return isNamedNode(decl) && decl.name.text === symbolName; }) ) { return true; } if ( ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier) && node.moduleSpecifier.text !== skipModule && node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings) && node.importClause.namedBindings.elements.some((el) => el.name.text === symbolName) ) { return true; } } return false; }
{ "end_byte": 22222, "start_byte": 15756, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/ast-utils.ts" }
angular-cli/packages/schematics/angular/utility/paths.ts_0_442
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { join, relative } from 'node:path/posix'; export function relativePathToWorkspaceRoot(projectRoot: string | undefined): string { if (!projectRoot) { return '.'; } return relative(join('/', projectRoot), '/') || '.'; }
{ "end_byte": 442, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/paths.ts" }
angular-cli/packages/schematics/angular/utility/find-module.ts_0_4560
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { NormalizedRoot, Path, dirname, join, normalize, relative } from '@angular-devkit/core'; import { DirEntry, Tree } from '@angular-devkit/schematics'; export interface ModuleOptions { module?: string; name: string; flat?: boolean; path?: string; skipImport?: boolean; moduleExt?: string; routingModuleExt?: string; standalone?: boolean; } export const MODULE_EXT = '.module.ts'; export const ROUTING_MODULE_EXT = '-routing.module.ts'; /** * Find the module referred by a set of options passed to the schematics. */ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path | undefined { if (options.standalone || options.skipImport) { return undefined; } const moduleExt = options.moduleExt || MODULE_EXT; const routingModuleExt = options.routingModuleExt || ROUTING_MODULE_EXT; if (!options.module) { const pathToCheck = (options.path || '') + '/' + options.name; return normalize(findModule(host, pathToCheck, moduleExt, routingModuleExt)); } else { const modulePath = normalize(`/${options.path}/${options.module}`); const componentPath = normalize(`/${options.path}/${options.name}`); const moduleBaseName = normalize(modulePath).split('/').pop(); const candidateSet = new Set<Path>([normalize(options.path || '/')]); for (let dir = modulePath; dir != NormalizedRoot; dir = dirname(dir)) { candidateSet.add(dir); } for (let dir = componentPath; dir != NormalizedRoot; dir = dirname(dir)) { candidateSet.add(dir); } const candidatesDirs = [...candidateSet].sort((a, b) => b.length - a.length); for (const c of candidatesDirs) { const candidateFiles = ['', `${moduleBaseName}.ts`, `${moduleBaseName}${moduleExt}`].map( (x) => join(c, x), ); for (const sc of candidateFiles) { if (host.exists(sc)) { return normalize(sc); } } } throw new Error( `Specified module '${options.module}' does not exist.\n` + `Looked in the following directories:\n ${candidatesDirs.join('\n ')}`, ); } } /** * Function to find the "closest" module to a generated file's path. */ export function findModule( host: Tree, generateDir: string, moduleExt = MODULE_EXT, routingModuleExt = ROUTING_MODULE_EXT, ): Path { let dir: DirEntry | null = host.getDir('/' + generateDir); let foundRoutingModule = false; while (dir) { const allMatches = dir.subfiles.filter((p) => p.endsWith(moduleExt)); const filteredMatches = allMatches.filter((p) => !p.endsWith(routingModuleExt)); foundRoutingModule = foundRoutingModule || allMatches.length !== filteredMatches.length; if (filteredMatches.length == 1) { return join(dir.path, filteredMatches[0]); } else if (filteredMatches.length > 1) { throw new Error( `More than one module matches. Use the '--skip-import' option to skip importing ` + 'the component into the closest module or use the module option to specify a module.', ); } dir = dir.parent; } const errorMsg = foundRoutingModule ? 'Could not find a non Routing NgModule.' + `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.` + `\nUse the '--skip-import' option to skip importing in NgModule.` : `Could not find an NgModule. Use the '--skip-import' option to skip importing in NgModule.`; throw new Error(errorMsg); } /** * Build a relative path from one file path to another file path. */ export function buildRelativePath(from: string, to: string): string { from = normalize(from); to = normalize(to); // Convert to arrays. const fromParts = from.split('/'); const toParts = to.split('/'); // Remove file names (preserving destination) fromParts.pop(); const toFileName = toParts.pop(); const relativePath = relative( normalize(fromParts.join('/') || '/'), normalize(toParts.join('/') || '/'), ); let pathPrefix = ''; // Set the path prefix for same dir or child dir, parent dir starts with `..` if (!relativePath) { pathPrefix = '.'; } else if (!relativePath.startsWith('.')) { pathPrefix = `./`; } if (pathPrefix && !pathPrefix.endsWith('/')) { pathPrefix += '/'; } return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName; }
{ "end_byte": 4560, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/find-module.ts" }
angular-cli/packages/schematics/angular/utility/parse-name_spec.ts_0_1349
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { parseName } from './parse-name'; describe('parse-name', () => { it('should handle just the name', () => { const result = parseName('src/app', 'foo'); expect(result.name).toEqual('foo'); expect(result.path).toEqual('/src/app'); }); it('should handle no path', () => { const result = parseName('', 'foo'); expect(result.name).toEqual('foo'); expect(result.path).toEqual('/'); }); it('should handle name has a path (sub-dir)', () => { const result = parseName('src/app', 'bar/foo'); expect(result.name).toEqual('foo'); expect(result.path).toEqual('/src/app/bar'); }); it('should handle name has a higher path', () => { const result = parseName('src/app', '../foo'); expect(result.name).toEqual('foo'); expect(result.path).toEqual('/src'); }); it('should handle name has a higher path above root', () => { expect(() => parseName('src/app', '../../../foo')).toThrow(); }); it('should handle Windows paths', () => { const result = parseName('', 'foo\\bar\\baz'); expect(result.name).toEqual('baz'); expect(result.path).toEqual('/foo/bar'); }); });
{ "end_byte": 1349, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/parse-name_spec.ts" }
angular-cli/packages/schematics/angular/utility/project-targets.ts_0_410
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicsException } from '@angular-devkit/schematics'; export function targetBuildNotFoundError(): SchematicsException { return new SchematicsException(`Project target "build" not found.`); }
{ "end_byte": 410, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/project-targets.ts" }
angular-cli/packages/schematics/angular/utility/test/create-app-module.ts_0_795
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { UnitTestTree } from '@angular-devkit/schematics/testing'; export function createAppModule(tree: UnitTestTree, path?: string): UnitTestTree { tree.create( path || '/src/app/app.module.ts', ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, ); return tree; }
{ "end_byte": 795, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/test/create-app-module.ts" }
angular-cli/packages/schematics/angular/utility/test/get-file-content.ts_0_485
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Tree } from '@angular-devkit/schematics'; export function getFileContent(tree: Tree, path: string): string { const fileEntry = tree.get(path); if (!fileEntry) { throw new Error(`The file (${path}) does not exist.`); } return fileEntry.content.toString(); }
{ "end_byte": 485, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/test/get-file-content.ts" }
angular-cli/packages/schematics/angular/utility/test/index.ts_0_277
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './create-app-module'; export * from './get-file-content';
{ "end_byte": 277, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/test/index.ts" }
angular-cli/packages/schematics/angular/utility/standalone/app_config.ts_0_4085
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Tree } from '@angular-devkit/schematics'; import { dirname, join } from 'path'; import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { getSourceFile } from './util'; /** App config that was resolved to its source node. */ export interface ResolvedAppConfig { /** Tree-relative path of the file containing the app config. */ filePath: string; /** Node defining the app config. */ node: ts.ObjectLiteralExpression; } /** * Resolves the node that defines the app config from a bootstrap call. * @param bootstrapCall Call for which to resolve the config. * @param tree File tree of the project. * @param filePath File path of the bootstrap call. */ export function findAppConfig( bootstrapCall: ts.CallExpression, tree: Tree, filePath: string, ): ResolvedAppConfig | null { if (bootstrapCall.arguments.length > 1) { const config = bootstrapCall.arguments[1]; if (ts.isObjectLiteralExpression(config)) { return { filePath, node: config }; } if (ts.isIdentifier(config)) { return resolveAppConfigFromIdentifier(config, tree, filePath); } } return null; } /** * Resolves the app config from an identifier referring to it. * @param identifier Identifier referring to the app config. * @param tree File tree of the project. * @param bootstapFilePath Path of the bootstrap call. */ function resolveAppConfigFromIdentifier( identifier: ts.Identifier, tree: Tree, bootstapFilePath: string, ): ResolvedAppConfig | null { const sourceFile = identifier.getSourceFile(); for (const node of sourceFile.statements) { // Only look at relative imports. This will break if the app uses a path // mapping to refer to the import, but in order to resolve those, we would // need knowledge about the entire program. if ( !ts.isImportDeclaration(node) || !node.importClause?.namedBindings || !ts.isNamedImports(node.importClause.namedBindings) || !ts.isStringLiteralLike(node.moduleSpecifier) || !node.moduleSpecifier.text.startsWith('.') ) { continue; } for (const specifier of node.importClause.namedBindings.elements) { if (specifier.name.text !== identifier.text) { continue; } // Look for a variable with the imported name in the file. Note that ideally we would use // the type checker to resolve this, but we can't because these utilities are set up to // operate on individual files, not the entire program. const filePath = join(dirname(bootstapFilePath), node.moduleSpecifier.text + '.ts'); const importedSourceFile = getSourceFile(tree, filePath); const resolvedVariable = findAppConfigFromVariableName( importedSourceFile, (specifier.propertyName || specifier.name).text, ); if (resolvedVariable) { return { filePath, node: resolvedVariable }; } } } const variableInSameFile = findAppConfigFromVariableName(sourceFile, identifier.text); return variableInSameFile ? { filePath: bootstapFilePath, node: variableInSameFile } : null; } /** * Finds an app config within the top-level variables of a file. * @param sourceFile File in which to search for the config. * @param variableName Name of the variable containing the config. */ function findAppConfigFromVariableName( sourceFile: ts.SourceFile, variableName: string, ): ts.ObjectLiteralExpression | null { for (const node of sourceFile.statements) { if (ts.isVariableStatement(node)) { for (const decl of node.declarationList.declarations) { if ( ts.isIdentifier(decl.name) && decl.name.text === variableName && decl.initializer && ts.isObjectLiteralExpression(decl.initializer) ) { return decl.initializer; } } } } return null; }
{ "end_byte": 4085, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/app_config.ts" }
angular-cli/packages/schematics/angular/utility/standalone/code_block.ts_0_4111
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, Tree } from '@angular-devkit/schematics'; import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { hasTopLevelIdentifier, insertImport } from '../ast-utils'; import { applyToUpdateRecorder } from '../change'; /** Generated code that hasn't been interpolated yet. */ export interface PendingCode { /** Code that will be inserted. */ expression: string; /** Imports that need to be added to the file in which the code is inserted. */ imports: PendingImports; } /** Map keeping track of imports and aliases under which they're referred to in an expression. */ type PendingImports = Map<string, Map<string, string>>; /** Counter used to generate unique IDs. */ let uniqueIdCounter = 0; /** * Callback invoked by a Rule that produces the code * that needs to be inserted somewhere in the app. */ export type CodeBlockCallback = (block: CodeBlock) => PendingCode; /** * Utility class used to generate blocks of code that * can be inserted by the devkit into a user's app. */ export class CodeBlock { private _imports: PendingImports = new Map<string, Map<string, string>>(); // Note: the methods here are defined as arrow function so that they can be destructured by // consumers without losing their context. This makes the API more concise. /** Function used to tag a code block in order to produce a `PendingCode` object. */ code = (strings: TemplateStringsArray, ...params: unknown[]): PendingCode => { return { expression: strings.map((part, index) => part + (params[index] || '')).join(''), imports: this._imports, }; }; /** * Used inside of a code block to mark external symbols and which module they should be imported * from. When the code is inserted, the required import statements will be produced automatically. * @param symbolName Name of the external symbol. * @param moduleName Module from which the symbol should be imported. */ external = (symbolName: string, moduleName: string): string => { if (!this._imports.has(moduleName)) { this._imports.set(moduleName, new Map()); } const symbolsPerModule = this._imports.get(moduleName) as Map<string, string>; if (!symbolsPerModule.has(symbolName)) { symbolsPerModule.set(symbolName, `@@__SCHEMATIC_PLACEHOLDER_${uniqueIdCounter++}__@@`); } return symbolsPerModule.get(symbolName) as string; }; /** * Produces the necessary rules to transform a `PendingCode` object into valid code. * @param initialCode Code pending transformed. * @param filePath Path of the file in which the code will be inserted. */ static transformPendingCode(initialCode: PendingCode, filePath: string) { const code = { ...initialCode }; const rules: Rule[] = []; code.imports.forEach((symbols, moduleName) => { symbols.forEach((placeholder, symbolName) => { rules.push((tree: Tree) => { const recorder = tree.beginUpdate(filePath); const sourceFile = ts.createSourceFile( filePath, tree.readText(filePath), ts.ScriptTarget.Latest, true, ); // Note that this could still technically clash if there's a top-level symbol called // `${symbolName}_alias`, however this is unlikely. We can revisit this if it becomes // a problem. const alias = hasTopLevelIdentifier(sourceFile, symbolName, moduleName) ? symbolName + '_alias' : undefined; code.expression = code.expression.replace( new RegExp(placeholder, 'g'), alias || symbolName, ); applyToUpdateRecorder(recorder, [ insertImport(sourceFile, filePath, symbolName, moduleName, false, alias), ]); tree.commitUpdate(recorder); }); }); }); return { code, rules }; } }
{ "end_byte": 4111, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/code_block.ts" }
angular-cli/packages/schematics/angular/utility/standalone/rules.ts_0_8408
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { Rule, SchematicsException, Tree, chain } from '@angular-devkit/schematics'; import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { addSymbolToNgModuleMetadata, insertAfterLastOccurrence } from '../ast-utils'; import { InsertChange } from '../change'; import { getAppModulePath, isStandaloneApp } from '../ng-ast-utils'; import { ResolvedAppConfig, findAppConfig } from './app_config'; import { CodeBlock, CodeBlockCallback, PendingCode } from './code_block'; import { applyChangesToFile, findBootstrapApplicationCall, findProvidersLiteral, getMainFilePath, getSourceFile, isMergeAppConfigCall, } from './util'; /** * Adds an import to the root of the project. * @param project Name of the project to which to add the import. * @param callback Function that generates the code block which should be inserted. * @example * * ```ts * import { Rule } from '@angular-devkit/schematics'; * import { addRootImport } from '@schematics/angular/utility'; * * export default function(): Rule { * return addRootImport('default', ({code, external}) => { * return code`${external('MyModule', '@my/module')}.forRoot({})`; * }); * } * ``` */ export function addRootImport(project: string, callback: CodeBlockCallback): Rule { return getRootInsertionRule(project, callback, 'imports', { name: 'importProvidersFrom', module: '@angular/core', }); } /** * Adds a provider to the root of the project. * @param project Name of the project to which to add the import. * @param callback Function that generates the code block which should be inserted. * @example * * ```ts * import { Rule } from '@angular-devkit/schematics'; * import { addRootProvider } from '@schematics/angular/utility'; * * export default function(): Rule { * return addRootProvider('default', ({code, external}) => { * return code`${external('provideLibrary', '@my/library')}({})`; * }); * } * ``` */ export function addRootProvider(project: string, callback: CodeBlockCallback): Rule { return getRootInsertionRule(project, callback, 'providers'); } /** * Creates a rule that inserts code at the root of either a standalone or NgModule-based project. * @param project Name of the project into which to inser tthe code. * @param callback Function that generates the code block which should be inserted. * @param ngModuleField Field of the root NgModule into which the code should be inserted, if the * app is based on NgModule * @param standaloneWrapperFunction Function with which to wrap the code if the app is standalone. */ function getRootInsertionRule( project: string, callback: CodeBlockCallback, ngModuleField: string, standaloneWrapperFunction?: { name: string; module: string }, ): Rule { return async (host) => { const mainFilePath = await getMainFilePath(host, project); const codeBlock = new CodeBlock(); if (isStandaloneApp(host, mainFilePath)) { return (tree) => addProviderToStandaloneBootstrap( tree, callback(codeBlock), mainFilePath, standaloneWrapperFunction, ); } const modulePath = getAppModulePath(host, mainFilePath); const pendingCode = CodeBlock.transformPendingCode(callback(codeBlock), modulePath); return chain([ ...pendingCode.rules, (tree) => { const changes = addSymbolToNgModuleMetadata( getSourceFile(tree, modulePath), modulePath, ngModuleField, pendingCode.code.expression, // Explicitly set the import path to null since we deal with imports here separately. null, ); applyChangesToFile(tree, modulePath, changes); }, ]); }; } /** * Adds a provider to the root of a standalone project. * @param host Tree of the root rule. * @param pendingCode Code that should be inserted. * @param mainFilePath Path to the project's main file. * @param wrapperFunction Optional function with which to wrap the provider. */ function addProviderToStandaloneBootstrap( host: Tree, pendingCode: PendingCode, mainFilePath: string, wrapperFunction?: { name: string; module: string }, ): Rule { const bootstrapCall = findBootstrapApplicationCall(host, mainFilePath); const fileToEdit = findAppConfig(bootstrapCall, host, mainFilePath)?.filePath || mainFilePath; const { code, rules } = CodeBlock.transformPendingCode(pendingCode, fileToEdit); return chain([ ...rules, () => { let wrapped: PendingCode; let additionalRules: Rule[]; if (wrapperFunction) { const block = new CodeBlock(); const result = CodeBlock.transformPendingCode( block.code`${block.external(wrapperFunction.name, wrapperFunction.module)}(${ code.expression })`, fileToEdit, ); wrapped = result.code; additionalRules = result.rules; } else { wrapped = code; additionalRules = []; } return chain([ ...additionalRules, (tree) => insertStandaloneRootProvider(tree, mainFilePath, wrapped.expression), ]); }, ]); } /** * Inserts a string expression into the root of a standalone project. * @param tree File tree used to modify the project. * @param mainFilePath Path to the main file of the project. * @param expression Code expression to be inserted. */ function insertStandaloneRootProvider(tree: Tree, mainFilePath: string, expression: string): void { const bootstrapCall = findBootstrapApplicationCall(tree, mainFilePath); const appConfig = findAppConfig(bootstrapCall, tree, mainFilePath); if (bootstrapCall.arguments.length === 0) { throw new SchematicsException( `Cannot add provider to invalid bootstrapApplication call in ${ bootstrapCall.getSourceFile().fileName }`, ); } if (appConfig) { addProvidersExpressionToAppConfig(tree, appConfig, expression); return; } const newAppConfig = `, {\n${tags.indentBy(2)`providers: [${expression}]`}\n}`; let targetCall: ts.CallExpression; if (bootstrapCall.arguments.length === 1) { targetCall = bootstrapCall; } else if (isMergeAppConfigCall(bootstrapCall.arguments[1])) { targetCall = bootstrapCall.arguments[1]; } else { throw new SchematicsException( `Cannot statically analyze bootstrapApplication call in ${ bootstrapCall.getSourceFile().fileName }`, ); } applyChangesToFile(tree, mainFilePath, [ insertAfterLastOccurrence( targetCall.arguments, newAppConfig, mainFilePath, targetCall.getEnd() - 1, ), ]); } /** * Adds a string expression to an app config object. * @param tree File tree used to modify the project. * @param appConfig Resolved configuration object of the project. * @param expression Code expression to be inserted. */ function addProvidersExpressionToAppConfig( tree: Tree, appConfig: ResolvedAppConfig, expression: string, ): void { const { node, filePath } = appConfig; const configProps = node.properties; const providersLiteral = findProvidersLiteral(node); // If there's a `providers` property, we can add the provider // to it, otherwise we need to declare it ourselves. if (providersLiteral) { applyChangesToFile(tree, filePath, [ insertAfterLastOccurrence( providersLiteral.elements, (providersLiteral.elements.length === 0 ? '' : ', ') + expression, filePath, providersLiteral.getStart() + 1, ), ]); } else { const prop = tags.indentBy(2)`providers: [${expression}]`; let toInsert: string; let insertPosition: number; if (configProps.length === 0) { toInsert = '\n' + prop + '\n'; insertPosition = node.getEnd() - 1; } else { const hasTrailingComma = configProps.hasTrailingComma; toInsert = (hasTrailingComma ? '' : ',') + '\n' + prop; insertPosition = configProps[configProps.length - 1].getEnd() + (hasTrailingComma ? 1 : 0); } applyChangesToFile(tree, filePath, [new InsertChange(filePath, insertPosition, toInsert)]); } }
{ "end_byte": 8408, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/rules.ts" }
angular-cli/packages/schematics/angular/utility/standalone/util.ts_0_5054
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicsException, Tree } from '@angular-devkit/schematics'; import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { Change, applyToUpdateRecorder } from '../change'; import { targetBuildNotFoundError } from '../project-targets'; import { getWorkspace } from '../workspace'; import { Builders } from '../workspace-models'; /** * Finds the main file of a project. * @param tree File tree for the project. * @param projectName Name of the project in which to search. */ export async function getMainFilePath(tree: Tree, projectName: string): Promise<string> { const workspace = await getWorkspace(tree); const project = workspace.projects.get(projectName); const buildTarget = project?.targets.get('build'); if (!buildTarget) { throw targetBuildNotFoundError(); } const options = buildTarget.options as Record<string, string>; return buildTarget.builder === Builders.Application || buildTarget.builder === Builders.BuildApplication ? options.browser : options.main; } /** * Gets a TypeScript source file at a specific path. * @param tree File tree of a project. * @param path Path to the file. */ export function getSourceFile(tree: Tree, path: string): ts.SourceFile { const content = tree.readText(path); const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); return source; } /** Finds the call to `bootstrapApplication` within a file. */ export function findBootstrapApplicationCall(tree: Tree, mainFilePath: string): ts.CallExpression { const sourceFile = getSourceFile(tree, mainFilePath); const localName = findImportLocalName( sourceFile, 'bootstrapApplication', '@angular/platform-browser', ); if (localName) { let result: ts.CallExpression | null = null; sourceFile.forEachChild(function walk(node) { if ( ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === localName ) { result = node; } if (!result) { node.forEachChild(walk); } }); if (result) { return result; } } throw new SchematicsException(`Could not find bootstrapApplication call in ${mainFilePath}`); } /** * Finds the local name of an imported symbol. Could be the symbol name itself or its alias. * @param sourceFile File within which to search for the import. * @param name Actual name of the import, not its local alias. * @param moduleName Name of the module from which the symbol is imported. */ function findImportLocalName( sourceFile: ts.SourceFile, name: string, moduleName: string, ): string | null { for (const node of sourceFile.statements) { // Only look for top-level imports. if ( !ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier) || node.moduleSpecifier.text !== moduleName ) { continue; } // Filter out imports that don't have the right shape. if ( !node.importClause || !node.importClause.namedBindings || !ts.isNamedImports(node.importClause.namedBindings) ) { continue; } // Look through the elements of the declaration for the specific import. for (const element of node.importClause.namedBindings.elements) { if ((element.propertyName || element.name).text === name) { // The local name is always in `name`. return element.name.text; } } } return null; } /** * Applies a set of changes to a file. * @param tree File tree of the project. * @param path Path to the file that is being changed. * @param changes Changes that should be applied to the file. */ export function applyChangesToFile(tree: Tree, path: string, changes: Change[]) { if (changes.length > 0) { const recorder = tree.beginUpdate(path); applyToUpdateRecorder(recorder, changes); tree.commitUpdate(recorder); } } /** Checks whether a node is a call to `mergeApplicationConfig`. */ export function isMergeAppConfigCall(node: ts.Node): node is ts.CallExpression { if (!ts.isCallExpression(node)) { return false; } const localName = findImportLocalName( node.getSourceFile(), 'mergeApplicationConfig', '@angular/core', ); return !!localName && ts.isIdentifier(node.expression) && node.expression.text === localName; } /** Finds the `providers` array literal within an application config. */ export function findProvidersLiteral( config: ts.ObjectLiteralExpression, ): ts.ArrayLiteralExpression | null { for (const prop of config.properties) { if ( ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'providers' && ts.isArrayLiteralExpression(prop.initializer) ) { return prop.initializer; } } return null; }
{ "end_byte": 5054, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/util.ts" }
angular-cli/packages/schematics/angular/utility/standalone/index.ts_0_341
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { addRootImport, addRootProvider } from './rules'; export type { PendingCode, CodeBlockCallback, CodeBlock } from './code_block';
{ "end_byte": 341, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/index.ts" }
angular-cli/packages/schematics/angular/utility/standalone/rules_spec.ts_0_1781
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Rule, SchematicContext, Tree, callRule } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import { join } from 'path'; import { addRootImport, addRootProvider } from './rules'; describe('standalone utilities', () => { const projectName = 'test'; let host: Tree; async function setupProject(standalone = false) { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../../collection.json'), ); host = await schematicRunner.runSchematic('workspace', { name: 'workspace', newProjectRoot: '/', version: '6.0.0', }); host = await schematicRunner.runSchematic( 'application', { name: projectName, standalone, routing: false, }, host, ); } afterEach(() => { // Clear the host so it doesn't leak between tests. host = null as unknown as Tree; }); function stripWhitespace(str: string) { return str.replace(/\s/g, ''); } function assertContains(source: string, targetString: string) { expect(stripWhitespace(source)).toContain(stripWhitespace(targetString)); } function getPathWithinProject(path: string): string { return join('/', projectName, 'src', path); } function readFile(projectPath: string): string { return host.readText(getPathWithinProject(projectPath)); } async function testRule(rule: Rule, tree: Tree): Promise<void> { await callRule(rule, tree, {} as unknown as SchematicContext).toPromise(); }
{ "end_byte": 1781, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/rules_spec.ts" }
angular-cli/packages/schematics/angular/utility/standalone/rules_spec.ts_1785_11343
describe('addRootImport', () => { it('should add a root import to an NgModule-based app', async () => { await setupProject(); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}.forRoot([])`, ), host, ); const content = readFile('app/app.module.ts'); assertContains(content, `import { MyModule } from '@my/module';`); assertContains(content, `imports: [BrowserModule, MyModule.forRoot([])]`); }); it('should add a root import to a standalone app', async () => { await setupProject(true); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('app/app.config.ts'); assertContains(content, `importProvidersFrom`); assertContains(content, `import { MyModule } from '@my/module';`); assertContains(content, `importProvidersFrom(MyModule)`); }); it('should add a root import to a standalone app whose app config does not have a providers array', async () => { await setupProject(true); host.overwrite( getPathWithinProject('app/app.config.ts'), ` import { ApplicationConfig } from '@angular/core'; export const appConfig: ApplicationConfig = {}; `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('app/app.config.ts'); assertContains( content, `import { ApplicationConfig, importProvidersFrom } from '@angular/core';`, ); assertContains(content, `import { MyModule } from '@my/module';`); assertContains(content, `providers: [importProvidersFrom(MyModule)]`); }); it('should add a root import to a standalone app with a config with providers', async () => { await setupProject(true); host.overwrite( getPathWithinProject('app/app.config.ts'), ` import { ApplicationConfig } from '@angular/core'; export const appConfig: ApplicationConfig = { providers: [ {provide: 'foo', useValue: 123} ] }; `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('app/app.config.ts'); assertContains( content, `import { ApplicationConfig, importProvidersFrom } from '@angular/core';`, ); assertContains(content, `import { MyModule } from '@my/module';`); assertContains( content, `providers: [ {provide: 'foo', useValue: 123}, importProvidersFrom(MyModule) ]`, ); }); it( 'should add a root import to a standalone app whose app config does not have have ' + 'a providers array, but has another property', async () => { await setupProject(true); host.overwrite( getPathWithinProject('app/app.config.ts'), ` import { ApplicationConfig } from '@angular/core'; export const appConfig: ApplicationConfig = { otherProp: {}, }; `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('app/app.config.ts'); assertContains( content, `import { ApplicationConfig, importProvidersFrom } from '@angular/core';`, ); assertContains(content, `import { MyModule } from '@my/module';`); assertContains( content, ` export const appConfig: ApplicationConfig = { otherProp: {}, providers: [importProvidersFrom(MyModule)] }; `, ); }, ); it('should add a root import to a standalone app with an inline app config', async () => { await setupProject(true); host.overwrite( getPathWithinProject('main.ts'), ` import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, {}); `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('main.ts'); assertContains(content, `import { importProvidersFrom } from '@angular/core';`); assertContains(content, `import { MyModule } from '@my/module';`); assertContains( content, `bootstrapApplication(AppComponent, { providers: [importProvidersFrom(MyModule)] });`, ); }); it('should add a root import to a standalone app without an app config', async () => { await setupProject(true); host.overwrite( getPathWithinProject('main.ts'), ` import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent); `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('main.ts'); assertContains(content, `import { importProvidersFrom } from '@angular/core';`); assertContains(content, `import { MyModule } from '@my/module';`); assertContains( content, `bootstrapApplication(AppComponent, { providers: [importProvidersFrom(MyModule)] });`, ); }); it('should add a root import to a standalone app with a merged app config', async () => { await setupProject(true); host.overwrite( getPathWithinProject('main.ts'), ` import { mergeApplicationConfig } from '@angular/core'; import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app.component'; bootstrapApplication(AppComponent, mergeApplicationConfig(a, b)); `, ); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); const content = readFile('main.ts'); assertContains( content, `import { mergeApplicationConfig, importProvidersFrom } from '@angular/core';`, ); assertContains(content, `import { MyModule } from '@my/module';`); assertContains( content, `bootstrapApplication(AppComponent, mergeApplicationConfig(a, b, { providers: [importProvidersFrom(MyModule)] }));`, ); }); it('should alias symbols that conflict with existing code', async () => { await setupProject(); await testRule( addRootImport( projectName, ({ code, external }) => code`${external('BrowserModule', '@my/module')}.forRoot([])`, ), host, ); const content = readFile('app/app.module.ts'); assertContains(content, `import { BrowserModule as BrowserModule_alias } from '@my/module';`); assertContains(content, `imports: [BrowserModule, BrowserModule_alias.forRoot([])]`); }); it('should throw an error if the bootstrapApplication code has no arguments', async () => { await setupProject(true); const mainPath = getPathWithinProject('main.ts'); host.overwrite( mainPath, ` import { bootstrapApplication } from '@angular/platform-browser'; bootstrapApplication(); `, ); const promise = testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); // eslint-disable-next-line @typescript-eslint/no-floating-promises await expectAsync(promise).toBeRejectedWithError( `Cannot add provider to invalid bootstrapApplication call in ${mainPath}`, ); }); it('should throw an error if the bootstrapApplication call cannot be analyzed', async () => { await setupProject(true); const mainPath = getPathWithinProject('main.ts'); host.overwrite( mainPath, ` import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from '@external/app-config'; bootstrapApplication(AppComponent, appConfig); `, ); const promise = testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); // eslint-disable-next-line @typescript-eslint/no-floating-promises await expectAsync(promise).toBeRejectedWithError( `Cannot statically analyze bootstrapApplication call in ${mainPath}`, ); });
{ "end_byte": 11343, "start_byte": 1785, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/rules_spec.ts" }
angular-cli/packages/schematics/angular/utility/standalone/rules_spec.ts_11349_14019
it('should throw an error if there is no bootstrapApplication call', async () => { await setupProject(true); host.overwrite(getPathWithinProject('main.ts'), ''); const promise = testRule( addRootImport( projectName, ({ code, external }) => code`${external('MyModule', '@my/module')}`, ), host, ); // eslint-disable-next-line @typescript-eslint/no-floating-promises await expectAsync(promise).toBeRejectedWithError('Bootstrap call not found'); }); }); describe('addRootProvider', () => { it('should add a root provider to an NgModule-based app', async () => { await setupProject(); await testRule( addRootProvider( projectName, ({ code, external }) => code`{ provide: ${external('SOME_TOKEN', '@my/module')}, useValue: 123 }`, ), host, ); const content = readFile('app/app.module.ts'); assertContains(content, `import { SOME_TOKEN } from '@my/module';`); assertContains(content, `providers: [{ provide: SOME_TOKEN, useValue: 123 }]`); }); it('should add a root provider to a standalone app', async () => { await setupProject(true); await testRule( addRootProvider( projectName, ({ code, external }) => code`${external('provideModule', '@my/module')}([])`, ), host, ); const content = readFile('app/app.config.ts'); assertContains(content, `import { provideModule } from '@my/module';`); assertContains( content, `providers: [provideZoneChangeDetection({ eventCoalescing:true }),provideModule([])]`, ); }); it('should add a root provider to a standalone app when providers contain a trailing comma', async () => { await setupProject(true); const configPath = 'app/app.config.ts'; host.overwrite( getPathWithinProject(configPath), ` import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; export const appConfig: ApplicationConfig = { providers: [ provideRouter([]), ] }; `, ); await testRule( addRootProvider( projectName, ({ code, external }) => code`${external('provideModule', '@my/module')}([])`, ), host, ); const content = readFile('app/app.config.ts'); assertContains(content, `import { provideModule } from '@my/module';`); assertContains(content, `providers: [provideRouter([]),provideModule([]),]`); }); }); });
{ "end_byte": 14019, "start_byte": 11349, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/standalone/rules_spec.ts" }
angular-cli/packages/angular_devkit/core/README.md_0_4301
# Core > Shared utilities for Angular DevKit. # Exception # Json ## Schema ### SchemaValidatorResult ``` export interface SchemaValidatorResult { success: boolean; errors?: string[]; } ``` ### SchemaValidator ``` export interface SchemaValidator { (data: any): Observable<SchemaValidatorResult>; } ``` ### SchemaFormatter ``` export interface SchemaFormatter { readonly async: boolean; validate(data: any): boolean | Observable<boolean>; } ``` ### SchemaRegistry ``` export interface SchemaRegistry { compile(schema: Object): Observable<SchemaValidator>; addFormat(name: string, formatter: SchemaFormatter): void; } ``` ### CoreSchemaRegistry `SchemaRegistry` implementation using https://github.com/epoberezkin/ajv. Constructor accepts object containing `SchemaFormatter` that will be added automatically. ``` export class CoreSchemaRegistry implements SchemaRegistry { constructor(formats: { [name: string]: SchemaFormatter} = {}) {} } ``` # Logger # Utils # Virtual FS # Workspaces The `workspaces` namespace provides an API for interacting with the workspace file formats. It provides an abstraction of the underlying storage format of the workspace and provides support for both reading and writing. Currently, the only supported format is the JSON-based format used by the Angular CLI. For this format, the API provides internal change tracking of values which enables fine-grained updates to the underlying storage of the workspace. This allows for the retention of existing formatting and comments. A workspace is defined via the following object model. Definition collection objects are specialized Javascript `Map` objects with an additional `add` method to simplify addition and provide more localized error checking of the newly added values. ```ts export interface WorkspaceDefinition { readonly extensions: Record<string, JsonValue | undefined>; readonly projects: ProjectDefinitionCollection; } export interface ProjectDefinition { readonly extensions: Record<string, JsonValue | undefined>; readonly targets: TargetDefinitionCollection; root: string; prefix?: string; sourceRoot?: string; } export interface TargetDefinition { options?: Record<string, JsonValue | undefined>; configurations?: Record<string, Record<string, JsonValue | undefined> | undefined>; builder: string; } ``` The API is asynchronous and has two main functions to facilitate reading, creation, and modifying a workspace: `readWorkspace` and `writeWorkspace`. ```ts export enum WorkspaceFormat { JSON, } ``` ```ts export function readWorkspace( path: string, host: WorkspaceHost, format?: WorkspaceFormat, ): Promise<{ workspace: WorkspaceDefinition }>; ``` ```ts export function writeWorkspace( workspace: WorkspaceDefinition, host: WorkspaceHost, path?: string, format?: WorkspaceFormat, ): Promise<void>; ``` A `WorkspaceHost` abstracts the underlying data access methods from the functions. It provides methods to read, write, and analyze paths. A utility function is provided to create an instance of a `WorkspaceHost` from the Angular DevKit's virtual filesystem host abstraction. ```ts export interface WorkspaceHost { readFile(path: string): Promise<string>; writeFile(path: string, data: string): Promise<void>; isDirectory(path: string): Promise<boolean>; isFile(path: string): Promise<boolean>; } export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost; ``` ## Usage Example To demonstrate the usage of the API, the following code will show how to add a option property to a build target for an application. ```ts import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { workspaces } from '@angular-devkit/core'; async function demonstrate() { const host = workspaces.createWorkspaceHost(new NodeJsSyncHost()); const { workspace } = await workspaces.readWorkspace('path/to/workspace/directory/', host); const project = workspace.projects.get('my-app'); if (!project) { throw new Error('my-app does not exist'); } const buildTarget = project.targets.get('build'); if (!buildTarget) { throw new Error('build target does not exist'); } buildTarget.options.optimization = true; await workspaces.writeWorkspace(workspace, host); } demonstrate(); ```
{ "end_byte": 4301, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/README.md" }
angular-cli/packages/angular_devkit/core/BUILD.bazel_0_2515
load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license package(default_visibility = ["//visibility:public"]) licenses(["notice"]) # @angular-devkit/core ts_library( name = "core", package_name = "@angular-devkit/core", srcs = glob( include = ["src/**/*.ts"], exclude = [ "src/**/*_spec.ts", ], ), data = glob( include = ["**/*.json"], # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces exclude = [ "node_modules/**", "src/workspace/json/test/**", ], ), module_name = "@angular-devkit/core", module_root = "src/index.d.ts", deps = [ "@npm//@types/node", "@npm//@types/picomatch", "@npm//ajv", "@npm//ajv-formats", "@npm//jsonc-parser", "@npm//picomatch", "@npm//rxjs", "@npm//source-map", # @node_module: typescript:es2015.proxy # @node_module: typescript:es2015.reflect # @node_module: typescript:es2015.symbol.wellknown # @typings: source_map ], ) # @external_begin ts_library( name = "core_test_lib", testonly = True, srcs = glob(["src/**/*_spec.ts"]), data = glob(["src/workspace/json/test/**/*.json"]), deps = [ ":core", "//packages/angular_devkit/core/node", "@npm//rxjs", ], ) jasmine_node_test( name = "core_test", srcs = [":core_test_lib"], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", tags = ["release-package"], deps = [ ":README.md", ":core", ":license", "//packages/angular_devkit/core/node", "//packages/angular_devkit/core/node/testing", ], ) api_golden_test_npm_package( name = "core_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular_cli/goldens/public-api/angular_devkit/core", npm_package = "angular_cli/packages/angular_devkit/core/npm_package", types = ["@npm//@types/node"], ) # @external_end
{ "end_byte": 2515, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/BUILD.bazel" }