diff --git a/jest.config.js b/jest.config.js index 370eef359..a53b4ef09 100644 --- a/jest.config.js +++ b/jest.config.js @@ -26,10 +26,7 @@ module.exports = { 'ts-jest': { tsConfig: './tsconfig.spec.json', stringifyContentPathRegex: '\\.html$', - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], + astTransformers: ['jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer'], }, }, }; diff --git a/libs/ng-lib/src/lib/transfer-state/transfer-state.service.ts b/libs/ng-lib/src/lib/transfer-state/transfer-state.service.ts index 35c4130f5..68449990b 100644 --- a/libs/ng-lib/src/lib/transfer-state/transfer-state.service.ts +++ b/libs/ng-lib/src/lib/transfer-state/transfer-state.service.ts @@ -2,18 +2,7 @@ import { DOCUMENT } from '@angular/common'; import { Inject, Injectable } from '@angular/core'; import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { BehaviorSubject, NEVER, Observable, of } from 'rxjs'; -import { - catchError, - filter, - first, - map, - pluck, - shareReplay, - switchMap, - take, - takeWhile, - tap, -} from 'rxjs/operators'; +import { catchError, filter, first, map, pluck, shareReplay, switchMap, take, takeWhile, tap } from 'rxjs/operators'; import { fetchHttp } from '../utils/fetchHttp'; import { isScullyGenerated, isScullyRunning } from '../utils/isScully'; import { mergePaths } from '../utils/merge-paths'; @@ -77,17 +66,10 @@ export class TransferStateService { shareReplay(1) ); - constructor( - @Inject(DOCUMENT) private document: Document, - private router: Router - ) {} + constructor(@Inject(DOCUMENT) private document: Document, private router: Router) {} startMonitoring() { - if ( - window && - window['ScullyIO-injected'] && - window['ScullyIO-injected'].inlineStateOnly - ) { + if (window && window['ScullyIO-injected'] && window['ScullyIO-injected'].inlineStateOnly) { this.inlineOnly = true; } this.setupEnvForTransferState(); @@ -106,10 +88,7 @@ export class TransferStateService { } else if (isScullyGenerated()) { // On the client AFTER scully rendered it this.initialUrl = window.location.pathname || '__no_NO_no__'; - this.initialUrl = - this.initialUrl !== '/' && this.initialUrl.endsWith('/') - ? this.initialUrl.slice(0, -1) - : this.initialUrl; + this.initialUrl = this.initialUrl !== '/' && this.initialUrl.endsWith('/') ? this.initialUrl.slice(0, -1) : this.initialUrl; /** set the initial state */ this.stateBS.next((window && window[SCULLY_SCRIPT_ID]) || {}); } @@ -150,11 +129,7 @@ export class TransferStateService { * Checks also if there is actually an value in the state. */ stateKeyHasValue(name: string) { - return ( - this.stateBS.value && - this.stateBS.value.hasOwnProperty(name) && - this.stateBS.value[name] != null - ); + return this.stateBS.value && this.stateBS.value.hasOwnProperty(name) && this.stateBS.value[name] != null; } /** @@ -170,9 +145,7 @@ export class TransferStateService { private saveState(newState) { if (isScullyRunning()) { - this.script.textContent = `window['${SCULLY_SCRIPT_ID}']=${SCULLY_STATE_START}${JSON.stringify( - newState - )}${SCULLY_STATE_END}`; + this.script.textContent = `window['${SCULLY_SCRIPT_ID}']=${SCULLY_STATE_START}${JSON.stringify(newState)}${SCULLY_STATE_END}`; } } @@ -201,10 +174,7 @@ export class TransferStateService { * @param name state key * @param originalState an observable which yields the desired data */ - useScullyTransferState( - name: string, - originalState: Observable - ): Observable { + useScullyTransferState(name: string, originalState: Observable): Observable { if (isScullyGenerated()) { return this.getState(name); } @@ -213,8 +183,7 @@ export class TransferStateService { private async fetchTransferState(): Promise { /** helper to read the part before the first slash (ignores leading slash) */ - const base = (url: string) => - url.split('/').filter((part) => part.trim() !== '')[0]; + const base = (url: string) => url.split('/').filter((part) => part.trim() !== '')[0]; /** put this in the next event cycle so the correct route can be read */ await new Promise((r) => setTimeout(r, 0)); /** get the current url */ @@ -231,9 +200,7 @@ export class TransferStateService { /** keep updating till we move to another route */ takeWhile((url) => base(url) === this.currentBaseUrl), // Get the next route's data from the the index or data file - switchMap((url) => - this.inlineOnly ? this.readFromIndex(url) : this.readFromJson(url) - ), + switchMap((url) => (this.inlineOnly ? this.readFromIndex(url) : this.readFromJson(url))), catchError((e) => { // TODO: come up with better error text. /** the developer needs to know, but its not fatal, so just return an empty state */ @@ -259,13 +226,8 @@ export class TransferStateService { } private readFromIndex(url): Promise { - return fetchHttp( - dropPreSlash(mergePaths(url, '/index.html')), - 'text' - ).then((html: string) => { - const newStateStr = html - .split(SCULLY_STATE_START)[1] - .split(SCULLY_STATE_END)[0]; + return fetchHttp(dropPreSlash(mergePaths(url, '/index.html')), 'text').then((html: string) => { + const newStateStr = html.split(SCULLY_STATE_START)[1].split(SCULLY_STATE_END)[0]; return JSON.parse(newStateStr); }); } diff --git a/libs/plugins/base-href-rewrite/src/lib/plugins-base-href-rewrite.ts b/libs/plugins/base-href-rewrite/src/lib/plugins-base-href-rewrite.ts index 7eb7cb639..8873aff0a 100644 --- a/libs/plugins/base-href-rewrite/src/lib/plugins-base-href-rewrite.ts +++ b/libs/plugins/base-href-rewrite/src/lib/plugins-base-href-rewrite.ts @@ -1,35 +1,18 @@ -import { - HandledRoute, - registerPlugin, - setMyConfig, - getMyConfig, - log, - yellow, -} from '@scullyio/scully'; +import { HandledRoute, registerPlugin, setMyConfig, getMyConfig, log, yellow } from '@scullyio/scully'; export const baseHrefRewrite = Symbol('baseHrefRewrite'); -const baseHrefRewritePlugin = async ( - html: string, - route: HandledRoute -): Promise => { +const baseHrefRewritePlugin = async (html: string, route: HandledRoute): Promise => { let { href } = getMyConfig(baseHrefRewritePlugin); /** if there is a predicate and it returns falsy, don't do anything */ - if ( - route.config?.baseHrefPredicate && - !route.config?.baseHrefPredicate(html, route) - ) { + if (route.config?.baseHrefPredicate && !route.config?.baseHrefPredicate(html, route)) { return html; } if (route.config?.baseHref && typeof route.config?.baseHref === 'string') { href = route.config.baseHref; } - log( - `Rewritten 'base href' to ${yellow(href)}, for route: ${yellow( - route.route - )}` - ); + log(`Rewritten 'base href' to ${yellow(href)}, for route: ${yellow(route.route)}`); if (!html.toLowerCase().includes(']/i, ``); diff --git a/libs/plugins/extra/src/lib/plugins-extra.ts b/libs/plugins/extra/src/lib/plugins-extra.ts index 8ecc700bb..6ab1ce53c 100644 --- a/libs/plugins/extra/src/lib/plugins-extra.ts +++ b/libs/plugins/extra/src/lib/plugins-extra.ts @@ -1,9 +1,4 @@ -import { - routeSplit, - registerPlugin, - HandledRoute, - yellow, -} from '@scullyio/scully'; +import { routeSplit, registerPlugin, HandledRoute, yellow } from '@scullyio/scully'; /** * This plugin replaces the parameter with a counter from 0 to the numberOfPages @@ -11,10 +6,7 @@ import { * @param route * @param options */ -export const extraRoutesPlugin = async ( - route, - options -): Promise[]> => { +export const extraRoutesPlugin = async (route, options): Promise[]> => { /** * routeSplit takes the route and returns a object. * The createPath property in there is a function that takes the @@ -24,12 +16,10 @@ export const extraRoutesPlugin = async ( const { createPath } = routeSplit(route); if (options.numberOfPages) { /** we are going to add numberOfPages handledRoutes, with the number as parameter */ - return Array.from({ length: options.numberOfPages }, (_v, k) => k).map( - (n) => ({ - route: createPath(n.toString()), - title: `page number ${n}`, - }) - ); + return Array.from({ length: options.numberOfPages }, (_v, k) => k).map((n) => ({ + route: createPath(n.toString()), + title: `page number ${n}`, + })); } /** just in case */ return []; @@ -39,17 +29,11 @@ const validator = async (options) => { const errors = []; if (options.numberOfPages === undefined) { - errors.push( - `Extraroutes parameter ${yellow( - 'numberOfPages' - )} is missing from the config` - ); + errors.push(`Extraroutes parameter ${yellow('numberOfPages')} is missing from the config`); } if (options.numberOfPages && typeof options.numberOfPages !== 'number') { - errors.push( - `extraroutesPlugin plugin numberOfPages should be a number, not a ${typeof options.numberOfPages}` - ); + errors.push(`extraroutesPlugin plugin numberOfPages should be a number, not a ${typeof options.numberOfPages}`); } return errors; diff --git a/libs/plugins/google-analytics/.eslintrc b/libs/plugins/google-analytics/.eslintrc new file mode 100644 index 000000000..1655d7292 --- /dev/null +++ b/libs/plugins/google-analytics/.eslintrc @@ -0,0 +1 @@ +{ "extends": "../../../.eslintrc", "rules": {}, "ignorePatterns": ["!**/*"] } diff --git a/libs/plugins/google-analytics/README.md b/libs/plugins/google-analytics/README.md new file mode 100644 index 000000000..c377323f4 --- /dev/null +++ b/libs/plugins/google-analytics/README.md @@ -0,0 +1,54 @@ +# plugins-google-analytics + +This library was generated with [Nx](https://nx.dev). + +## Running unit tests + +# Run `ng test plugins-google-analytics` to execute the unit tests via [Jest](https://jestjs.io). + +# Google Analytics + +## Description + +This plugin allows the usage of Google Analytics via Global Site Tag. + +## Type + +Render Plugin + +## Usage + +In the application's scully..config.ts: + +1. Configure the plugin: + +The plugin's configuration receives an object like this `{globalSiteTag: string}` where +the `globalSiteTag` is the `gtag` provided by Google Analytics. + +2. Make a default post render array and add the plugin to it. + +3. Set the default post renders in Scully config. + +e.g. +`./scully..config.ts` + +```typescript +import { setPluginConfig, ScullyConfig, prod } from '@scullyio/scully'; +import { GoogleAnalytics } from '@scullyio/plugins/google-analytics'; + +const defaultPostRenderers = []; + +if (prod) { + setPluginConfig(GoogleAnalytics, { globalSiteTag: 'UA-#########-1' }); + defaultPostRenderers.push(GoogleAnalytics); +} +export const config: ScullyConfig = { + defaultPostRenderers, + routes: { + '/': { + type: 'contentFolder', + postRenderers: [...defaultPostRenderers], + }, + }, +}; +``` diff --git a/libs/plugins/google-analytics/jest.config.js b/libs/plugins/google-analytics/jest.config.js new file mode 100644 index 000000000..e96a25c23 --- /dev/null +++ b/libs/plugins/google-analytics/jest.config.js @@ -0,0 +1,9 @@ +module.exports = { + name: 'plugins-google-analytics', + preset: '../../../jest.config.js', + transform: { + '^.+\\.[tj]sx?$': 'ts-jest', + }, + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'], + coverageDirectory: '../../../coverage/libs/plugins/google-analytics', +}; diff --git a/libs/plugins/google-analytics/package.json b/libs/plugins/google-analytics/package.json new file mode 100644 index 000000000..5e0e95b8b --- /dev/null +++ b/libs/plugins/google-analytics/package.json @@ -0,0 +1,10 @@ +{ + "name": "@scullyio/plugins-google-analytics", + "version": "0.0.1", + "author": "Israel Guzman", + "repository": { + "type": "GIT", + "url": "https://github.com/scullyio/scully/tree/main/libs/plugins/google-analytics" + }, + "license": "MIT" +} diff --git a/libs/plugins/google-analytics/src/index.ts b/libs/plugins/google-analytics/src/index.ts new file mode 100644 index 000000000..0d8dd92b9 --- /dev/null +++ b/libs/plugins/google-analytics/src/index.ts @@ -0,0 +1 @@ +export * from './lib/plugins-google-analytics'; diff --git a/libs/plugins/google-analytics/src/lib/plugins-google-analytics.ts b/libs/plugins/google-analytics/src/lib/plugins-google-analytics.ts new file mode 100644 index 000000000..ad015e3f9 --- /dev/null +++ b/libs/plugins/google-analytics/src/lib/plugins-google-analytics.ts @@ -0,0 +1,27 @@ +import { registerPlugin, getMyConfig } from '@scullyio/scully'; + +export const GoogleAnalytics = 'googleAnalytics'; + +export const googleAnalyticsPlugin = async (html: string): Promise => { + const googleAnalyticsConfig = getMyConfig(googleAnalyticsPlugin); + + if (!googleAnalyticsConfig) { + throw new Error('googleAnalytics plugin missing Global Site Tag'); + } + const siteTag: string = googleAnalyticsConfig['globalSiteTag']; + + const googleAnalyticsScript = ` + + `; + + return html.replace(/<\/head/i, `${googleAnalyticsScript} []; + +registerPlugin('render', GoogleAnalytics, googleAnalyticsPlugin, validator); diff --git a/libs/plugins/google-analytics/tsconfig.json b/libs/plugins/google-analytics/tsconfig.json new file mode 100644 index 000000000..08c7db8c9 --- /dev/null +++ b/libs/plugins/google-analytics/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "types": ["node", "jest"] + }, + "include": ["**/*.ts"] +} diff --git a/libs/plugins/google-analytics/tsconfig.lib.json b/libs/plugins/google-analytics/tsconfig.lib.json new file mode 100644 index 000000000..9c463b51e --- /dev/null +++ b/libs/plugins/google-analytics/tsconfig.lib.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "../../../dist/out-tsc", + "declaration": true, + "rootDir": "./src", + "types": ["node"] + }, + "exclude": ["**/*.spec.ts"], + "include": ["**/*.ts"] +} diff --git a/libs/plugins/google-analytics/tsconfig.spec.json b/libs/plugins/google-analytics/tsconfig.spec.json new file mode 100644 index 000000000..1798b378a --- /dev/null +++ b/libs/plugins/google-analytics/tsconfig.spec.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.spec.js", + "**/*.spec.jsx", + "**/*.d.ts" + ] +} diff --git a/libs/scully-schematics/src/ng-add/index.ts b/libs/scully-schematics/src/ng-add/index.ts index c60cf52b0..fb87317c9 100644 --- a/libs/scully-schematics/src/ng-add/index.ts +++ b/libs/scully-schematics/src/ng-add/index.ts @@ -1,29 +1,11 @@ -import { - chain, - Rule, - SchematicContext, - SchematicsException, - Tree, -} from '@angular-devkit/schematics'; -import { - NodePackageInstallTask, - RunSchematicTask, -} from '@angular-devkit/schematics/tasks'; -import { - createSourceFile, - ScriptTarget, -} from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; -import { - addImportToModule, - insertImport, -} from '@schematics/angular/utility/ast-utils'; +import { chain, Rule, SchematicContext, SchematicsException, Tree } from '@angular-devkit/schematics'; +import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; +import { createSourceFile, ScriptTarget } from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; +import { addImportToModule, insertImport } from '@schematics/angular/utility/ast-utils'; import { InsertChange } from '@schematics/angular/utility/change'; import { getSourceFile, getSrc } from '../utils/utils'; -import { - addPackageToPackageJson, - getPackageVersionFromPackageJson, -} from './package-config'; +import { addPackageToPackageJson, getPackageVersionFromPackageJson } from './package-config'; import { Schema } from './schema'; import { scullyComponentVersion, scullyVersion } from './version-names'; @@ -40,75 +22,41 @@ export default (options: Schema): Rule => { }; let angularJSON = 'angular.json'; const checkAngularVersion = () => (tree: Tree, context: SchematicContext) => { - const ngCoreVersionTag = getPackageVersionFromPackageJson( - tree, - '@angular/core' - ); + const ngCoreVersionTag = getPackageVersionFromPackageJson(tree, '@angular/core'); if (+ngCoreVersionTag.search(/(\^7|~7|\^6|~6|\^5|~5|\^4|~4)/g) === 0) { - console.log( - '==============================================================' - ); - console.log( - '==============================================================' - ); + console.log('=============================================================='); + console.log('=============================================================='); context.logger.error('Scully only work for version 8 or higher'); context.logger.info('Please visit https://scully.io/ for more information'); - console.log( - '==============================================================' - ); - console.log( - '==============================================================' - ); + console.log('=============================================================='); + console.log('=============================================================='); process.exit(0); } }; const addDependencies = () => (tree: Tree, context: SchematicContext) => { addPackageToPackageJson(tree, '@scullyio/scully', `${scullyVersion}`); - const ngCoreVersionTag = getPackageVersionFromPackageJson( - tree, - '@angular/core' - ); + const ngCoreVersionTag = getPackageVersionFromPackageJson(tree, '@angular/core'); if (+ngCoreVersionTag.search(/(\^8|~8)/g) === 0) { context.logger.info('Install ng-lib for Angular v8'); - addPackageToPackageJson( - tree, - '@scullyio/ng-lib-v8', - `${scullyComponentVersion}` - ); + addPackageToPackageJson(tree, '@scullyio/ng-lib-v8', `${scullyComponentVersion}`); } else { context.logger.info('Install ng-lib for Angular v9'); - addPackageToPackageJson( - tree, - '@scullyio/ng-lib', - `${scullyComponentVersion}` - ); + addPackageToPackageJson(tree, '@scullyio/ng-lib', `${scullyComponentVersion}`); } context.logger.info('✅️ Added dependency'); }; -const importScullyModule = (project: string) => ( - tree: Tree, - context: SchematicContext -) => { +const importScullyModule = (project: string) => (tree: Tree, context: SchematicContext) => { try { let mainFilePath; try { mainFilePath = `./${getSrc(tree, project)}/app/app.module.ts`; } catch (e) { angularJSON = 'workspace.json'; - mainFilePath = `./${getSrc( - tree, - project, - angularJSON - )}/app/app.module.ts`; + mainFilePath = `./${getSrc(tree, project, angularJSON)}/app/app.module.ts`; } const recorder = tree.beginUpdate(mainFilePath); const mainFileSource = getSourceFile(tree, mainFilePath); - const importChange = insertImport( - mainFileSource, - mainFilePath, - 'ScullyLibModule', - getDependencyFileName(tree) - ) as InsertChange; + const importChange = insertImport(mainFileSource, mainFilePath, 'ScullyLibModule', getDependencyFileName(tree)) as InsertChange; if (importChange.toAdd) { recorder.insertLeft(importChange.pos, importChange.toAdd); } @@ -118,32 +66,15 @@ const importScullyModule = (project: string) => ( context.logger.error('error into import SculyLib', e); } }; -const addScullyModule = (project: string) => ( - tree: Tree, - context: SchematicContext -) => { - const mainFilePath = `./${getSrc( - tree, - project, - angularJSON - )}/app/app.module.ts`; +const addScullyModule = (project: string) => (tree: Tree, context: SchematicContext) => { + const mainFilePath = `./${getSrc(tree, project, angularJSON)}/app/app.module.ts`; const text = tree.read(mainFilePath); if (text === null) { throw new SchematicsException(`File ${mainFilePath} does not exist.`); } const sourceText = text.toString(); - const source = createSourceFile( - mainFilePath, - sourceText, - ScriptTarget.Latest, - true - ); - const changes = addImportToModule( - source, - mainFilePath, - 'ScullyLibModule', - '@scullyio/ng-lib' - ); + const source = createSourceFile(mainFilePath, sourceText, ScriptTarget.Latest, true); + const changes = addImportToModule(source, mainFilePath, 'ScullyLibModule', '@scullyio/ng-lib'); const recorder = tree.beginUpdate(mainFilePath); for (const change of changes) { if (change instanceof InsertChange) { @@ -153,13 +84,8 @@ const addScullyModule = (project: string) => ( tree.commitUpdate(recorder); return tree; }; -const addPolyfill = (project: string) => ( - tree: Tree, - context: SchematicContext -) => { - let polyfills = tree - .read(`${getSrc(tree, project, angularJSON)}/polyfills.ts`) - .toString(); +const addPolyfill = (project: string) => (tree: Tree, context: SchematicContext) => { + let polyfills = tree.read(`${getSrc(tree, project, angularJSON)}/polyfills.ts`).toString(); if (polyfills.includes('SCULLY IMPORTS')) { context.logger.info('⚠️ Skipping polyfills.ts'); } else { @@ -170,16 +96,10 @@ const addPolyfill = (project: string) => ( */ // tslint:disable-next-line: align import 'zone.js/dist/task-tracking';`; - tree.overwrite( - `${getSrc(tree, project, angularJSON)}/polyfills.ts`, - polyfills - ); + tree.overwrite(`${getSrc(tree, project, angularJSON)}/polyfills.ts`, polyfills); } }; -const runBlogSchematic = (options: Schema) => ( - tree: Tree, - context: SchematicContext -) => { +const runBlogSchematic = (options: Schema) => (tree: Tree, context: SchematicContext) => { const nextRules: Rule[] = []; if (options.blog === true) { nextRules.push((host: Tree, ctx: SchematicContext) => { @@ -188,10 +108,7 @@ const runBlogSchematic = (options: Schema) => ( } return chain(nextRules); }; -const runScullySchematic = (options: Schema) => ( - tree: Tree, - context: SchematicContext -) => { +const runScullySchematic = (options: Schema) => (tree: Tree, context: SchematicContext) => { const nextRules: Rule[] = []; nextRules.push((host: Tree, ctx: SchematicContext) => { const installTaskId = ctx.addTask(new NodePackageInstallTask()); @@ -202,10 +119,7 @@ const runScullySchematic = (options: Schema) => ( const getDependencyFileName = (tree: Tree) => { const defaultDependencyFileName = '@scullyio/ng-lib'; - const ngCoreVersionTag = getPackageVersionFromPackageJson( - tree, - '@angular/core' - ); + const ngCoreVersionTag = getPackageVersionFromPackageJson(tree, '@angular/core'); if (+ngCoreVersionTag.search(/(\^8|~8)/g) === 0) { return `${defaultDependencyFileName}-v8`; } else { diff --git a/libs/scully-schematics/src/scully/index.ts b/libs/scully-schematics/src/scully/index.ts index e93ce251e..6801ccac5 100644 --- a/libs/scully-schematics/src/scully/index.ts +++ b/libs/scully-schematics/src/scully/index.ts @@ -1,33 +1,14 @@ -import { - Rule, - SchematicContext, - Tree, - SchematicsException, - chain, -} from '@angular-devkit/schematics'; -import { - getSrc, - getPackageJson, - overwritePackageJson, - getProject, - checkProjectExist, -} from '../utils/utils'; +import { Rule, SchematicContext, Tree, SchematicsException, chain } from '@angular-devkit/schematics'; +import { getSrc, getPackageJson, overwritePackageJson, getProject, checkProjectExist } from '../utils/utils'; import { Schema } from '../ng-add/schema'; let angularJSON = 'angular.json'; export default (options: any): Rule => { - return chain([ - verifyAngularWorkspace(), - modifyPackageJson(options), - createScullyConfig(options), - ]); + return chain([verifyAngularWorkspace(), modifyPackageJson(options), createScullyConfig(options)]); }; -const verifyAngularWorkspace = () => ( - tree: Tree, - context: SchematicContext -) => { +const verifyAngularWorkspace = () => (tree: Tree, context: SchematicContext) => { let workspaceConfigBuffer; workspaceConfigBuffer = tree.read(angularJSON); if (!workspaceConfigBuffer) { @@ -39,16 +20,12 @@ const verifyAngularWorkspace = () => ( } }; -const modifyPackageJson = (options: Schema) => ( - tree: Tree, - context: SchematicContext -) => { +const modifyPackageJson = (options: Schema) => (tree: Tree, context: SchematicContext) => { let defaultProjectName, projectName; defaultProjectName = getProject(tree, 'defaultProject', angularJSON); projectName = getProject(tree, options.project, angularJSON); - const params = - projectName === defaultProjectName ? '' : ` --projectName=${projectName}`; + const params = projectName === defaultProjectName ? '' : ` --projectName=${projectName}`; const jsonContent = getPackageJson(tree); jsonContent.scripts.scully = 'scully' + params; jsonContent.scripts['scully:serve'] = 'scully serve' + params; @@ -56,25 +33,10 @@ const modifyPackageJson = (options: Schema) => ( context.logger.info('✅️ Update package.json'); }; -const createScullyConfig = (options: Schema) => ( - tree: Tree, - context: SchematicContext -) => { - const scullyConfigFile = `scully.${getProject( - tree, - options.project, - angularJSON - )}.config.ts`; - if ( - !checkProjectExist( - tree, - getProject(tree, options.project, angularJSON), - angularJSON - ) - ) { - throw new SchematicsException( - `There is no ${options.project} project in angular.json` - ); +const createScullyConfig = (options: Schema) => (tree: Tree, context: SchematicContext) => { + const scullyConfigFile = `scully.${getProject(tree, options.project, angularJSON)}.config.ts`; + if (!checkProjectExist(tree, getProject(tree, options.project, angularJSON), angularJSON)) { + throw new SchematicsException(`There is no ${options.project} project in angular.json`); } if (!tree.exists(scullyConfigFile)) { const srcFolder = getSrc(tree, options.project, angularJSON); @@ -90,8 +52,6 @@ export const config: ScullyConfig = { } };` ); - context.logger.info( - `✅️ Created scully configuration file in ${scullyConfigFile}` - ); + context.logger.info(`✅️ Created scully configuration file in ${scullyConfigFile}`); } }; diff --git a/libs/scully/src/lib/renderPlugins/launchedBrowser.ts b/libs/scully/src/lib/renderPlugins/launchedBrowser.ts index 5bf9cb65c..d2df64cdb 100644 --- a/libs/scully/src/lib/renderPlugins/launchedBrowser.ts +++ b/libs/scully/src/lib/renderPlugins/launchedBrowser.ts @@ -1,13 +1,6 @@ import { Browser, launch, LaunchOptions } from 'puppeteer'; import { BehaviorSubject, from, merge, Observable } from 'rxjs'; -import { - filter, - shareReplay, - switchMap, - take, - tap, - throttleTime, -} from 'rxjs/operators'; +import { filter, shareReplay, switchMap, take, tap, throttleTime } from 'rxjs/operators'; import { showBrowser } from '../utils/cli-options'; import { loadConfig, scullyConfig } from '../utils/config'; import { green, log, logError } from '../utils/log'; @@ -56,9 +49,7 @@ export const reLaunch = (reason?: string): Promise => { * Function that creates an observable with the puppeteer browser inside * @param options */ -function obsBrowser( - options: LaunchOptions = scullyConfig.puppeteerLaunchOptions || {} -): Observable { +function obsBrowser(options: LaunchOptions = scullyConfig.puppeteerLaunchOptions || {}): Observable { if (showBrowser) { options.headless = false; } @@ -68,9 +59,7 @@ function obsBrowser( const { SCULLY_PUPPETEER_EXECUTABLE_PATH } = process.env; if (SCULLY_PUPPETEER_EXECUTABLE_PATH) { - log( - `Launching puppeteer with executablePath ${SCULLY_PUPPETEER_EXECUTABLE_PATH}` - ); + log(`Launching puppeteer with executablePath ${SCULLY_PUPPETEER_EXECUTABLE_PATH}`); options.executablePath = SCULLY_PUPPETEER_EXECUTABLE_PATH; options.args = [...options.args, '--disable-dev-shm-usage']; } diff --git a/libs/scully/src/lib/routerPlugins/traverseAppRoutesPlugin.ts b/libs/scully/src/lib/routerPlugins/traverseAppRoutesPlugin.ts index fa22f468e..617d5b02e 100644 --- a/libs/scully/src/lib/routerPlugins/traverseAppRoutesPlugin.ts +++ b/libs/scully/src/lib/routerPlugins/traverseAppRoutesPlugin.ts @@ -6,10 +6,7 @@ import { scullyConfig } from '../utils/config'; import { existFolder } from '../utils/fsFolder'; import { green, log, logError, logWarn, yellow } from '../utils/log'; import { createFolderFor } from '../utils/createFolderFor'; -import { - scullySystem, - registerPlugin, -} from '../pluginManagement/pluginRepository'; +import { scullySystem, registerPlugin } from '../pluginManagement/pluginRepository'; export const traverseAppRoutes = Symbol('traverseAppRoutes'); @@ -27,15 +24,11 @@ const plugin = async (forceScan = scanRoutes): Promise => { /** read from cache when exists and not forced to scan. */ if (forceScan === false && existFolder(routesPath)) { try { - const result = JSON.parse( - readFileSync(routesPath).toString() - ) as string[]; + const result = JSON.parse(readFileSync(routesPath).toString()) as string[]; logWarn(` ---------------------------------- Using stored unhandled routes!. - To discover new routes in the angular app use "${yellow( - 'npm run scully -- --scanRoutes' - )}" + To discover new routes in the angular app use "${yellow('npm run scully -- --scanRoutes')}" ----------------------------------`); /** return de-duplicated set of routes */ return [...new Set([...result, ...extraRoutes]).values()]; @@ -43,8 +36,7 @@ Using stored unhandled routes!. } log('traversing app for routes'); const excludedFiles = - scullyConfig.guessParserOptions && - scullyConfig.guessParserOptions.excludedFiles + scullyConfig.guessParserOptions && scullyConfig.guessParserOptions.excludedFiles ? scullyConfig.guessParserOptions.excludedFiles : []; try { @@ -57,13 +49,9 @@ Using stored unhandled routes!. } if (!existFolder(file)) { logWarn( - `We could not find "${yellow( - file - )}". Using the apps source folder as source. This might lead to unpredictable results` - ); - routes = parseAngularRoutes(appRootFolder, excludedFiles).map( - (r) => r.path + `We could not find "${yellow(file)}". Using the apps source folder as source. This might lead to unpredictable results` ); + routes = parseAngularRoutes(appRootFolder, excludedFiles).map((r) => r.path); } else { routes = parseAngularRoutes(file, excludedFiles).map((r) => r.path); } @@ -78,9 +66,7 @@ Or when there are paths we can not resolve statically. Check the routes in your app, rebuild and retry. ${yellow('(You can inspect the error by passing the --showGuessError flag')} -${green( - 'When there are extraRoutes in your config, we will still try to render those.' -)} +${green('When there are extraRoutes in your config, we will still try to render those.')} `); } @@ -98,12 +84,8 @@ ${green( }; export async function addExtraRoutes(): Promise { - const isPromise = (x: any) => - x && x.then !== undefined && typeof x.then === 'function'; - const extraRoutes: - | string - | (string | Promise)[] - | Promise = scullyConfig.extraRoutes; + const isPromise = (x: any) => x && x.then !== undefined && typeof x.then === 'function'; + const extraRoutes: string | (string | Promise)[] | Promise = scullyConfig.extraRoutes; if (!extraRoutes) { return []; } @@ -128,9 +110,7 @@ export async function addExtraRoutes(): Promise { workList.push(r); }); } else { - logWarn( - `ExtraRoutes must be provided as an string array. Current type: ${typeof extraRoutes}` - ); + logWarn(`ExtraRoutes must be provided as an string array. Current type: ${typeof extraRoutes}`); return []; } diff --git a/libs/scully/src/lib/utils/asyncPool.ts b/libs/scully/src/lib/utils/asyncPool.ts index 08bfeea8f..1142c1c2d 100644 --- a/libs/scully/src/lib/utils/asyncPool.ts +++ b/libs/scully/src/lib/utils/asyncPool.ts @@ -9,11 +9,7 @@ const progressTime = 100; * @param array * @param taskFn */ -export async function asyncPool( - MaxParralellTasks: number, - array: T[], - taskFn: (x: T) => Promise -): Promise { +export async function asyncPool(MaxParralellTasks: number, array: T[], taskFn: (x: T) => Promise): Promise { const ret = []; const executing = []; let logTime = performance.now(); diff --git a/libs/scully/src/lib/utils/cli-options.ts b/libs/scully/src/lib/utils/cli-options.ts index 2c3fcff31..0673a9d16 100644 --- a/libs/scully/src/lib/utils/cli-options.ts +++ b/libs/scully/src/lib/utils/cli-options.ts @@ -42,10 +42,7 @@ export const { .boolean('RSD') .default('RSD', false) .alias('RSD', 'removeStaticDist') - .describe( - 'RSD', - 'Use this flag to remove the Scully outfolder before starting' - ) + .describe('RSD', 'Use this flag to remove the Scully outfolder before starting') /** open browser */ .boolean('o') .default('o', false) @@ -108,10 +105,7 @@ export const { .alias('cf', 'configFile') .alias('cf', 'configFileName') .default('cf', '') - .describe( - 'cf', - 'provide name of the config file to use. if the option --project is also there that takes precedence)' - ) + .describe('cf', 'provide name of the config file to use. if the option --project is also there that takes precedence)') /** don't log info lines to console */ .boolean('nl') .default('nl', false) @@ -132,27 +126,18 @@ export const { .string('bf') .alias('bf', 'baseFilter') .default('bf', '') - .describe( - 'bf', - 'provide a wildcard string separated by ,(comma) to filter the unhandled routes' - ) + .describe('bf', 'provide a wildcard string separated by ,(comma) to filter the unhandled routes') /** filter */ .string('routeFilter') .alias('routeFilter', 'rf') .default('routeFilter', '') - .describe( - 'routeFilter', - 'provide a wildcard string separated by ,(comma) to filter the handled routes' - ) + .describe('routeFilter', 'provide a wildcard string separated by ,(comma) to filter the handled routes') /** server Timout */ .number('st') .default('st', 0) .alias('st', 'serverTimeout') - .describe( - 'st', - 'The time Scully will wait for the server before timeout. in milliseconds' - ) + .describe('st', 'The time Scully will wait for the server before timeout. in milliseconds') /** package json fist */ .boolean('pjf') .default('pjf', false) diff --git a/libs/scully/src/lib/utils/handlers/handleTravesal.ts b/libs/scully/src/lib/utils/handlers/handleTravesal.ts index 6aa9fdffc..42fff6513 100644 --- a/libs/scully/src/lib/utils/handlers/handleTravesal.ts +++ b/libs/scully/src/lib/utils/handlers/handleTravesal.ts @@ -25,9 +25,7 @@ async function plugin({ forceScan } = { forceScan: false }): Promise { unhandledRoutes = [...rawRoutesCache.keys()]; } if (unhandledRoutes.length < 1) { - logWarn( - 'No routes found in application, are you sure you installed the router? Terminating.' - ); + logWarn('No routes found in application, are you sure you installed the router? Terminating.'); process.exit(15); } return unhandledRoutes; diff --git a/libs/scully/src/lib/utils/handlers/renderParallel.ts b/libs/scully/src/lib/utils/handlers/renderParallel.ts index 3d2bcc45d..9e298a70c 100644 --- a/libs/scully/src/lib/utils/handlers/renderParallel.ts +++ b/libs/scully/src/lib/utils/handlers/renderParallel.ts @@ -36,11 +36,7 @@ export async function renderParallel(dataRoutes: any[]): Promise { performanceIds.add('Render'); let renderPool = []; try { - renderPool = await asyncPool( - scullyConfig.maxRenderThreads, - dataRoutes, - routeRender - ); + renderPool = await asyncPool(scullyConfig.maxRenderThreads, dataRoutes, routeRender); } catch (e) { console.log('oops during rendering?', e); } diff --git a/libs/scully/src/lib/utils/log.ts b/libs/scully/src/lib/utils/log.ts index 3dc203897..92028592f 100644 --- a/libs/scully/src/lib/utils/log.ts +++ b/libs/scully/src/lib/utils/log.ts @@ -15,10 +15,7 @@ export const enum LogSeverity { none, } const logFilePath = join(findAngularJsonPath(), 'scully.log'); -const logToFile = (string) => - new Promise((res, rej) => - appendFile(logFilePath, string, (e) => (e ? rej(e) : res())) - ); +const logToFile = (string) => new Promise((res, rej) => appendFile(logFilePath, string, (e) => (e ? rej(e) : res()))); export const log = (...a) => enhancedLog(white, LogSeverity.normal, ...a); export const logError = (...a) => enhancedLog(red, LogSeverity.error, ...a); @@ -66,7 +63,5 @@ export function printProgress(tasks: number, text = 'Tasks left:'): void { // process.stdout.clearLine(); // tslint:disable-next-line: no-unused-expression process.stdout.cursorTo && process.stdout.cursorTo(0); - process.stdout.write( - `${spinToken.next().value} ${orange(text)} ${yellow(tasks)} ` - ); + process.stdout.write(`${spinToken.next().value} ${orange(text)} ${yellow(tasks)} `); } diff --git a/libs/scully/src/lib/utils/startup.ts b/libs/scully/src/lib/utils/startup.ts index 421f0a06b..d9b912345 100644 --- a/libs/scully/src/lib/utils/startup.ts +++ b/libs/scully/src/lib/utils/startup.ts @@ -1,9 +1,5 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ -import { - performance, - PerformanceObserver, - PerformanceObserverCallback, -} from 'perf_hooks'; +import { performance, PerformanceObserver, PerformanceObserverCallback } from 'perf_hooks'; import { watch, ssl } from './cli-options'; import { scullyConfig } from './config'; import { generateAll } from './handlers/defaultAction'; @@ -29,40 +25,24 @@ export const startScully = (url?: string) => { performance.mark('stopDuration'); /** measure all performance checks */ try { - [...performanceIds.values()].forEach((id) => - performance.measure(id, `start${id}`, `stop${id}`) - ); + [...performanceIds.values()].forEach((id) => performance.measure(id, `start${id}`, `stop${id}`)); } catch (e) { console.error(e); } return routes.length; }) .catch(() => 0); - Promise.all([ - numberOfRoutesProm, - durationProm, - ]).then(([numberOfRoutes, durations]) => - resolve({ numberOfRoutes, durations }) - ); - }).then( - ({ - numberOfRoutes, - durations, - }: { - numberOfRoutes: number; - durations: { [key: string]: number }; - }) => { - const duration = durations.Duration; - // tslint:disable-next-line:variable-name - const seconds = duration / 1000; - const singleTime = duration / numberOfRoutes; - const routesProSecond = Math.ceil((1000 / singleTime) * 100) / 100; - // console.table(durations) - reloadAll(); - log(` -Generating took ${yellow(Math.floor(seconds * 100) / 100)} seconds for ${yellow( - numberOfRoutes - )} pages: + Promise.all([numberOfRoutesProm, durationProm]).then(([numberOfRoutes, durations]) => resolve({ numberOfRoutes, durations })); + }).then(({ numberOfRoutes, durations }: { numberOfRoutes: number; durations: { [key: string]: number } }) => { + const duration = durations.Duration; + // tslint:disable-next-line:variable-name + const seconds = duration / 1000; + const singleTime = duration / numberOfRoutes; + const routesProSecond = Math.ceil((1000 / singleTime) * 100) / 100; + // console.table(durations) + reloadAll(); + log(` +Generating took ${yellow(Math.floor(seconds * 100) / 100)} seconds for ${yellow(numberOfRoutes)} pages: That is ${yellow(routesProSecond)} pages per second, or ${yellow(Math.ceil(singleTime))} milliseconds for each page. ${ @@ -76,24 +56,17 @@ Generating took ${yellow(Math.floor(seconds * 100) / 100)} seconds for ${yellow( ${ watch - ? `The server is available on "${yellow( - `http${ssl ? 's' : ''}://${scullyConfig.hostName}:${ - scullyConfig.staticport - }/` - )}" + ? `The server is available on "${yellow(`http${ssl ? 's' : ''}://${scullyConfig.hostName}:${scullyConfig.staticport}/`)}" ${yellow('------------------------------------------------------------')} Press ${green('r')} for re-run Scully, or ${green('q')} for close the servers. ${yellow('------------------------------------------------------------')}` : '' } `); - } - ); + }); }; -function measurePerformance( - resolve: (value?: unknown) => void -): PerformanceObserverCallback { +function measurePerformance(resolve: (value?: unknown) => void): PerformanceObserverCallback { return (list, observer) => { const durations = list.getEntries().reduce( (acc, entry) => ({ diff --git a/libs/scully/src/scully.ts b/libs/scully/src/scully.ts index cd2e24826..7902aab2f 100644 --- a/libs/scully/src/scully.ts +++ b/libs/scully/src/scully.ts @@ -9,13 +9,7 @@ import { join } from 'path'; import './lib/pluginManagement/systemPlugins'; import { startBackgroundServer } from './lib/startBackgroundServer'; import { waitForServerToBeAvailable, ScullyConfig } from './lib/utils'; -import { - ssl, - hostName, - openNavigator, - removeStaticDist, - watch, -} from './lib/utils/cli-options'; +import { ssl, hostName, openNavigator, removeStaticDist, watch } from './lib/utils/cli-options'; import { loadConfig, scullyDefaults } from './lib/utils/config'; import { moveDistAngular } from './lib/utils/fsAngular'; import { httpGetJson } from './lib/utils/httpGetJson'; @@ -29,9 +23,7 @@ import { bootServe, isBuildThere, watchMode } from './lib/watchMode'; require('events').defaultMaxListeners = 100; if (process.argv.includes('version')) { - const { version } = JSON.parse( - readFileSync(join(__dirname, './package.json')).toString() - ); + const { version } = JSON.parse(readFileSync(join(__dirname, './package.json')).toString()); process.exit(0); } @@ -49,18 +41,12 @@ if (process.argv.includes('version')) { } /** do we need to kill something? */ if (process.argv.includes('killServer')) { - await httpGetJson( - `http://${scullyConfig.hostName}:${scullyConfig.appPort}/killMe`, - { - suppressErrors: true, - } - ).catch((e) => e); - await httpGetJson( - `https://${scullyConfig.hostName}:${scullyConfig.appPort}/killMe`, - { - suppressErrors: true, - } - ).catch((e) => e); + await httpGetJson(`http://${scullyConfig.hostName}:${scullyConfig.appPort}/killMe`, { + suppressErrors: true, + }).catch((e) => e); + await httpGetJson(`https://${scullyConfig.hostName}:${scullyConfig.appPort}/killMe`, { + suppressErrors: true, + }).catch((e) => e); logWarn('Sent kill command to server'); process.exit(0); } @@ -78,11 +64,7 @@ if (process.argv.includes('version')) { if (process.argv.includes('serve')) { await bootServe(scullyConfig); if (openNavigator) { - await open( - `http${ssl ? 's' : ''}://${scullyConfig.hostName}:${ - scullyConfig.staticport - }/` - ); + await open(`http${ssl ? 's' : ''}://${scullyConfig.hostName}:${scullyConfig.staticport}/`); } } else { const folder = join(scullyConfig.homeFolder, scullyConfig.distFolder); @@ -111,30 +93,18 @@ You are using "${yellow(scullyConfig.hostUrl)}" as server. } } if (openNavigator) { - await open( - `http${ssl ? 's' : ''}://${scullyConfig.hostName}:${ - scullyConfig.staticport - }/` - ); + await open(`http${ssl ? 's' : ''}://${scullyConfig.hostName}:${scullyConfig.staticport}/`); } if (watch) { - watchMode( - join(scullyConfig.homeFolder, scullyConfig.distFolder) || - join(scullyConfig.homeFolder, './dist/browser') - ); + watchMode(join(scullyConfig.homeFolder, scullyConfig.distFolder) || join(scullyConfig.homeFolder, './dist/browser')); } else { // console.log('servers available'); await startScully(); if (!isTaken && typeof scullyConfig.hostUrl !== 'string') { // kill serve ports - await httpGetJson( - `http${ssl ? 's' : ''}://${scullyConfig.hostName}:${ - scullyConfig.appPort - }/killMe`, - { - suppressErrors: true, - } - ); + await httpGetJson(`http${ssl ? 's' : ''}://${scullyConfig.hostName}:${scullyConfig.appPort}/killMe`, { + suppressErrors: true, + }); } /** done, stop the program */ process.exit(0); diff --git a/nx.json b/nx.json index 18f5a5906..6006c90e2 100644 --- a/nx.json +++ b/nx.json @@ -48,6 +48,9 @@ }, "plugins-logrocket": { "tags": [] + }, + "plugins-google-analytics": { + "tags": [] } } } diff --git a/scully.scully-docs.config.ts b/scully.scully-docs.config.ts index 2cbe5ce63..7aef85e39 100644 --- a/scully.scully-docs.config.ts +++ b/scully.scully-docs.config.ts @@ -1,24 +1,31 @@ -import { - ScullyConfig, - setPluginConfig, - prod, - getPluginConfig, -} from '@scullyio/scully'; +import { ScullyConfig, setPluginConfig, prod } from '@scullyio/scully'; import { DisableAngular } from 'scully-plugin-disable-angular'; import './demos/plugins/docs-link-update'; import { LogRocket } from '@scullyio/plugins/logrocket'; +import { GoogleAnalytics } from '@scullyio/plugins/google-analytics'; setPluginConfig('md', { enableSyntaxHighlighting: true }); const defaultPostRenderers = [DisableAngular]; if (prod) { + /* + * Config for production + * */ setPluginConfig(LogRocket, { app: 'herodevs', id: 'scully' }); defaultPostRenderers.push(LogRocket); + + setPluginConfig(GoogleAnalytics, { globalSiteTag: 'UA-171495765-1' }); + defaultPostRenderers.push(GoogleAnalytics); } else { - // This is for check the plugin with the test + /* + * Config for test + */ setPluginConfig(LogRocket, { app: 'test', id: 'test' }); defaultPostRenderers.push(LogRocket); + + setPluginConfig(GoogleAnalytics, { globalSiteTag: 'test' }); + defaultPostRenderers.push(GoogleAnalytics); } export const config: ScullyConfig = { diff --git a/tests/jest/src/__tests__/__snapshots__/docsThere.spec.ts.snap b/tests/jest/src/__tests__/__snapshots__/docsThere.spec.ts.snap index 996c620c3..68210d68f 100644 --- a/tests/jest/src/__tests__/__snapshots__/docsThere.spec.ts.snap +++ b/tests/jest/src/__tests__/__snapshots__/docsThere.spec.ts.snap @@ -64,6 +64,16 @@ exports[`docsSite should have content for all markdown files check html for mark + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + window.LogRocket && window.LogRocket.init('test/test'); + + { - if (error) { - console.error(`exec error: ${error}`); - return; - } - console.log(`Package ${_package} v:${stdout}`); + exec(`npm publish --access publish --prefix ${_path}${_package}`, (_error, _stdout, _stderr) => { + if (error) { + console.error(`exec error: ${error}`); + return; } - ); + console.log(`Package ${_package} v:${stdout}`); + }); } ); }); diff --git a/tsconfig.json b/tsconfig.json index 3b07d7879..27ec02d50 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,14 +19,11 @@ "@scullyio/ng-lib": ["dist/libs/ng-lib"], "@scullyio/plugins/extra": ["libs/plugins/extra/src/index.ts"], "@scullyio/plugins/from-data": ["libs/plugins/from-data/src/index.ts"], - "@scullyio/plugins/base-href-rewrite": [ - "libs/plugins/base-href-rewrite/src/index.ts" - ], + "@scullyio/plugins/base-href-rewrite": ["libs/plugins/base-href-rewrite/src/index.ts"], "@scullyio/plugins/demo-lib": ["libs/plugins/demo-lib/src/index.ts"], - "@scul lyio/plugins/scully-plugin-flash-prevention": [ - "dist/libs/plugins/scully-plugin-flash-prevention" - ], - "@scullyio/plugins/logrocket": ["libs/plugins/logrocket/src/index.ts"] + "@scul lyio/plugins/scully-plugin-flash-prevention": ["dist/libs/plugins/scully-plugin-flash-prevention"], + "@scullyio/plugins/logrocket": ["libs/plugins/logrocket/src/index.ts"], + "@scullyio/plugins/google-analytics": ["libs/plugins/google-analytics/src/index.ts"] } }, "angularCompilerOptions": { diff --git a/workspace.json b/workspace.json index bf5ff1979..dce83a2d4 100644 --- a/workspace.json +++ b/workspace.json @@ -487,6 +487,46 @@ } } } + }, + "plugins-google-analytics": { + "root": "libs/plugins/google-analytics", + "sourceRoot": "libs/plugins/google-analytics/src", + "projectType": "library", + "schematics": {}, + "architect": { + "lint": { + "builder": "@nrwl/linter:lint", + "options": { + "linter": "eslint", + "tsConfig": [ + "libs/plugins/google-analytics/tsconfig.lib.json", + "libs/plugins/google-analytics/tsconfig.spec.json" + ], + "exclude": [ + "**/node_modules/**", + "!libs/plugins/google-analytics/**/*" + ] + } + }, + "test": { + "builder": "@nrwl/jest:jest", + "options": { + "jestConfig": "libs/plugins/google-analytics/jest.config.js", + "tsConfig": "libs/plugins/google-analytics/tsconfig.spec.json", + "passWithNoTests": true + } + }, + "build": { + "builder": "@nrwl/node:package", + "options": { + "outputPath": "dist/libs/plugins/google-analytics", + "tsConfig": "libs/plugins/google-analytics/tsconfig.lib.json", + "packageJson": "libs/plugins/google-analytics/package.json", + "main": "libs/plugins/google-analytics/src/index.ts", + "assets": ["libs/plugins/google-analytics/*.md"] + } + } + } } }, "cli": {