@magek/cli 0.0.1

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 (61) hide show
  1. package/bin/run +5 -0
  2. package/bin/run.cmd +3 -0
  3. package/dist/commands/add/projection.js +51 -0
  4. package/dist/commands/add/reducer.js +52 -0
  5. package/dist/commands/build.js +35 -0
  6. package/dist/commands/clean.js +35 -0
  7. package/dist/commands/deploy.js +47 -0
  8. package/dist/commands/new/command.js +71 -0
  9. package/dist/commands/new/entity.js +84 -0
  10. package/dist/commands/new/event-handler.js +73 -0
  11. package/dist/commands/new/event.js +65 -0
  12. package/dist/commands/new/query.js +71 -0
  13. package/dist/commands/new/read-model.js +85 -0
  14. package/dist/commands/new/scheduled-command.js +60 -0
  15. package/dist/commands/new/type.js +53 -0
  16. package/dist/commands/nuke.js +63 -0
  17. package/dist/commands/start.js +52 -0
  18. package/dist/commands/stub/publish.js +44 -0
  19. package/dist/commands/synth.js +45 -0
  20. package/dist/common/base-command.js +18 -0
  21. package/dist/common/brand.js +38 -0
  22. package/dist/common/errors.js +24 -0
  23. package/dist/common/filenames.js +45 -0
  24. package/dist/common/provider.js +2 -0
  25. package/dist/common/sandbox.js +45 -0
  26. package/dist/common/script.js +102 -0
  27. package/dist/hooks/command_not_found/custom-parse.js +40 -0
  28. package/dist/index.js +4 -0
  29. package/dist/services/config-service.js +76 -0
  30. package/dist/services/environment.js +22 -0
  31. package/dist/services/file-system/index.js +12 -0
  32. package/dist/services/file-system/live.impl.js +26 -0
  33. package/dist/services/generator/target/index.js +5 -0
  34. package/dist/services/generator/target/parsing.js +64 -0
  35. package/dist/services/generator/target/types.js +2 -0
  36. package/dist/services/generator.js +40 -0
  37. package/dist/services/logger.js +23 -0
  38. package/dist/services/method-generator.js +81 -0
  39. package/dist/services/package-manager/common.js +74 -0
  40. package/dist/services/package-manager/index.js +21 -0
  41. package/dist/services/package-manager/live.impl.js +35 -0
  42. package/dist/services/package-manager/npm.impl.js +8 -0
  43. package/dist/services/package-manager/pnpm.impl.js +8 -0
  44. package/dist/services/package-manager/rush.impl.js +50 -0
  45. package/dist/services/package-manager/yarn.impl.js +8 -0
  46. package/dist/services/process/index.js +12 -0
  47. package/dist/services/process/live.impl.js +30 -0
  48. package/dist/services/project-checker.js +152 -0
  49. package/dist/services/provider-service.js +53 -0
  50. package/dist/services/semver.js +29 -0
  51. package/dist/services/stub-publisher.js +42 -0
  52. package/dist/services/user-prompt.js +31 -0
  53. package/dist/templates/command.stub +17 -0
  54. package/dist/templates/entity.stub +22 -0
  55. package/dist/templates/event-handler.stub +8 -0
  56. package/dist/templates/event.stub +16 -0
  57. package/dist/templates/query.stub +17 -0
  58. package/dist/templates/read-model.stub +24 -0
  59. package/dist/templates/scheduled-command.stub +13 -0
  60. package/dist/templates/type.stub +7 -0
  61. package/package.json +91 -0
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Script = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const ReaderTaskEither_js_1 = require("fp-ts/lib/ReaderTaskEither.js");
6
+ const pipeable_js_1 = require("fp-ts/lib/pipeable.js");
7
+ const Either_js_1 = require("fp-ts/lib/Either.js");
8
+ const TaskEither_js_1 = require("fp-ts/lib/TaskEither.js");
9
+ const function_js_1 = require("fp-ts/lib/function.js");
10
+ const logger_js_1 = require("../services/logger.js");
11
+ const brand_js_1 = tslib_1.__importDefault(require("./brand.js"));
12
+ /**
13
+ * A Script represents some steps in a Magek command, it stores the initial context
14
+ * implicitly, and makes it available for all of the steps that define this process.
15
+ */
16
+ class Script {
17
+ constructor(contextResolver, errorHandlers, action) {
18
+ /**
19
+ * Method that eases the creation of steps. It accepts a message to be shown in the spinner and a
20
+ * function that receives the context and the input from the previous step.
21
+ * From this function you must return a Promise that resolves with the value that you want to pass to the next step (if any)
22
+ *
23
+ * @param message Message to initialize the spinner
24
+ * @param action Function that receives the config object and performs an action
25
+ */
26
+ this.step = (message, action) => new Script(this.contextResolver, this.errorHandlers, (0, pipeable_js_1.pipe)(this.action, (0, ReaderTaskEither_js_1.chain)(() => (0, ReaderTaskEither_js_1.ask)()), (0, ReaderTaskEither_js_1.chain)((ctx) => (0, ReaderTaskEither_js_1.fromTaskEither)((0, TaskEither_js_1.tryCatch)(async () => {
27
+ Script.logger.start(message);
28
+ await action(ctx);
29
+ Script.logger.succeed(message);
30
+ }, (err) => {
31
+ Script.logger.fail(message);
32
+ return err;
33
+ })))));
34
+ /**
35
+ * Function to determine next action depending on passed boolean condition
36
+ * If condition is true, step will be skipped and info action will be called.
37
+ * Otherwise, step method will be called as usual.
38
+ *
39
+ * @param skipCondition When true, the action is skipped
40
+ * @param message Message to initialize the spinner
41
+ * @param action Function that receives the config object and performs an action
42
+ */
43
+ this.optionalStep = (skipCondition, message, action) => {
44
+ if (skipCondition)
45
+ return this.info(brand_js_1.default.mellancholize(`Skipping: ${message}`));
46
+ return this.step(message, action);
47
+ };
48
+ /**
49
+ * Convenience method to generate a step that just prints a message with a small blue `i` character in front of it.
50
+ *
51
+ * @param message Message to be shown in the CLI
52
+ */
53
+ this.info = (message) => new Script(this.contextResolver, this.errorHandlers, (0, pipeable_js_1.pipe)(this.action, (0, ReaderTaskEither_js_1.chain)(() => (0, ReaderTaskEither_js_1.rightIO)(() => {
54
+ Script.logger.info(message);
55
+ }))));
56
+ /**
57
+ * Add a handler to catch a specific type of errors
58
+ *
59
+ * @param errorType the kind of errors that the handler will catch
60
+ * @param handler handler for the errors
61
+ */
62
+ this.catch = (errorType, handler) => {
63
+ const newHandlers = { ...this.errorHandlers };
64
+ newHandlers[errorType] = handler;
65
+ return new Script(this.contextResolver, newHandlers, this.action);
66
+ };
67
+ this.contextResolver = contextResolver;
68
+ this.errorHandlers = errorHandlers;
69
+ this.action = action;
70
+ }
71
+ /**
72
+ * Function to finish the script,
73
+ * it will handle any error in between that might happen in
74
+ * some steps.
75
+ */
76
+ async done() {
77
+ try {
78
+ const context = await this.contextResolver;
79
+ const result = await this.action(context)();
80
+ return (0, pipeable_js_1.pipe)(result, (0, Either_js_1.fold)((err) => {
81
+ throw err;
82
+ }, function_js_1.constVoid));
83
+ }
84
+ catch (err) {
85
+ const error = err;
86
+ const defaultHandler = (e) => e.stack || e.message || JSON.stringify(e);
87
+ const handler = this.errorHandlers[error.name] || defaultHandler;
88
+ throw new Error(handler(error));
89
+ }
90
+ }
91
+ }
92
+ exports.Script = Script;
93
+ /**
94
+ * Convenience function to print a welcome message and initialize the context of the script
95
+ *
96
+ * @param initialMessage The message to show in the console
97
+ * @param contextResolver A promise that fulfills into a valid context object
98
+ */
99
+ Script.init = (initialMessage, contextResolver) => new Script(contextResolver, {}, (0, ReaderTaskEither_js_1.rightIO)(() => {
100
+ Script.logger.info(initialMessage);
101
+ }));
102
+ Script.logger = logger_js_1.oraLogger;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const path = require("path");
5
+ const process = tslib_1.__importStar(require("process"));
6
+ const logger_js_1 = require("../../services/logger.js");
7
+ const environment_js_1 = require("../../services/environment.js");
8
+ // Function to find and remove the `-e` argument and its accompanying value
9
+ const extractEnvironmentArg = () => {
10
+ const argv = process.argv;
11
+ const eIndex = argv.indexOf('-e'); // Find the index of `-e` in argv
12
+ let environment; // Variable to store the value found after `-e`
13
+ if (eIndex !== -1 && eIndex + 1 < argv.length) {
14
+ environment = argv[eIndex + 1]; // Save the value following `-e`
15
+ argv.splice(eIndex, 2); // Remove both `-e` and its value from argv
16
+ }
17
+ return environment;
18
+ };
19
+ const hook = async function (opts) {
20
+ var _a;
21
+ // ensure opts.argv is argv without the environment
22
+ process.env['MAGEK_CLI_HOOK'] = 'true';
23
+ if (opts.id === '-e') {
24
+ opts.id = '';
25
+ opts.argv = ['-e', ...((_a = opts.argv) !== null && _a !== void 0 ? _a : [])];
26
+ }
27
+ const firstArgs = process.argv.filter((arg) => { var _a; return !((_a = opts.argv) === null || _a === void 0 ? void 0 : _a.includes(arg)); });
28
+ const environment = extractEnvironmentArg();
29
+ opts.argv = process.argv.filter((arg) => !firstArgs.includes(arg));
30
+ const cwd = process.cwd();
31
+ if ((0, environment_js_1.initializeEnvironment)(logger_js_1.logger, environment)) {
32
+ // to allow doing `magek -e <env>` and show the help
33
+ if (!opts.id && opts.argv.length === 0) {
34
+ ;
35
+ process.argv = [...firstArgs, '--help'];
36
+ }
37
+ await import(path.join(cwd, 'dist', 'index.js'));
38
+ }
39
+ };
40
+ exports.default = hook;
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var core_1 = require("@oclif/core");
4
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return core_1.run; } });
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cleanProject = exports.compileProject = exports.compileProjectAndLoadConfig = exports.configService = exports.configServiceDependencies = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const errors_js_1 = require("../common/errors.js");
7
+ const project_checker_js_1 = require("./project-checker.js");
8
+ const environment_js_1 = require("./environment.js");
9
+ const live_impl_js_1 = require("./package-manager/live.impl.js");
10
+ const loadUserProject = (userProjectPath) => {
11
+ const projectIndexJSPath = path.resolve(path.join(userProjectPath, 'dist', 'index.js'));
12
+ return require(projectIndexJSPath);
13
+ };
14
+ exports.configServiceDependencies = {
15
+ loadUserProject,
16
+ checkItIsAMagekProject: project_checker_js_1.checkItIsAMagekProject,
17
+ currentEnvironment: environment_js_1.currentEnvironment,
18
+ };
19
+ const compileProjectAndLoadConfigImpl = async (userProjectPath) => {
20
+ await exports.configServiceDependencies.checkItIsAMagekProject(userProjectPath);
21
+ await exports.configService.compileProject(userProjectPath);
22
+ return readProjectConfig(userProjectPath);
23
+ };
24
+ const compileProjectImpl = async (projectPath) => {
25
+ try {
26
+ const packageManager = await (0, live_impl_js_1.createLivePackageManager)();
27
+ packageManager.setProjectRoot(projectPath);
28
+ await cleanProjectImpl(projectPath);
29
+ await packageManager.build([]);
30
+ }
31
+ catch (error) {
32
+ throw (0, errors_js_1.guardError)('Project contains compilation errors')(error);
33
+ }
34
+ };
35
+ const cleanProjectImpl = async (projectPath) => {
36
+ try {
37
+ const packageManager = await (0, live_impl_js_1.createLivePackageManager)();
38
+ packageManager.setProjectRoot(projectPath);
39
+ await packageManager.runScript('clean', []);
40
+ }
41
+ catch (error) {
42
+ throw (0, errors_js_1.guardError)('Could not clean project')(error);
43
+ }
44
+ };
45
+ function readProjectConfig(userProjectPath) {
46
+ const userProject = exports.configServiceDependencies.loadUserProject(userProjectPath);
47
+ return new Promise((resolve) => {
48
+ userProject.Magek.configureCurrentEnv((config) => {
49
+ checkEnvironmentWasConfigured(userProject);
50
+ resolve(config);
51
+ });
52
+ });
53
+ }
54
+ function checkEnvironmentWasConfigured(userProject) {
55
+ if (userProject.Magek.configuredEnvironments.size == 0) {
56
+ throw new Error("You haven't configured any environment. Please make sure you have at least one environment configured by calling 'Magek.configure' method (normally done inside the folder 'src/config')");
57
+ }
58
+ const currentEnv = exports.configServiceDependencies.currentEnvironment();
59
+ if (!currentEnv) {
60
+ throw new Error("You haven't provided any environment. Please make sure you are using option '-e' with a valid environment name");
61
+ }
62
+ if (!userProject.Magek.configuredEnvironments.has(currentEnv)) {
63
+ throw new Error(`The environment '${currentEnv}' does not match any of the environments you used to configure your Magek project, which are: '${Array.from(userProject.Magek.configuredEnvironments).join(', ')}'`);
64
+ }
65
+ }
66
+ exports.configService = {
67
+ compileProjectAndLoadConfig: compileProjectAndLoadConfigImpl,
68
+ compileProject: compileProjectImpl,
69
+ cleanProject: cleanProjectImpl,
70
+ };
71
+ const compileProjectAndLoadConfig = (...args) => exports.configService.compileProjectAndLoadConfig(...args);
72
+ exports.compileProjectAndLoadConfig = compileProjectAndLoadConfig;
73
+ const compileProject = (...args) => exports.configService.compileProject(...args);
74
+ exports.compileProject = compileProject;
75
+ const cleanProject = (...args) => exports.configService.cleanProject(...args);
76
+ exports.cleanProject = cleanProject;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.currentEnvironment = exports.initializeEnvironment = exports.environmentService = void 0;
4
+ const initializeEnvironmentImpl = (logger, environment) => {
5
+ if (environment) {
6
+ process.env.MAGEK_ENV = environment;
7
+ }
8
+ if (!exports.environmentService.currentEnvironment()) {
9
+ logger.error('Error: No environment set. Use the flag `-e` or set the environment variable MAGEK_ENV to set it before running this command. Example usage: `magek start -e <environment>`.');
10
+ return false;
11
+ }
12
+ return true;
13
+ };
14
+ const currentEnvironmentImpl = () => process.env.MAGEK_ENV;
15
+ exports.environmentService = {
16
+ initializeEnvironment: initializeEnvironmentImpl,
17
+ currentEnvironment: currentEnvironmentImpl,
18
+ };
19
+ const initializeEnvironment = (...args) => exports.environmentService.initializeEnvironment(...args);
20
+ exports.initializeEnvironment = initializeEnvironment;
21
+ const currentEnvironment = (...args) => exports.environmentService.currentEnvironment(...args);
22
+ exports.currentEnvironment = currentEnvironment;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileSystemError = void 0;
4
+ class FileSystemError extends Error {
5
+ constructor(message, cause) {
6
+ super(message);
7
+ this.cause = cause;
8
+ this._tag = 'FileSystemError';
9
+ this.name = 'FileSystemError';
10
+ }
11
+ }
12
+ exports.FileSystemError = FileSystemError;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.liveFileSystemService = exports.createFileSystemService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const index_js_1 = require("./index.js");
6
+ const fs = tslib_1.__importStar(require("fs"));
7
+ const createFileSystemService = () => ({
8
+ readDirectoryContents: async (directoryPath) => {
9
+ try {
10
+ return await fs.promises.readdir(directoryPath);
11
+ }
12
+ catch (reason) {
13
+ throw new index_js_1.FileSystemError(`There were some issues reading the directory ${directoryPath}`, reason instanceof Error ? reason : new Error(String(reason)));
14
+ }
15
+ },
16
+ readFileContents: async (filePath) => {
17
+ try {
18
+ return await fs.promises.readFile(filePath, 'utf8');
19
+ }
20
+ catch (reason) {
21
+ throw new index_js_1.FileSystemError(`There were some issues reading the file ${filePath}`, reason instanceof Error ? reason : new Error(String(reason)));
22
+ }
23
+ },
24
+ });
25
+ exports.createFileSystemService = createFileSystemService;
26
+ exports.liveFileSystemService = (0, exports.createFileSystemService)();
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./parsing.js"), exports);
5
+ tslib_1.__exportStar(require("./types.js"), exports);
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseReaction = exports.parseProjectionField = exports.parseProjections = exports.parseFields = exports.parseEvent = exports.parseName = void 0;
4
+ exports.joinParsers = joinParsers;
5
+ const parseName = (name) => Promise.resolve({ name });
6
+ exports.parseName = parseName;
7
+ const parseEvent = (event) => Promise.resolve({ event });
8
+ exports.parseEvent = parseEvent;
9
+ const parseFields = async (fields) => {
10
+ const parsedFields = await Promise.all(fields.map(parseField));
11
+ const parsedFieldNames = parsedFields.map((field) => field.name);
12
+ const uniqueFieldNames = new Set(parsedFieldNames);
13
+ const duplicates = parsedFieldNames.filter((field) => !uniqueFieldNames.delete(field));
14
+ if (duplicates.length > 0) {
15
+ throw fieldDuplicatedError(duplicates.join(', '));
16
+ }
17
+ return { fields: parsedFields };
18
+ };
19
+ exports.parseFields = parseFields;
20
+ function parseField(rawField) {
21
+ const splitInput = rawField.split(':');
22
+ if (splitInput.length != 2 || splitInput[0].length === 0 || splitInput[1].length === 0) {
23
+ return Promise.reject(fieldParsingError(rawField));
24
+ }
25
+ else {
26
+ return Promise.resolve({
27
+ name: splitInput[0],
28
+ type: splitInput[1],
29
+ });
30
+ }
31
+ }
32
+ const parseProjections = (fields) => Promise.all(fields.map(parseProjection)).then((projections) => ({ projections }));
33
+ exports.parseProjections = parseProjections;
34
+ const parseProjectionField = (field) => parseProjection(field).then((projection) => ({ projection }));
35
+ exports.parseProjectionField = parseProjectionField;
36
+ async function parseProjection(rawProjection) {
37
+ const splitInput = rawProjection.split(':');
38
+ if (splitInput.length != 2 || splitInput[0].length === 0 || splitInput[1].length === 0) {
39
+ throw projectionParsingError(rawProjection);
40
+ }
41
+ else {
42
+ return {
43
+ entityName: splitInput[0],
44
+ entityId: splitInput[1],
45
+ };
46
+ }
47
+ }
48
+ const parseReaction = (rawEvents) => Promise.all(rawEvents.map(parseReactionEvent)).then((events) => ({
49
+ events,
50
+ }));
51
+ exports.parseReaction = parseReaction;
52
+ const parseReactionEvent = (eventName) => Promise.resolve({ eventName });
53
+ const fieldParsingError = (field) => new Error(`Error parsing field ${field}. Fields must be in the form of <field name>:<field type>`);
54
+ const fieldDuplicatedError = (field) => new Error(`Error parsing field ${field}. Fields cannot be duplicated`);
55
+ const projectionParsingError = (projection) => new Error(`Error parsing projection ${projection}. Projections must be in the form of <entity name>:<entity id>`);
56
+ function joinParsers(...parsers) {
57
+ return Promise.all(parsers).then((results) => {
58
+ let merged = {};
59
+ for (const value of results) {
60
+ merged = Object.assign(merged, value);
61
+ }
62
+ return merged;
63
+ });
64
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generate = generate;
4
+ exports.template = template;
5
+ exports.filePath = filePath;
6
+ exports.getResourceType = getResourceType;
7
+ const tslib_1 = require("tslib");
8
+ const path = tslib_1.__importStar(require("path"));
9
+ const fsExtra = tslib_1.__importStar(require("fs-extra"));
10
+ const Mustache = tslib_1.__importStar(require("mustache"));
11
+ const filenames_js_1 = require("../common/filenames.js");
12
+ const project_checker_js_1 = require("./project-checker.js");
13
+ const stub_publisher_js_1 = require("./stub-publisher.js");
14
+ async function generate(target) {
15
+ await (0, project_checker_js_1.checkResourceExists)(target.name, target.placementDir, target.extension);
16
+ (0, filenames_js_1.checkResourceNameIsValid)(target.name);
17
+ const rendered = Mustache.render(target.template, { ...target.info });
18
+ const renderPath = filePath(target);
19
+ await fsExtra.outputFile(renderPath, rendered);
20
+ }
21
+ function template(name) {
22
+ const fileName = `${name}.stub`;
23
+ const stubFile = (0, stub_publisher_js_1.resourceStubFilePath)(fileName);
24
+ if ((0, stub_publisher_js_1.checkStubsFolderExists)() && (0, stub_publisher_js_1.checkResourceStubFileExists)(stubFile)) {
25
+ return fsExtra.readFileSync(stubFile).toString();
26
+ }
27
+ return fsExtra.readFileSync((0, stub_publisher_js_1.resourceTemplateFilePath)(fileName)).toString();
28
+ }
29
+ function filePath(target) {
30
+ const fileName = (0, filenames_js_1.classNameToFileName)(target.name);
31
+ return path.join(process.cwd(), target.placementDir, `${fileName}${target.extension}`);
32
+ }
33
+ /**
34
+ * Split path string to get resource folder name
35
+ *
36
+ * @param resourcePath path string
37
+ */
38
+ function getResourceType(resourcePath) {
39
+ return path.parse(resourcePath).name;
40
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logger = exports.oraLogger = void 0;
4
+ exports.appendOnErrorsFile = appendOnErrorsFile;
5
+ const tslib_1 = require("tslib");
6
+ const ora_1 = tslib_1.__importDefault(require("ora"));
7
+ const fs_1 = require("fs");
8
+ const path = tslib_1.__importStar(require("path"));
9
+ exports.oraLogger = (0, ora_1.default)({ stream: process.stdout });
10
+ exports.logger = {
11
+ debug: (message) => exports.oraLogger.warn(message),
12
+ info: (message) => exports.oraLogger.info(message),
13
+ warn: (message) => exports.oraLogger.warn(message),
14
+ error: (message) => exports.oraLogger.fail(message),
15
+ };
16
+ function appendOnErrorsFile(data) {
17
+ const errorsFile = path.join(process.cwd(), 'errors.log');
18
+ const transformedData = data
19
+ .split('\n')
20
+ .map((line) => `[${new Date().toISOString()}] ${line}`)
21
+ .join('\n');
22
+ (0, fs_1.appendFileSync)(errorsFile, transformedData);
23
+ }
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateProjection = exports.generateReducers = exports.getResourceSourceFile = exports.methodGenerator = void 0;
4
+ const ts_morph_1 = require("ts-morph");
5
+ const filenames_js_1 = require("../common/filenames.js");
6
+ const getResourceSourceFileImpl = (name) => {
7
+ const project = new ts_morph_1.Project({
8
+ tsConfigFilePath: './tsconfig.json',
9
+ manipulationSettings: {
10
+ quoteKind: ts_morph_1.QuoteKind.Single,
11
+ indentationText: ts_morph_1.IndentationText.TwoSpaces,
12
+ },
13
+ });
14
+ const sourceFileName = (0, filenames_js_1.fileNameWithExtension)(name);
15
+ return project.getSourceFileOrThrow(sourceFileName);
16
+ };
17
+ const generateReducersImpl = (entity, events) => {
18
+ return events.map(({ eventName }) => {
19
+ return {
20
+ decorators: [
21
+ {
22
+ name: 'Reduces',
23
+ arguments: [eventName],
24
+ },
25
+ ],
26
+ scope: ts_morph_1.Scope.Public,
27
+ isStatic: true,
28
+ name: `reduce${eventName}`,
29
+ returnType: entity,
30
+ parameters: [
31
+ {
32
+ name: 'event',
33
+ type: eventName,
34
+ },
35
+ {
36
+ name: `current${entity}`,
37
+ type: entity,
38
+ hasQuestionToken: true,
39
+ },
40
+ ],
41
+ statements: [`return /* NEW ${entity} HERE */`],
42
+ };
43
+ });
44
+ };
45
+ const generateProjectionImpl = (readModel, projection) => {
46
+ return {
47
+ decorators: [
48
+ {
49
+ name: 'Projects',
50
+ arguments: [projection.entityName, `'${projection.entityId}'`],
51
+ },
52
+ ],
53
+ scope: ts_morph_1.Scope.Public,
54
+ isStatic: true,
55
+ name: `project${projection.entityName}`,
56
+ parameters: [
57
+ {
58
+ name: 'entity',
59
+ type: projection.entityName,
60
+ },
61
+ {
62
+ name: `current${readModel}`,
63
+ type: readModel,
64
+ hasQuestionToken: true,
65
+ },
66
+ ],
67
+ returnType: `ProjectionResult<${readModel}>`,
68
+ statements: [`return /* NEW ${readModel} HERE */`],
69
+ };
70
+ };
71
+ exports.methodGenerator = {
72
+ getResourceSourceFile: getResourceSourceFileImpl,
73
+ generateReducers: generateReducersImpl,
74
+ generateProjection: generateProjectionImpl,
75
+ };
76
+ const getResourceSourceFile = (...args) => exports.methodGenerator.getResourceSourceFile(...args);
77
+ exports.getResourceSourceFile = getResourceSourceFile;
78
+ const generateReducers = (...args) => exports.methodGenerator.generateReducers(...args);
79
+ exports.generateReducers = generateReducers;
80
+ const generateProjection = (...args) => exports.methodGenerator.generateProjection(...args);
81
+ exports.generateProjection = generateProjection;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPackageManagerService = exports.makeScopedRun = void 0;
4
+ const index_js_1 = require("./index.js");
5
+ /**
6
+ * Returns a function that executes a package manager command in the project directory.
7
+ */
8
+ const makeScopedRun = (packageManagerCommand, processService, projectDirRef) => {
9
+ return async (scriptName, subscriptName, args) => {
10
+ const projectDir = projectDirRef.value || processService.cwd();
11
+ if (!projectDirRef.value) {
12
+ projectDirRef.value = projectDir;
13
+ }
14
+ return processService.exec(`${packageManagerCommand} ${scriptName} ${subscriptName ? subscriptName + ' ' : ''}${args.join(' ')}`.trim(), projectDir);
15
+ };
16
+ };
17
+ exports.makeScopedRun = makeScopedRun;
18
+ /**
19
+ * Checks if a script exists in the package.json file
20
+ */
21
+ const checkScriptExists = async (processService, fileSystemService, scriptName) => {
22
+ const pwd = processService.cwd();
23
+ const packageJson = await fileSystemService.readFileContents(`${pwd}/package.json`);
24
+ const packageJsonContents = JSON.parse(packageJson);
25
+ return !!(packageJsonContents.scripts && packageJsonContents.scripts[scriptName]);
26
+ };
27
+ const createPackageManagerService = (packageManagerCommand, deps) => {
28
+ const { processService, fileSystemService } = deps;
29
+ // Create a reference to store the current project directory
30
+ const projectDirRef = { value: '' };
31
+ // Create a function to run a script in the project directory
32
+ const run = (0, exports.makeScopedRun)(packageManagerCommand, processService, projectDirRef);
33
+ const service = {
34
+ setProjectRoot: (projectDir) => {
35
+ projectDirRef.value = projectDir;
36
+ },
37
+ runScript: async (scriptName, args) => {
38
+ try {
39
+ return await run('run', scriptName, args);
40
+ }
41
+ catch (error) {
42
+ throw new index_js_1.RunScriptError(`Failed to run script ${scriptName}`, error instanceof Error ? error : undefined);
43
+ }
44
+ },
45
+ build: async (args) => {
46
+ try {
47
+ const scriptExists = await checkScriptExists(processService, fileSystemService, 'compile');
48
+ const scriptName = scriptExists ? 'compile' : 'build';
49
+ return await run('run', scriptName, args);
50
+ }
51
+ catch (error) {
52
+ throw new index_js_1.RunScriptError('Failed to build', error instanceof Error ? error : undefined);
53
+ }
54
+ },
55
+ installProductionDependencies: async () => {
56
+ try {
57
+ await run('install', null, ['--omit=dev', '--omit=optional', '--no-bin-links']);
58
+ }
59
+ catch (error) {
60
+ throw new index_js_1.InstallDependenciesError('Failed to install production dependencies', error instanceof Error ? error : undefined);
61
+ }
62
+ },
63
+ installAllDependencies: async () => {
64
+ try {
65
+ await run('install', null, []);
66
+ }
67
+ catch (error) {
68
+ throw new index_js_1.InstallDependenciesError('Failed to install dependencies', error instanceof Error ? error : undefined);
69
+ }
70
+ },
71
+ };
72
+ return service;
73
+ };
74
+ exports.createPackageManagerService = createPackageManagerService;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RunScriptError = exports.InstallDependenciesError = void 0;
4
+ class InstallDependenciesError extends Error {
5
+ constructor(message, cause) {
6
+ super(message);
7
+ this.cause = cause;
8
+ this._tag = 'InstallDependenciesError';
9
+ this.name = 'InstallDependenciesError';
10
+ }
11
+ }
12
+ exports.InstallDependenciesError = InstallDependenciesError;
13
+ class RunScriptError extends Error {
14
+ constructor(message, cause) {
15
+ super(message);
16
+ this.cause = cause;
17
+ this._tag = 'RunScriptError';
18
+ this.name = 'RunScriptError';
19
+ }
20
+ }
21
+ exports.RunScriptError = RunScriptError;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLivePackageManager = exports.inferPackageManagerFromDirectoryContents = void 0;
4
+ const rush_impl_js_1 = require("./rush.impl.js");
5
+ const pnpm_impl_js_1 = require("./pnpm.impl.js");
6
+ const yarn_impl_js_1 = require("./yarn.impl.js");
7
+ const npm_impl_js_1 = require("./npm.impl.js");
8
+ const live_impl_js_1 = require("../file-system/live.impl.js");
9
+ const live_impl_js_2 = require("../process/live.impl.js");
10
+ const inferPackageManagerFromDirectoryContents = async (processService, fileSystemService) => {
11
+ const workingDir = processService.cwd();
12
+ const contents = await fileSystemService.readDirectoryContents(workingDir);
13
+ if (contents.includes('.rush')) {
14
+ return rush_impl_js_1.createRushPackageManager;
15
+ }
16
+ if (contents.includes('pnpm-lock.yaml')) {
17
+ return pnpm_impl_js_1.createPnpmPackageManager;
18
+ }
19
+ if (contents.includes('yarn.lock')) {
20
+ return yarn_impl_js_1.createYarnPackageManager;
21
+ }
22
+ if (contents.includes('package-lock.json')) {
23
+ return npm_impl_js_1.createNpmPackageManager;
24
+ }
25
+ // Infer npm by default
26
+ return npm_impl_js_1.createNpmPackageManager;
27
+ };
28
+ exports.inferPackageManagerFromDirectoryContents = inferPackageManagerFromDirectoryContents;
29
+ const createLivePackageManager = async () => {
30
+ const processService = live_impl_js_2.liveProcessService;
31
+ const fileSystemService = live_impl_js_1.liveFileSystemService;
32
+ const factory = await (0, exports.inferPackageManagerFromDirectoryContents)(processService, fileSystemService);
33
+ return factory({ processService, fileSystemService });
34
+ };
35
+ exports.createLivePackageManager = createLivePackageManager;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNpmPackageManager = void 0;
4
+ const common_js_1 = require("./common.js");
5
+ const createNpmPackageManager = (deps) => {
6
+ return (0, common_js_1.createPackageManagerService)('npm', deps);
7
+ };
8
+ exports.createNpmPackageManager = createNpmPackageManager;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPnpmPackageManager = void 0;
4
+ const common_js_1 = require("./common.js");
5
+ const createPnpmPackageManager = (deps) => {
6
+ return (0, common_js_1.createPackageManagerService)('pnpm', deps);
7
+ };
8
+ exports.createPnpmPackageManager = createPnpmPackageManager;