Skip to content

Commit

Permalink
cleanup build.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
robertIsaac committed Aug 29, 2023
1 parent ca4665b commit 1cb5412
Showing 1 changed file with 5 additions and 82 deletions.
87 changes: 5 additions & 82 deletions tools/build.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import { spawn } from 'cross-spawn';
import { copy, readFile, writeFile } from 'fs-extra';
import { prettySize } from 'pretty-size';
import { file as gzipSizeFile } from 'gzip-size';
import { join } from 'path';

// TODO infer these from the package.json
const MODULES = [
'core', 'app', 'app-check', 'auth-guard', 'compat', 'analytics', 'auth', 'database', 'firestore', 'functions',
'remote-config', 'storage', 'messaging', 'performance', 'compat/analytics',
'compat/auth-guard', 'compat/auth', 'compat/database', 'compat/firestore',
'compat/functions', 'compat/remote-config', 'compat/storage', 'compat/messaging',
'compat/performance', 'firestore/lite',
];
const LAZY_MODULES = ['compat/analytics', 'compat/auth', 'compat/functions', 'compat/messaging', 'compat/remote-config'];
const UMD_NAMES = MODULES.map(m => m === 'core' ? 'angular-fire' : `angular-fire-${m.replace('/', '-')}`);
const ENTRY_NAMES = MODULES.map(m => m === 'core' ? '@angular/fire' : `@angular/fire/${m}`);
import { spawn } from 'cross-spawn';
import { copy, writeFile } from 'fs-extra';

interface OverrideOptions {
exportName?: string;
Expand All @@ -32,10 +18,11 @@ function zoneWrapExports() {
overrides: Record<string, OverrideOptions | null> = {}
) => {
const imported = await import(path);
const toBeExported: Array<[string, string, boolean]> = exports.
const toBeExported: [string, string, boolean][] = exports.
filter(it => !it.startsWith('_') && overrides[it] !== null && overrides[it]?.override !== true).
map(importName => {
const zoneWrap = typeof imported[importName] === 'function' &&
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
(overrides[importName]?.zoneWrap ?? importName[0] !== importName[0].toUpperCase());
const exportName = overrides[importName]?.exportName ?? importName;
return [importName, exportName, zoneWrap];
Expand Down Expand Up @@ -134,33 +121,6 @@ ${exportedZoneWrappedFns}
]);
}

function webpackFirestoreProtos() {
const path = dest('firestore-protos.js');
console.log({ path })
return writeFile(dest('firestore-protos.js'), `/**
* @deprecated No longer needed since Firebase JS SDK 9.6.3
*/
export {};`);
}

function proxyPolyfillCompat() {
const defaultObject = {
'compat/analytics': ["app", "logEvent", "setCurrentScreen", "setUserId", "setUserProperties", "setAnalyticsCollectionEnabled"],
'compat/auth': ["name", "config", "emulatorConfig", "app", "applyActionCode", "checkActionCode", "confirmPasswordReset", "createUserWithEmailAndPassword", "currentUser", "fetchSignInMethodsForEmail", "isSignInWithEmailLink", "getRedirectResult", "languageCode", "settings", "onAuthStateChanged", "onIdTokenChanged", "sendSignInLinkToEmail", "sendPasswordResetEmail", "setPersistence", "signInAndRetrieveDataWithCredential", "signInAnonymously", "signInWithCredential", "signInWithCustomToken", "signInWithEmailAndPassword", "signInWithPhoneNumber", "signInWithEmailLink", "signInWithPopup", "signInWithRedirect", "signOut", "tenantId", "updateCurrentUser", "useDeviceLanguage", "useEmulator", "verifyPasswordResetCode"],
'compat/functions': ["useEmulator", "useFunctionsEmulator", "httpsCallable"],
'compat/messaging': ["deleteToken", "getToken", "onMessage", "onBackgroundMessage"],
'compat/performance': ["app", "trace", "instrumentationEnabled", "dataCollectionEnabled"],
'compat/remote-config': ["app", "settings", "defaultConfig", "fetchTimeMillis", "lastFetchStatus", "activate", "ensureInitialized", "fetch", "fetchAndActivate", "getAll", "getBoolean", "getNumber", "getString", "getValue", "setLogLevel"],
};
return Promise.all(Object.keys(defaultObject).map(module =>
writeFile(join(process.cwd(), 'src', `${module}/base.ts`), `// DO NOT MODIFY, this file is autogenerated by tools/build.ts
// Export a null object with the same keys as firebase/${module}, so Proxy can work with proxy-polyfill in Internet Explorer
export const proxyPolyfillCompat = {
${defaultObject[module].map(it => ` ${it}: null,`).join('\n')}
};\n`)
));
}

const src = (...args: string[]) => join(process.cwd(), 'src', ...args);
const dest = (...args: string[]) => join(process.cwd(), 'dist', '@angular/fire', ...args);
const destPacakges = (...args: string[]) => join(process.cwd(), 'dist/packages-dist', ...args);
Expand All @@ -169,6 +129,7 @@ const rootPackage = import(join(process.cwd(), 'package.json'));

async function replacePackageCoreVersion() {
const root = await rootPackage;
// eslint-disable-next-line @typescript-eslint/no-var-requires
const replace = require('replace-in-file');
const files = destPacakges('package.json');
return replace({
Expand Down Expand Up @@ -215,39 +176,7 @@ async function compileSchematics() {
]);
}

async function measure(module: string) {
const path = dest('bundles', `${module}.umd.js`);
const file = await readFile(path);
const size = prettySize(file.byteLength, true);
const gzip = prettySize(await gzipSizeFile(path), true);
return { size, gzip };
}

async function fixImportForLazyModules() {
await Promise.all(LAZY_MODULES.map(async module => {
const packageJson = JSON.parse((await readFile(dest(module, 'package.json'))).toString());
const entries = Array.from(new Set(Object.values(packageJson).filter(v => typeof v === 'string' && v.endsWith('.js')))) as string[];
// TODO don't hardcode esm2015 here, perhaps we should scan all the entry directories
// e.g, if ng-packagr starts building other non-flattened entries we'll lose the dynamic import
// TODO fix in Windows
entries.push(`../${module.includes('/') ? '../' : ''}esm2015/${module}/public_api.js`);
await Promise.all(entries.map(async path => {
const source = (await readFile(dest(module, path))).toString();
let newSource: string;
if (path.endsWith('.umd.js')) {
// in the UMD for lazy modules replace the dyanamic import
newSource = source.replace(`import('firebase/${module}')`, 'rxjs.of(undefined)');
} else {
// in everything else get rid of the global side-effect import
newSource = source.replace(new RegExp(`^import 'firebase/${module}'.+$`, 'gm'), '');
}
await writeFile(dest(module, path), newSource);
}));
}));
}

async function buildLibrary() {
// await proxyPolyfillCompat();
await zoneWrapExports();
await spawnPromise('npx', ['ng', 'build']);
await Promise.all([
Expand All @@ -256,15 +185,9 @@ async function buildLibrary() {
copy(join(process.cwd(), 'docs'), dest('docs')),
compileSchematics(),
replacePackageCoreVersion(),
// fixImportForLazyModules(),
// webpackFirestoreProtos(),
]);
}

function measureLibrary() {
return Promise.all(UMD_NAMES.map(measure));
}

buildLibrary().catch(err => {
console.error(err);
process.exit(1);
Expand Down

0 comments on commit 1cb5412

Please sign in to comment.