Skip to content

Commit

Permalink
chore(nx-aws-cdk): re build package and publish to version 2.0.4 (#170)
Browse files Browse the repository at this point in the history
* chore(nx-aws-cdk): re build pacakge and publish to versoin 2.0.4

* fix(nx-serverless): fix get process env

* feat(nx-serverless): update release version 3.2.6 =\> 3.2.7

* fix(core): update yarn.lock

* feat(nx-serverless): clean code
  • Loading branch information
NarongOk authored Jan 20, 2025
1 parent dbc4f30 commit 748ada8
Show file tree
Hide file tree
Showing 10 changed files with 880 additions and 1,267 deletions.
2 changes: 1 addition & 1 deletion libs/aws-cdk-stack/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@flowaccount/aws-cdk-stack",
"version": "2.0.3",
"version": "2.0.4",
"dependencies": {
"constructs": "^10.3.0",
"aws-cdk": "^2.143.1",
Expand Down
4 changes: 2 additions & 2 deletions libs/nx-serverless/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@flowaccount/nx-serverless",
"version": "99.99.99",
"version": "3.2.7",
"main": "src/index.js",
"description": "Serverless schematics for nx workspace",
"keywords": [
Expand Down Expand Up @@ -56,4 +56,4 @@
"test": "yarn nx test nx-serverless"
},
"author": "FlowAccount Co., Ltd."
}
}
124 changes: 33 additions & 91 deletions libs/nx-serverless/src/builders/build/build.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,119 +13,61 @@
// import normalizeAssetOptions from '../../utils/normalize-options';
// import { eachValueFrom } from 'rxjs-for-await';

import { convertNxExecutor, createProjectGraphAsync, ExecutorContext, logger } from '@nx/devkit'; //, runExecutor, Target
import { WebpackExecutorOptions, webpackExecutor } from '@nx/webpack';
import {
convertNxExecutor,
createProjectGraphAsync,
ExecutorContext,
logger,
} from '@nx/devkit'; //, runExecutor, Target
import { webpackExecutor } from '@nx/webpack';
import path = require('path');
import { ServerlessWrapper } from '../../utils/serverless';
import * as chalk from 'chalk';
import {
assignEntriesToFunctionsFromServerless,
// normalizeBuildOptions,
getSourceRoot,
} from '../../utils/normalize';

// export type ServerlessBuildEvent = ServerlessEventResult & {
// outfile: string;
// success: boolean;
// };

// export async function buildExecutor(
// options: BuildBuilderOptions,
// context: ExecutorContext
// ) {
// const root = getSourceRoot(context);
// options = normalizeBuildOptions(options, context.root, root);
// await ServerlessWrapper.init(options);
// options = assignEntriesToFunctionsFromServerless(options, context.root);
// options.tsConfig = consolidateExcludes(options);
// options.entry = options.files;
// const config = (<NormalizedBuildServerlessBuilderOptions>(
// options
// )).webpackConfig.reduce((currentConfig, plugin) => {
// return require(plugin)(currentConfig, {
// options,
// configuration: context.configurationName,
// });
// }, getNodeWebpackConfig(options));

// const resultCopy = copyAssetFilesSync(
// normalizeAssetOptions(options, context)
// );
// if (!resultCopy.success) {
// throw new Error(
// `Error building serverless application ${resultCopy.error}`
// );
// }
// logger.info('finished copying assets');
// logger.info('start compiling webpack');
// const iterator = eachValueFrom(
// runWebpack(config).pipe(
// tap((stats) => {
// // console.info(stats.toString(config.stats));
// if (options.statsJson) {
// const statsJsonFile = resolve(
// context.root,
// options.outputPath,
// 'stats.json'
// );
// writeFileSync(statsJsonFile, JSON.stringify(stats.toJson('verbose')));
// }
// }),
// map((stats) => {
// return {
// success: !stats.hasErrors(),
// outfile: resolve(context.root, options.outputPath),
// webpackStats: stats.toJson(config.stats),
// resolverName: 'WebpackDependencyResolver',
// tsconfig: options.tsConfig,
// } as ServerlessBuildEvent;
// }),
// catchError((e, caught) => {
// logger.error(e);
// logger.error(caught);
// return of({ success: false } as ServerlessBuildEvent);
// })
// )
// );
// const event = <ServerlessBuildEvent>(await iterator.next()).value;
// return event;
// }

import chalk from 'chalk';
import { assignEntriesToFunctionsFromServerless } from '../../utils/normalize';
import { ServerlessBuildBuilderOptions } from '../../utils/types';

export async function buildExecutor(
options: WebpackExecutorOptions,
options: ServerlessBuildBuilderOptions,
context: ExecutorContext
) {
const info = chalk.bold.green('info')
const info = chalk.bold.green('info');
const envFile: string = options.processEnvironmentFile ?? `env.json`;

//const root = getSourceRoot(context);
if(options.generatePackageJson) {
logger.info(`${info} creating projectGraph`)
if (options.generatePackageJson) {
logger.info(`${info} creating projectGraph`);
context.projectGraph = await createProjectGraphAsync();
}
logger.info(`${info} initialing serverless configurations`)
await ServerlessWrapper.init(context, 'env.json');
logger.info(`${info} initialing serverless configurations`);
await ServerlessWrapper.init(context, envFile);
const handlerEntries = assignEntriesToFunctionsFromServerless(context);
options.main = handlerEntries.shift().entryPath;
if(handlerEntries.length > 0) {
if (handlerEntries.length > 0) {
options.additionalEntryPoints = handlerEntries;
}
const mainFileName = options.main.split('/')[options.main.split('/').length - 1].replace('.ts', '.js');
console.log(options.main , mainFileName, options.additionalEntryPoints );
console.log(options.outputPath)
options.compiler = 'swc';
const mainFileName = options.main
.split('/')
[options.main.split('/').length - 1].replace('.ts', '.js');
console.log(options.main, mainFileName, options.additionalEntryPoints);
console.log(options.outputPath);
options.compiler = 'swc';
options.outputFileName = mainFileName;
options.target = 'node';
options.runtimeChunk = false;
options.commonChunk = false;
options.outputHashing = 'none';
options.progress = true;
options.standardWebpackConfigFunction = false
options.webpackConfig = path.join(__dirname, '..', '..', 'webpack/webpack.config.js');
options.standardWebpackConfigFunction = false;
options.webpackConfig = path.join(
__dirname,
'..',
'..',
'webpack/webpack.config.js'
);
logger.info(`${info} start compiling webpack`);
const result = await webpackExecutor(options,context).next();
const result = await webpackExecutor(options, context).next();
return result.value;
}

export default buildExecutor;
export const serverlessBuilder = convertNxExecutor(buildExecutor);

56 changes: 24 additions & 32 deletions libs/nx-serverless/src/builders/deploy/deploy.impl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
/* Fix for EMFILE: too many open files on serverless deploy */
import * as fs from 'fs';
import * as gracefulFs from 'graceful-fs'; // TODO: 0 this is not needed here anymore?
import { runWaitUntilTargets, startBuild } from '../../utils/target.schedulers';
import { ExecutorContext, logger } from '@nx/devkit';
import {
Expand All @@ -11,22 +8,17 @@ import {
import { ScullyBuilderOptions } from '../scully/scully.impl';
import { detectPackageManager } from '@nx/devkit';
import { getProjectConfiguration, getProjectRoot } from '../../utils/normalize';
import * as chalk from 'chalk';
import * as dotEnvJson from 'dotenv-json';
import chalk from 'chalk';
import dotEnvJson from 'dotenv-json';

import { execSync } from 'child_process';

// import { WebpackExecutorOptions } from '@nx/webpack';

import { NX_SERVERLESS_BUILD_TARGET_KEY } from '../../nrwl/nx-facade';
import { NPM } from '../../utils/packagers/npm';
import { Yarn } from '../../utils/packagers/yarn';
import { packager } from '../../utils/packagers';
import { WebpackExecutorOptions } from '@nx/webpack';

gracefulFs.gracefulify(fs); // TODO: 0 this is not needed here anymore?
/* Fix for EMFILE: too many open files on serverless deploy */

function getSlsCommand() {
const packageManager = detectPackageManager();
switch (packageManager) {
Expand All @@ -40,11 +32,11 @@ function getSlsCommand() {

function getBuildTargetConfiguration(
targetName: string,
context: ExecutorContext,
context: ExecutorContext
): WebpackExecutorOptions {
const projectConfig = getProjectConfiguration(context);

const targetSplit = targetName.split(':')
const targetSplit = targetName.split(':');
const finalName = targetSplit[1];
const configuration = targetSplit[2];

Expand All @@ -60,7 +52,7 @@ function getBuildTargetConfiguration(
throw new Error(`Build target '${targetName}' `);
}

function getPackagerInstance(options){
function getPackagerInstance(options) {
let packagerInstance = null;
if (options.packager && options.packager.toString().toLowerCase() == 'npm') {
packagerInstance = NPM;
Expand All @@ -87,8 +79,6 @@ export async function deployExecutor(
options: ServerlessDeployBuilderOptions,
context: ExecutorContext
) {


// const { target, project, configuration } = parseTargetString(options.buildTarget, context);
// const root = getSourceRoot(context);

Expand All @@ -104,9 +94,9 @@ export async function deployExecutor(
// root
// );
const projectRoot = getProjectRoot(context);
const info = chalk.bold.green('info')
const info = chalk.bold.green('info');
dotEnvJson({
path: `${projectRoot}/${options.processEnvironmentFile ?? 'env.json'}`
path: `${projectRoot}/${options.processEnvironmentFile ?? 'env.json'}`,
});

if (!options.skipBuild) {
Expand All @@ -126,8 +116,7 @@ export async function deployExecutor(
}
const iterator = await buildTarget(options, context);
const buildOutput = <SimpleBuildEvent>(await iterator.next()).value;
if(buildOutput.error)
{
if (buildOutput.error) {
throw new Error(buildOutput.error);
}
}
Expand All @@ -148,22 +137,25 @@ export async function deployExecutor(
//const npxPath = path.resolve(context.root, 'node_modules/serverless', 'bin', 'serverless.js');
try {
const packagerInstance = getPackagerInstance(options);
logger.info(`${info} installing yarn on ${context.root}/${buildConfig.outputPath}`);
const result = await packagerInstance.install(`${context.root}/${buildConfig.outputPath}`);
logger.info(
`${info} installing yarn on ${context.root}/${buildConfig.outputPath}`
);
const result = await packagerInstance.install(
`${context.root}/${buildConfig.outputPath}`
);
if (result.error) {
logger.error('ERROR: generating lock file!');
return { success: false, error: result.error.toString() };
}
execSync(fullCommand,
{
stdio: 'inherit',
cwd: projectRoot,
env: {
FORCE_COLOR: 'true',
NODE_OPTIONS: '--enable-source-maps',
...process.env,
[NX_SERVERLESS_BUILD_TARGET_KEY]: options.buildTarget,
}
execSync(fullCommand, {
stdio: 'inherit',
cwd: projectRoot,
env: {
FORCE_COLOR: 'true',
NODE_OPTIONS: '--enable-source-maps',
...process.env,
[NX_SERVERLESS_BUILD_TARGET_KEY]: options.buildTarget,
},
});
} catch (error) {
logger.error(error);
Expand All @@ -176,7 +168,7 @@ export async function deployExecutor(
}

export async function* buildTarget(
options:
options:
| ServerlessDeployBuilderOptions
| ServerlessSlsBuilderOptions
| ScullyBuilderOptions,
Expand Down
4 changes: 2 additions & 2 deletions libs/nx-serverless/src/builders/offline/offline.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import treeKill from 'tree-kill';
import { runWaitUntilTargets, startBuild } from '../../utils/target.schedulers';
import { ExecutorContext, logger } from '@nx/devkit';
import { promisify } from 'util';
import * as dotEnvJson from 'dotenv-json';
import dotEnvJson from 'dotenv-json';
import {
InspectType,
ServerlessExecutorOptions,
SimpleBuildEvent,
} from '../../utils/types';
import { getSlsCommand } from '../../utils/packagers';
import * as path from 'node:path';
import * as chalk from 'chalk';
import chalk from 'chalk';
import { getProjectRoot } from '../../utils/normalize';
import { NX_SERVERLESS_BUILD_TARGET_KEY } from '../../nrwl/nx-facade';
import * as dotfile from 'dotenv';
Expand Down
Loading

0 comments on commit 748ada8

Please sign in to comment.