@nu-art/build-and-install 0.204.67 → 0.204.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/build-and-install.js +11 -26
  2. package/core/package/generate.js +5 -3
  3. package/core/params/params.d.ts +3 -2
  4. package/core/params/params.js +16 -4
  5. package/defaults/consts.d.ts +11 -23
  6. package/defaults/consts.js +7 -7
  7. package/package.json +1 -1
  8. package/phases/phases.js +7 -3
  9. package/screen/ProjectScreen.js +0 -1
  10. package/v2/phase/consts.d.ts +53 -0
  11. package/v2/phase/consts.js +146 -0
  12. package/v2/phase/index.d.ts +2 -0
  13. package/v2/phase/index.js +18 -0
  14. package/v2/phase/types.d.ts +9 -0
  15. package/v2/phase/types.js +2 -0
  16. package/v2/phase-runner/PhaseRunner.d.ts +69 -13
  17. package/v2/phase-runner/PhaseRunner.js +392 -32
  18. package/v2/phase-runner/PhaseRunnerDispatcher.d.ts +25 -0
  19. package/v2/phase-runner/PhaseRunnerDispatcher.js +26 -0
  20. package/v2/phase-runner/RunnerParams.d.ts +12 -0
  21. package/v2/phase-runner/RunnerParams.js +9 -0
  22. package/v2/phase-runner/consts.d.ts +7 -0
  23. package/v2/phase-runner/consts.js +9 -0
  24. package/v2/phase-runner/types.d.ts +6 -9
  25. package/v2/phase-runner/types.js +4 -0
  26. package/v2/project/types.d.ts +8 -0
  27. package/v2/project/types.js +2 -0
  28. package/v2/screens/list-screen.d.ts +47 -0
  29. package/v2/screens/list-screen.js +196 -0
  30. package/v2/unit/core/BaseUnit.d.ts +18 -7
  31. package/v2/unit/core/BaseUnit.js +35 -10
  32. package/v2/unit/core/Unit_Python.d.ts +18 -2
  33. package/v2/unit/core/Unit_Python.js +30 -1
  34. package/v2/unit/core/Unit_Typescript.d.ts +15 -13
  35. package/v2/unit/core/Unit_Typescript.js +40 -36
  36. package/v2/unit/core/Unit_TypescriptLib.d.ts +27 -3
  37. package/v2/unit/core/Unit_TypescriptLib.js +98 -4
  38. package/v2/unit/core/Unit_TypescriptProject.d.ts +11 -2
  39. package/v2/unit/core/Unit_TypescriptProject.js +29 -0
  40. package/v2/unit/core/index.d.ts +2 -1
  41. package/v2/unit/core/index.js +2 -1
  42. package/v2/unit/firebase-units/Unit_FirebaseFunctionsApp.d.ts +40 -0
  43. package/v2/unit/firebase-units/Unit_FirebaseFunctionsApp.js +312 -0
  44. package/v2/unit/firebase-units/Unit_FirebaseHostingApp.d.ts +32 -0
  45. package/v2/unit/firebase-units/Unit_FirebaseHostingApp.js +159 -0
  46. package/v2/unit/firebase-units/index.d.ts +2 -0
  47. package/v2/unit/firebase-units/index.js +18 -0
  48. package/v2/unit/thunderstorm.d.ts +291 -0
  49. package/v2/unit/thunderstorm.js +199 -0
  50. package/v2/unit/types.d.ts +7 -0
  51. package/v2/unit/types.js +2 -0
  52. package/v2/BasePackage.d.ts +0 -4
  53. package/v2/BasePackage.js +0 -9
  54. package/v2/ProjectManagerV2.d.ts +0 -8
  55. package/v2/ProjectManagerV2.js +0 -23
  56. package/v2/test/test.d.ts +0 -14
  57. package/v2/test/test.js +0 -85
  58. package/v2/unit/core/types.d.ts +0 -13
  59. package/v2/unit/core/types.js +0 -23
@@ -27,13 +27,34 @@ exports.Unit_TypescriptLib = void 0;
27
27
  const nvm_1 = require("@nu-art/commando/cli/nvm");
28
28
  const Unit_Typescript_1 = require("./Unit_Typescript");
29
29
  const fs = __importStar(require("fs"));
30
+ const fs_1 = require("fs");
30
31
  const basic_1 = require("@nu-art/commando/cli/basic");
31
32
  const ts_common_1 = require("@nu-art/ts-common");
32
- const fs_1 = require("fs");
33
+ const RunnerParams_1 = require("../../phase-runner/RunnerParams");
34
+ const cli_1 = require("@nu-art/commando/core/cli");
35
+ const consts_1 = require("../../../core/consts");
36
+ const params_1 = require("../../../core/params/params");
37
+ const extensionsToLint = ['.ts', '.tsx'];
38
+ const assetExtensions = [
39
+ 'json',
40
+ 'scss',
41
+ 'svg',
42
+ 'png',
43
+ 'jpg',
44
+ 'jpeg',
45
+ 'rules',
46
+ '_ts'
47
+ ];
33
48
  class Unit_TypescriptLib extends Unit_Typescript_1.Unit_Typescript {
49
+ async init(setInitialized = true) {
50
+ await super.init(false);
51
+ this.runtime.pathTo.output = this.runtime.pathTo.pkg + `/${this.config.output}`;
52
+ if (setInitialized)
53
+ this.setStatus('Initialized');
54
+ }
34
55
  //######################### Internal Logic #########################
35
56
  async resolveTSConfig() {
36
- const pathToUnitTSConfig = `${this.config.pathToPackage}/src/main/tsconfig.json`;
57
+ const pathToUnitTSConfig = `${this.runtime.pathTo.pkg}/src/main/tsconfig.json`;
37
58
  // const pathToProjectTSConfig = '';
38
59
  //If set to use a custom ts config
39
60
  if (this.config.customTSConfig) {
@@ -43,7 +64,7 @@ class Unit_TypescriptLib extends Unit_Typescript_1.Unit_Typescript {
43
64
  return;
44
65
  }
45
66
  //Copy project ts config file into the unit main folder
46
- const pathToProjectConfig = this.getRunnerParam('configPath');
67
+ const pathToProjectConfig = this.getRunnerParam(RunnerParams_1.RunnerParamKey_ConfigPath);
47
68
  if (!pathToProjectConfig)
48
69
  throw new ts_common_1.BadImplementationException('Could not get config path from runner params');
49
70
  //Make sure a project ts config file exists
@@ -53,17 +74,90 @@ class Unit_TypescriptLib extends Unit_Typescript_1.Unit_Typescript {
53
74
  //Copy the file into the unit
54
75
  await fs_1.promises.copyFile(pathToProjectTSConfig, pathToUnitTSConfig);
55
76
  }
77
+ async clearOutputDir() {
78
+ if (!params_1.RuntimeParams.clean)
79
+ return;
80
+ //Return if output dir doesn't exist
81
+ if (!fs.existsSync(this.runtime.pathTo.output))
82
+ return;
83
+ await fs_1.promises.rm(this.runtime.pathTo.output, { recursive: true, force: true });
84
+ await fs_1.promises.mkdir(this.runtime.pathTo.output, { recursive: true });
85
+ }
86
+ async compileImpl() {
87
+ const pathToCompile = `${this.runtime.pathTo.pkg}/src/main`;
88
+ const pathToTSConfig = `${pathToCompile}/tsconfig.json`;
89
+ await nvm_1.NVM
90
+ .createCommando(basic_1.Cli_Basic)
91
+ .setUID(this.config.key)
92
+ .cd(this.runtime.pathTo.pkg)
93
+ .append(`tsc -p "${pathToTSConfig}" --rootDir "${pathToCompile}" --outDir "${this.runtime.pathTo.output}"`)
94
+ .execute();
95
+ }
96
+ async copyAssetsToOutput() {
97
+ const command = `find . \\( -name ${assetExtensions.map(suffix => `'*.${suffix}'`).join(' -o -name ')} \\) | cpio -pdm "${this.runtime.pathTo.output}" > /dev/null`;
98
+ await cli_1.Commando
99
+ .create(basic_1.Cli_Basic)
100
+ .cd(`${this.runtime.pathTo.pkg}/src/main`)
101
+ .setStdErrorValidator(stderr => {
102
+ return !stderr.match(/\d+\sblock/);
103
+ })
104
+ .append(command)
105
+ .execute();
106
+ }
107
+ async copyPackageJSONToOutput() {
108
+ const targetPath = `${this.runtime.pathTo.output}/${consts_1.CONST_PackageJSON}`;
109
+ const fileContent = JSON.stringify(this.packageJson.dist, null, 2);
110
+ await fs_1.promises.writeFile(targetPath, fileContent, { encoding: 'utf-8' });
111
+ }
56
112
  //######################### Phase Implementations #########################
57
113
  async preCompile() {
58
114
  if (!fs.existsSync(`${this.config.pathToPackage}/prebuild.sh`))
59
115
  return;
116
+ this.setStatus('Pre-Compile');
60
117
  await nvm_1.NVM.createCommando(basic_1.Cli_Basic)
61
- .cd(this.config.pathToPackage)
118
+ .cd(this.runtime.pathTo.pkg)
62
119
  .append('bash prebuild.sh')
63
120
  .execute();
64
121
  }
65
122
  async compile() {
123
+ this.setStatus('Compile');
66
124
  await this.resolveTSConfig();
125
+ await this.clearOutputDir();
126
+ await this.compileImpl();
127
+ await this.copyAssetsToOutput();
128
+ await this.copyPackageJSONToOutput();
129
+ this.setStatus('Compiled');
130
+ }
131
+ async purge() {
132
+ await fs_1.promises.rm(this.runtime.pathTo.output, { recursive: true, force: true });
133
+ }
134
+ async printDependencyTree() {
135
+ const CONST_RunningRoot = process.cwd();
136
+ this.logDebug(`Generating Dependency Tree - ${this.config.label}`);
137
+ await nvm_1.NVM.createCommando(basic_1.Cli_Basic)
138
+ .cd(this.runtime.pathTo.pkg)
139
+ .append(`mkdir -p ${CONST_RunningRoot}/.trash/dependencies`)
140
+ .append(`pnpm list --depth 1000 > "${CONST_RunningRoot}/.trash/dependencies/${this.config.key}.txt"`)
141
+ .execute();
142
+ }
143
+ async checkCyclicImports() {
144
+ this.logDebug(`Checking Cyclic Imports - ${this.config.label}`);
145
+ await nvm_1.NVM.createCommando(basic_1.Cli_Basic)
146
+ .cd(this.runtime.pathTo.pkg)
147
+ .setStdErrorValidator(stderr => {
148
+ return !stderr.includes('Finding files') && !stderr.includes('Image created');
149
+ })
150
+ .append(`npx madge --no-spinner --image "./imports-${this.config.key}.svg" --circular ${this.runtime.pathTo.output}`)
151
+ .append('echo $?')
152
+ .execute();
153
+ }
154
+ async lint() {
155
+ const pathToProjectESLint = RunnerParams_1.MemKey_RunnerParams.get()[RunnerParams_1.RunnerParamKey_ConfigPath] + '/.eslintrc.js';
156
+ const pathToLint = this.runtime.pathTo.pkg + 'src/main';
157
+ const extensions = extensionsToLint.map(ext => `--ext ${ext}`).join(' ');
158
+ await nvm_1.NVM.createCommando()
159
+ .append(`eslint --config ${pathToProjectESLint} ${extensions} ${pathToLint}`)
160
+ .execute();
67
161
  }
68
162
  }
69
163
  exports.Unit_TypescriptLib = Unit_TypescriptLib;
@@ -1,5 +1,14 @@
1
+ import { UnitPhaseImplementor } from '../types';
1
2
  import { Unit_Typescript } from './Unit_Typescript';
2
- import { Phase_Install, UnitPhaseImplementor } from './types';
3
- export declare class Unit_TypescriptProject extends Unit_Typescript implements UnitPhaseImplementor<[Phase_Install]> {
3
+ import { Phase_Install } from '../../phase';
4
+ import { StringMap } from '@nu-art/ts-common/utils/types';
5
+ type _Config<Config> = {
6
+ globalPackages?: StringMap;
7
+ } & Config;
8
+ type _RuntimeConfig<RTC> = {} & RTC;
9
+ export declare class Unit_TypescriptProject<Config extends {} = {}, RuntimeConfig extends {} = {}, C extends _Config<Config> = _Config<Config>, RTC extends _RuntimeConfig<RuntimeConfig> = _RuntimeConfig<RuntimeConfig>> extends Unit_Typescript<C, RTC> implements UnitPhaseImplementor<[Phase_Install]> {
10
+ private installGlobals;
11
+ private installPackages;
4
12
  install(): Promise<void>;
5
13
  }
14
+ export {};
@@ -2,8 +2,37 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Unit_TypescriptProject = void 0;
4
4
  const Unit_Typescript_1 = require("./Unit_Typescript");
5
+ const params_1 = require("../../../core/params/params");
6
+ const ts_common_1 = require("@nu-art/ts-common");
7
+ const nvm_1 = require("@nu-art/commando/cli/nvm");
8
+ const pnpm_1 = require("@nu-art/commando/cli/pnpm");
9
+ const consts_1 = require("../../phase-runner/consts");
5
10
  class Unit_TypescriptProject extends Unit_Typescript_1.Unit_Typescript {
11
+ //######################### Internal Logic #########################
12
+ async installGlobals() {
13
+ if ((!params_1.RuntimeParams.install && !params_1.RuntimeParams.installGlobals) || !this.config.globalPackages)
14
+ return;
15
+ const packages = (0, ts_common_1._keys)(this.config.globalPackages)
16
+ .reduce((acc, pkg) => {
17
+ acc.push(`${pkg}@${this.config.globalPackages[pkg]}`);
18
+ return acc;
19
+ }, []);
20
+ this.logInfo(`Installing Global Packages: ${packages.join(' ')}`);
21
+ await nvm_1.NVM.createCommando().append(`npm i -g ${packages.join(' ')}`).execute();
22
+ }
23
+ async installPackages() {
24
+ if (!params_1.RuntimeParams.install && !params_1.RuntimeParams.installPackages)
25
+ return;
26
+ const runner = consts_1.MemKey_PhaseRunner.get();
27
+ const units = runner.getUnits().filter(unit => unit instanceof Unit_Typescript_1.Unit_Typescript);
28
+ const packages = units.map(unit => unit.config.pathToPackage);
29
+ await pnpm_1.PNPM.createWorkspace(packages);
30
+ await pnpm_1.PNPM.installPackages(nvm_1.NVM.createCommando());
31
+ }
32
+ //######################### Phase Implementation #########################
6
33
  async install() {
34
+ await this.installGlobals();
35
+ await this.installPackages();
7
36
  }
8
37
  }
9
38
  exports.Unit_TypescriptProject = Unit_TypescriptProject;
@@ -1,4 +1,5 @@
1
- export * from './types';
2
1
  export * from './BaseUnit';
3
2
  export * from './Unit_Python';
4
3
  export * from './Unit_Typescript';
4
+ export * from './Unit_TypescriptLib';
5
+ export * from './Unit_TypescriptProject';
@@ -14,7 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
18
17
  __exportStar(require("./BaseUnit"), exports);
19
18
  __exportStar(require("./Unit_Python"), exports);
20
19
  __exportStar(require("./Unit_Typescript"), exports);
20
+ __exportStar(require("./Unit_TypescriptLib"), exports);
21
+ __exportStar(require("./Unit_TypescriptProject"), exports);
@@ -0,0 +1,40 @@
1
+ import { Unit_TypescriptLib } from '../core';
2
+ import { UnitPhaseImplementor } from '../types';
3
+ import { Phase_DeployBackend, Phase_Launch, Phase_ResolveConfigs } from '../../phase';
4
+ import { FirebasePackageConfig } from '../../../core/types';
5
+ type _Config<Config> = {
6
+ firebaseConfig: FirebasePackageConfig;
7
+ sources?: string[];
8
+ } & Config;
9
+ export declare class Unit_FirebaseFunctionsApp<Config extends {} = {}, C extends _Config<Config> = _Config<Config>> extends Unit_TypescriptLib<C> implements UnitPhaseImplementor<[Phase_ResolveConfigs, Phase_Launch, Phase_DeployBackend]> {
10
+ static staggerCount: number;
11
+ private readonly PROXY_PID_LOG;
12
+ private readonly PROXY_KILL_LOG;
13
+ private readonly EMULATOR_PID_LOG;
14
+ private readonly EMULATOR_KILL_LOG;
15
+ private launchCommandos;
16
+ private listeners;
17
+ resolveConfigs(): Promise<void>;
18
+ compile(): Promise<void>;
19
+ launch(): Promise<void>;
20
+ deployBackend(): Promise<void>;
21
+ private getEnvConfig;
22
+ private resolveFunctionsRC;
23
+ private resolveProxyFile;
24
+ private resolveConfigDir;
25
+ private resolveFunctionsJSON;
26
+ private resolveFunctionsRuntimeConfig;
27
+ private createAppVersionFile;
28
+ private createDependenciesDir;
29
+ private initLaunch;
30
+ private initLaunchListeners;
31
+ private clearPorts;
32
+ private runProxy;
33
+ private runEmulator;
34
+ private onLaunched;
35
+ private getPID;
36
+ kill(): Promise<void>;
37
+ private printFiles;
38
+ private deployImpl;
39
+ }
40
+ export {};
@@ -0,0 +1,312 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Unit_FirebaseFunctionsApp = void 0;
4
+ const core_1 = require("../core");
5
+ const consts_1 = require("../../../core/consts");
6
+ const fs_1 = require("fs");
7
+ const params_1 = require("../../../core/params/params");
8
+ const ts_common_1 = require("@nu-art/ts-common");
9
+ const consts_2 = require("../../../defaults/consts");
10
+ const RunnerParams_1 = require("../../phase-runner/RunnerParams");
11
+ const cli_1 = require("@nu-art/commando/core/cli");
12
+ const basic_1 = require("@nu-art/commando/cli/basic");
13
+ const nvm_1 = require("@nu-art/commando/cli/nvm");
14
+ const consts_3 = require("../../phase-runner/consts");
15
+ const CONST_VersionApp = 'version-app.json';
16
+ class Unit_FirebaseFunctionsApp extends core_1.Unit_TypescriptLib {
17
+ constructor() {
18
+ super(...arguments);
19
+ this.PROXY_PID_LOG = '_PROXY_PID_';
20
+ this.PROXY_KILL_LOG = '_PROXY_KILLED_';
21
+ this.EMULATOR_PID_LOG = '_EMULATOR_PID_';
22
+ this.EMULATOR_KILL_LOG = '_EMULATOR_KILLED_';
23
+ }
24
+ //######################### Phase Implementations #########################
25
+ async resolveConfigs() {
26
+ await this.resolveFunctionsRC();
27
+ await this.resolveProxyFile();
28
+ await this.resolveConfigDir();
29
+ await this.resolveFunctionsRuntimeConfig();
30
+ await this.resolveFunctionsJSON();
31
+ }
32
+ async compile() {
33
+ this.setStatus('Compile');
34
+ await this.resolveTSConfig();
35
+ await this.clearOutputDir();
36
+ await this.createAppVersionFile();
37
+ await this.compileImpl();
38
+ await this.copyAssetsToOutput();
39
+ await this.createDependenciesDir();
40
+ await this.copyPackageJSONToOutput();
41
+ this.setStatus('Compiled');
42
+ }
43
+ async launch() {
44
+ this.setStatus('Launching');
45
+ await (0, ts_common_1.sleep)(2 * ts_common_1.Second * Unit_FirebaseFunctionsApp.staggerCount++);
46
+ await this.initLaunch();
47
+ await this.initLaunchListeners();
48
+ await this.clearPorts();
49
+ await this.runProxy();
50
+ await this.runEmulator();
51
+ }
52
+ async deployBackend() {
53
+ await this.printFiles();
54
+ await this.deployImpl();
55
+ }
56
+ //######################### ResolveConfig Logic #########################
57
+ getEnvConfig() {
58
+ const env = params_1.RuntimeParams.environment;
59
+ const envConfig = this.config.firebaseConfig.envs.find(_env => _env.env === env);
60
+ if (!envConfig)
61
+ throw new ts_common_1.ImplementationMissingException(`Missing EnvConfig for env ${env} in unit ${this.config.label}`);
62
+ return envConfig;
63
+ }
64
+ async resolveFunctionsRC() {
65
+ const envConfig = this.getEnvConfig();
66
+ const rcConfig = { projects: { default: envConfig.projectId } };
67
+ const targetPath = `${this.runtime.pathTo.pkg}/${consts_1.CONST_FirebaseRC}`;
68
+ await fs_1.promises.writeFile(targetPath, JSON.stringify(rcConfig, null, 2), { encoding: 'utf-8' });
69
+ }
70
+ async resolveProxyFile() {
71
+ var _a, _b, _c;
72
+ const envConfig = this.getEnvConfig();
73
+ const defaultFiles = consts_2.MemKey_DefaultFiles.get();
74
+ const targetPath = `${this.runtime.pathTo.pkg}/src/main/proxy.ts`;
75
+ const path = (_a = defaultFiles === null || defaultFiles === void 0 ? void 0 : defaultFiles.backend) === null || _a === void 0 ? void 0 : _a.proxy;
76
+ if (!path)
77
+ return;
78
+ let fileContent = await fs_1.promises.readFile(path, { encoding: 'utf-8' });
79
+ fileContent = fileContent.replace(/PROJECT_ID/g, `${envConfig.projectId}`);
80
+ fileContent = fileContent.replace(/PROXY_PORT/g, `${this.config.firebaseConfig.basePort}`);
81
+ fileContent = fileContent.replace(/SERVER_PORT/g, `${this.config.firebaseConfig.basePort + 1}`);
82
+ fileContent = fileContent.replace(/PATH_TO_SSL_KEY/g, `${(_b = this.config.firebaseConfig.ssl) === null || _b === void 0 ? void 0 : _b.pathToKey}`);
83
+ fileContent = fileContent.replace(/PATH_TO_SSL_CERTIFICATE/g, `${(_c = this.config.firebaseConfig.ssl) === null || _c === void 0 ? void 0 : _c.pathToCertificate}`);
84
+ await fs_1.promises.writeFile(targetPath, fileContent, { encoding: 'utf-8' });
85
+ }
86
+ async resolveConfigDir() {
87
+ //Create the dir if it doesn't exist
88
+ const pathToFirebaseConfigFolder = `${this.runtime.pathTo.pkg}/${this.config.firebaseConfig.pathToFirebaseConfig}`;
89
+ try {
90
+ await fs_1.promises.access(pathToFirebaseConfigFolder);
91
+ }
92
+ catch (e) {
93
+ await fs_1.promises.mkdir(pathToFirebaseConfigFolder, { recursive: true });
94
+ }
95
+ //Fill config dir with relevant files for each file that doesn't exist
96
+ const defaultFiles = RunnerParams_1.MemKey_ProjectConfig.get().defaultFileRoutes;
97
+ if (!defaultFiles) {
98
+ this.logError('No defaultFileRoutes in project config');
99
+ return;
100
+ }
101
+ await Promise.all(consts_2.Const_FirebaseConfigKeys.map(async (firebaseConfigKey) => {
102
+ var _a;
103
+ const pathToConfigFile = `${pathToFirebaseConfigFolder}/${consts_2.Const_FirebaseDefaultsKeyToFile[firebaseConfigKey]}`;
104
+ try {
105
+ await fs_1.promises.access(pathToConfigFile);
106
+ }
107
+ catch (e) {
108
+ const path = (_a = defaultFiles.firebaseConfig) === null || _a === void 0 ? void 0 : _a[firebaseConfigKey];
109
+ if (!path)
110
+ return;
111
+ const defaultFileContent = await fs_1.promises.readFile(path, { encoding: 'utf-8' });
112
+ await fs_1.promises.writeFile(pathToConfigFile, defaultFileContent, { encoding: 'utf-8' });
113
+ }
114
+ }));
115
+ }
116
+ async resolveFunctionsJSON() {
117
+ var _a, _b;
118
+ const envConfig = this.getEnvConfig();
119
+ const targetPath = `${this.runtime.pathTo.pkg}/${consts_1.CONST_FirebaseJSON}`;
120
+ let fileContent;
121
+ if (envConfig.isLocal) {
122
+ const port = this.config.firebaseConfig.basePort;
123
+ fileContent = {
124
+ database: {
125
+ rules: `${this.config.firebaseConfig.pathToFirebaseConfig}/database.rules.json`
126
+ },
127
+ firestore: {
128
+ rules: `${this.config.firebaseConfig.pathToFirebaseConfig}/firestore.rules`,
129
+ indexes: `${this.config.firebaseConfig.pathToFirebaseConfig}/firestore.indexes.json`
130
+ },
131
+ storage: {
132
+ rules: `${this.config.firebaseConfig.pathToFirebaseConfig}/storage.rules`
133
+ },
134
+ remoteconfig: {
135
+ template: `${this.config.firebaseConfig.pathToFirebaseConfig}/remoteconfig.template.json`
136
+ },
137
+ functions: {
138
+ ignore: (_a = this.config.firebaseConfig.functions) === null || _a === void 0 ? void 0 : _a.ignore,
139
+ source: '.',
140
+ predeploy: [
141
+ 'echo "Thunderstorm - Local environment is not deployable... Aborting..." && exit 2'
142
+ ]
143
+ },
144
+ emulators: {
145
+ functions: { port: port + 1 },
146
+ database: { port: port + 2 },
147
+ firestore: {
148
+ port: port + 3,
149
+ websocketPort: port + 4
150
+ },
151
+ pubsub: { port: port + 5 },
152
+ storage: { port: port + 6 },
153
+ auth: { port: port + 7 },
154
+ ui: { port: port + 8, enabled: true },
155
+ hub: { port: port + 9 },
156
+ logging: { port: port + 10 }
157
+ }
158
+ };
159
+ }
160
+ else {
161
+ fileContent = {
162
+ functions: {
163
+ source: this.config.output.replace(`${this.config.pathToPackage}/`, ''),
164
+ ignore: (_b = this.config.firebaseConfig.functions) === null || _b === void 0 ? void 0 : _b.ignore
165
+ }
166
+ };
167
+ }
168
+ await fs_1.promises.writeFile(targetPath, JSON.stringify(fileContent, null, 2), { encoding: 'utf-8' });
169
+ }
170
+ async resolveFunctionsRuntimeConfig() {
171
+ const envConfig = this.getEnvConfig();
172
+ const targetPath = `${this.runtime.pathTo.pkg}/src/main/config.ts`;
173
+ const beConfig = { name: envConfig.env };
174
+ const fileContent = `${envConfig.isLocal ? '// @ts-ignore\nprocess.env[\'NODE_TLS_REJECT_UNAUTHORIZED\'] = 0;\n' : ''}
175
+ export const Environment = ${JSON.stringify(beConfig)};`;
176
+ await fs_1.promises.writeFile(targetPath, fileContent, { encoding: 'utf-8' });
177
+ }
178
+ //######################### Compile Logic #########################
179
+ async createAppVersionFile() {
180
+ //Writing the file to the package source instead of the output is fine,
181
+ //copyAssetsToOutput will move the file to output
182
+ const targetPath = `${this.runtime.pathTo.pkg}/${CONST_VersionApp}`;
183
+ const appVersion = RunnerParams_1.MemKey_ProjectConfig.get().projectVersion;
184
+ const fileContent = JSON.stringify({ version: appVersion }, null, 2);
185
+ await fs_1.promises.writeFile(targetPath, fileContent, { encoding: 'utf-8' });
186
+ }
187
+ async createDependenciesDir() {
188
+ var _a;
189
+ //Gather units that are dependencies of this unit
190
+ const dependencies = (0, ts_common_1._keys)((_a = this.packageJson.root.dependencies) !== null && _a !== void 0 ? _a : {});
191
+ const runner = consts_3.MemKey_PhaseRunner.get();
192
+ const tsLibUnits = runner.getUnits().filter(unit => unit instanceof core_1.Unit_TypescriptLib);
193
+ const dependencyUnits = tsLibUnits.filter(unit => {
194
+ const unitPJName = unit.packageJson.template.name;
195
+ return dependencies.includes(unitPJName);
196
+ });
197
+ if (!dependencyUnits.length)
198
+ return;
199
+ const packageJsonConverter = (pj) => {
200
+ var _a;
201
+ const finalPJ = (0, ts_common_1.deepClone)(this.packageJson.dist);
202
+ (_a = finalPJ.dependencies) !== null && _a !== void 0 ? _a : (finalPJ.dependencies = {});
203
+ (0, ts_common_1._keys)(finalPJ.dependencies).reduce((acc, packageName) => {
204
+ const unit = dependencyUnits.find(unit => unit.packageJson.template.name === packageName);
205
+ if (!unit)
206
+ return acc;
207
+ acc[packageName] = `file:.dependencies/${unit.config.key}`;
208
+ return acc;
209
+ }, finalPJ.dependencies);
210
+ return finalPJ;
211
+ };
212
+ await Promise.all(dependencyUnits.map(async (unit) => {
213
+ //Copy dependency unit output into this units output/.dependency dir
214
+ const dependencyOutputPath = `${unit.runtime.pathTo.output}/`;
215
+ const targetPath = `${this.runtime.pathTo.output}/.dependencies/${unit.config.key}/`;
216
+ const pjTargetPath = `${targetPath}/${consts_1.CONST_PackageJSON}`;
217
+ await cli_1.Commando.create()
218
+ .append(`mkdir -p ${targetPath}`)
219
+ .append(`rsync -a --delete ${dependencyOutputPath} ${targetPath}`)
220
+ .execute();
221
+ //Copy units dependency package into newly created dir
222
+ const dependencyPJ = packageJsonConverter(unit.packageJson.dist);
223
+ const fileContent = JSON.stringify(dependencyPJ, null, 2);
224
+ await fs_1.promises.writeFile(pjTargetPath, fileContent, { encoding: 'utf-8' });
225
+ }));
226
+ this.packageJson.dist = packageJsonConverter(this.packageJson.dist);
227
+ }
228
+ //######################### Launch Logic #########################
229
+ async initLaunch() {
230
+ this.launchCommandos = {
231
+ emulator: nvm_1.NVM.createInteractiveCommando(basic_1.Cli_Basic).setUID(this.config.key).cd(this.runtime.pathTo.pkg),
232
+ proxy: nvm_1.NVM.createInteractiveCommando(basic_1.Cli_Basic).setUID(this.config.key).cd(this.runtime.pathTo.pkg),
233
+ };
234
+ }
235
+ async initLaunchListeners() {
236
+ this.listeners = {
237
+ proxy: {
238
+ pid: new cli_1.CommandoCLIKeyValueListener(new RegExp(`${this.PROXY_PID_LOG}=(\\d+)`)),
239
+ kill: new cli_1.CommandoCLIListener(() => this.launchCommandos.proxy.close(), this.PROXY_KILL_LOG),
240
+ },
241
+ emulator: {
242
+ pid: new cli_1.CommandoCLIKeyValueListener(new RegExp(`${this.EMULATOR_PID_LOG}=(\\d+)`)),
243
+ kill: new cli_1.CommandoCLIListener(() => this.launchCommandos.emulator.close(), this.EMULATOR_KILL_LOG),
244
+ },
245
+ onReady: new cli_1.CommandoCLIListener(() => this.onLaunched(), new RegExp('.*Emulator Hub running.*')),
246
+ };
247
+ this.listeners.proxy.kill.listen(this.launchCommandos.proxy);
248
+ this.listeners.proxy.pid.listen(this.launchCommandos.proxy);
249
+ this.listeners.emulator.kill.listen(this.launchCommandos.emulator);
250
+ this.listeners.emulator.pid.listen(this.launchCommandos.emulator);
251
+ this.listeners.onReady.listen(this.launchCommandos.emulator);
252
+ }
253
+ async clearPorts() {
254
+ const allPorts = Array.from({ length: 10 }, (_, i) => `${this.config.firebaseConfig.basePort + i}`);
255
+ await cli_1.Commando.create(basic_1.Cli_Basic)
256
+ .debug()
257
+ .append(`array=($(lsof -ti:${allPorts.join(',')}))`)
258
+ .append(`((\${#array[@]} > 0)) && kill -9 "\${array[@]}"`)
259
+ .append('echo ')
260
+ .execute();
261
+ }
262
+ async runProxy() {
263
+ await this.launchCommandos.proxy
264
+ .append('ts-node src/main/proxy.ts &')
265
+ .append('pid=$!')
266
+ .append(`echo "${this.PROXY_PID_LOG}=\${pid}"`)
267
+ .append(`wait \$pid`)
268
+ .append(`echo "${this.PROXY_KILL_LOG} \${pid}"`)
269
+ .execute();
270
+ }
271
+ async runEmulator() {
272
+ await this.launchCommandos.emulator
273
+ .append(`firebase emulators:start --export-on-exit --import=.trash/data ${params_1.RuntimeParams.debugBackend ? `--inspect-functions ${this.config.firebaseConfig.debugPort}` : ''} &`)
274
+ .append('pid=$!')
275
+ .append(`echo "${this.EMULATOR_PID_LOG}=\${pid}"`)
276
+ .append(`wait \$pid`)
277
+ .append(`echo "${this.EMULATOR_KILL_LOG} \${pid}"`)
278
+ .execute();
279
+ }
280
+ onLaunched() {
281
+ this.setStatus('Launch Complete');
282
+ }
283
+ getPID(listener) {
284
+ const pid = Number(listener.getValue());
285
+ return isNaN(pid) ? undefined : pid;
286
+ }
287
+ async kill() {
288
+ if (!this.launchCommandos)
289
+ return;
290
+ const emulatorPid = this.getPID(this.listeners.emulator.pid);
291
+ const proxyPid = this.getPID(this.listeners.proxy.pid);
292
+ await this.launchCommandos.emulator.gracefullyKill(emulatorPid);
293
+ await this.launchCommandos.proxy.gracefullyKill(proxyPid);
294
+ }
295
+ //######################### Deploy Logic #########################
296
+ async printFiles() {
297
+ await cli_1.Commando.create(basic_1.Cli_Basic)
298
+ .cd(this.runtime.pathTo.output)
299
+ .ls()
300
+ .cat('package.json')
301
+ .cat('index.js')
302
+ .execute();
303
+ }
304
+ async deployImpl() {
305
+ await nvm_1.NVM.createCommando(basic_1.Cli_Basic)
306
+ .cd(this.runtime.pathTo.pkg)
307
+ .append(`firebase --debug deploy --only functions --force`)
308
+ .execute();
309
+ }
310
+ }
311
+ Unit_FirebaseFunctionsApp.staggerCount = 0;
312
+ exports.Unit_FirebaseFunctionsApp = Unit_FirebaseFunctionsApp;
@@ -0,0 +1,32 @@
1
+ import { Unit_TypescriptLib } from '../core';
2
+ import { FirebasePackageConfig } from '../../../core/types';
3
+ import { UnitPhaseImplementor } from '../types';
4
+ import { Phase_DeployFrontend, Phase_Launch, Phase_ResolveConfigs } from '../../phase';
5
+ type _Config<Config> = {
6
+ firebaseConfig: FirebasePackageConfig;
7
+ sources?: string[];
8
+ } & Config;
9
+ export declare class Unit_FirebaseHostingApp<Config extends {} = {}, C extends _Config<Config> = _Config<Config>> extends Unit_TypescriptLib<C> implements UnitPhaseImplementor<[Phase_ResolveConfigs, Phase_Launch, Phase_DeployFrontend]> {
10
+ private readonly APP_PID_LOG;
11
+ private readonly APP_KILL_LOG;
12
+ private launchCommando;
13
+ private listeners;
14
+ resolveConfigs(): Promise<void>;
15
+ compile(): Promise<void>;
16
+ launch(): Promise<void>;
17
+ deployFrontend(): Promise<void>;
18
+ private getEnvConfig;
19
+ private resolveHostingRC;
20
+ private resolveHostingJSON;
21
+ private resolveHostingRuntimeConfig;
22
+ protected compileImpl(): Promise<void>;
23
+ private createAppVersionFile;
24
+ private initLaunch;
25
+ private initLaunchListeners;
26
+ private getPID;
27
+ private clearPorts;
28
+ private runApp;
29
+ kill(): Promise<void>;
30
+ private deployImpl;
31
+ }
32
+ export {};