carlin 3.0.1 → 3.1.0

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 (2) hide show
  1. package/dist/index.mjs +206 -123
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -2393,7 +2393,7 @@ const logPrefix$15 = "lambda";
2393
2393
  * which reduces the payload size when deploying the Lambda function. The file
2394
2394
  * extension of the output files will be `.mjs` for ESM and `.cjs` for CJS.
2395
2395
  */
2396
- const buildLambdaCode = async ({ lambdaEntryPoints, lambdaEntryPointsBaseDir = ".", lambdaExternal = [], lambdaFormat = "esm", lambdaOutdir }) => {
2396
+ const buildLambdaCode = async ({ lambdaEntryPoints, lambdaEntryPointsBaseDir = ".", lambdaExternal = [], lambdaFormat = "esm", lambdaOutdir, lambdaSourcemap = false }) => {
2397
2397
  log.info(logPrefix$15, "Building Lambda single file...");
2398
2398
  /**
2399
2399
  * Remove the output directory if it exists to not mix old files with the
@@ -2422,6 +2422,16 @@ const buildLambdaCode = async ({ lambdaEntryPoints, lambdaEntryPointsBaseDir = "
2422
2422
  */
2423
2423
  minifySyntax: true,
2424
2424
  platform: "node",
2425
+ /**
2426
+ * Node applies the map only with `--enable-source-maps`, which
2427
+ * `addSourceMapsNodeOptions` sets on every function. Without
2428
+ * `sourcesContent`: Node maps a frame from names and lines alone, and the
2429
+ * source text would only grow the zip.
2430
+ */
2431
+ ...lambdaSourcemap ? {
2432
+ sourcemap: "linked",
2433
+ sourcesContent: false
2434
+ } : {},
2425
2435
  splitting: lambdaFormat === "esm",
2426
2436
  outbase: path.join(process.cwd(), lambdaEntryPointsBaseDir),
2427
2437
  outdir: path.join(process.cwd(), lambdaOutdir),
@@ -2604,7 +2614,7 @@ const uploadCodeToS3 = async ({ stackName, lambdaOutdir }) => {
2604
2614
  //#endregion
2605
2615
  //#region src/deploy/lambda/deployLambdaCode.ts
2606
2616
  const logPrefix$11 = "lambda";
2607
- const deployLambdaCode = async ({ lambdaDockerfile, lambdaExternal = [], lambdaImage, lambdaEntryPoints, lambdaEntryPointsBaseDir = "src", lambdaFormat, lambdaOutdir = "out", stackName }) => {
2617
+ const deployLambdaCode = async ({ lambdaDockerfile, lambdaExternal = [], lambdaImage, lambdaEntryPoints, lambdaEntryPointsBaseDir = "src", lambdaFormat, lambdaOutdir = "out", lambdaSourcemap, stackName }) => {
2608
2618
  if (!lambdaEntryPoints.length) return {};
2609
2619
  log.info(logPrefix$11, "Deploying Lambda code...");
2610
2620
  for (const entryPoint of lambdaEntryPoints) {
@@ -2616,7 +2626,8 @@ const deployLambdaCode = async ({ lambdaDockerfile, lambdaExternal = [], lambdaI
2616
2626
  lambdaEntryPoints,
2617
2627
  lambdaEntryPointsBaseDir,
2618
2628
  lambdaFormat,
2619
- lambdaOutdir
2629
+ lambdaOutdir,
2630
+ lambdaSourcemap
2620
2631
  });
2621
2632
  const { bucket, key, versionId } = await uploadCodeToS3({
2622
2633
  stackName,
@@ -2927,6 +2938,27 @@ const findAndReadCloudFormationTemplate = async ({ templatePath: defaultTemplate
2927
2938
  });
2928
2939
  };
2929
2940
  //#endregion
2941
+ //#region src/deploy/lambda/addSourceMapsNodeOptions.ts
2942
+ const FLAG = "--enable-source-maps";
2943
+ /**
2944
+ * Sets `NODE_OPTIONS=--enable-source-maps` on every Lambda function, the flag
2945
+ * that makes Node read the source map `buildLambdaCode` ships. A string
2946
+ * `NODE_OPTIONS` already set keeps its flags; one set with an intrinsic
2947
+ * function is left alone, since it cannot be read before deploy.
2948
+ */
2949
+ const addSourceMapsNodeOptions = (template) => {
2950
+ for (const resource of Object.values(template.Resources)) {
2951
+ if (!["AWS::Lambda::Function", "AWS::Serverless::Function"].includes(resource.Type)) continue;
2952
+ resource.Properties = resource.Properties ?? {};
2953
+ resource.Properties.Environment = resource.Properties.Environment ?? {};
2954
+ const variables = resource.Properties.Environment.Variables ?? {};
2955
+ resource.Properties.Environment.Variables = variables;
2956
+ const current = variables.NODE_OPTIONS;
2957
+ if (current === void 0) variables.NODE_OPTIONS = FLAG;
2958
+ else if (typeof current === "string" && !current.includes(FLAG)) variables.NODE_OPTIONS = `${current} ${FLAG}`.trim();
2959
+ }
2960
+ };
2961
+ //#endregion
2930
2962
  //#region src/deploy/lambda/getLambdaEntryPointsFromTemplate.ts
2931
2963
  const getLambdaEntryPointsFromTemplate = (template) => {
2932
2964
  return Object.keys(template.Resources).filter((key) => {
@@ -2980,34 +3012,127 @@ const getCloudformationTemplateOptions = ({ cliOptions, stackName }) => {
2980
3012
  projectName: getProjectName()
2981
3013
  };
2982
3014
  };
2983
- const deployCloudFormation = async (cliOptions) => {
2984
- try {
2985
- const { lambdaDockerfile, lambdaEntryPoints, lambdaEntryPointsBaseDir, lambdaImage, lambdaExternal, lambdaFormat, lambdaOutdir, parameters, template, templatePath } = cliOptions;
2986
- const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$8 });
2987
- const cloudFormationTemplate = await (async () => {
2988
- if (template) return { ...template };
2989
- return findAndReadCloudFormationTemplate({
2990
- templatePath,
2991
- options: getCloudformationTemplateOptions({
2992
- stackName,
2993
- cliOptions
2994
- })
2995
- });
2996
- })();
3015
+ const getParameterType = (parameter) => {
3016
+ if (typeof parameter.value === "string") return "String";
3017
+ if (typeof parameter.value === "number") return "Number";
3018
+ throw new Error(`Parameter assertion failed. Parameter ${parameter.key} value ${parameter.value} is not mapped.`);
3019
+ };
3020
+ /**
3021
+ * Add Parameters passed on CLI to CloudFormation template if they don't exist.
3022
+ * Also, automatically add the Type of the parameter.
3023
+ */
3024
+ const addCliParametersToTemplate = ({ template, parameters = [] }) => {
3025
+ for (const parameter of parameters) {
3026
+ if (template.Parameters?.[parameter.key]) continue;
3027
+ template.Parameters = {
3028
+ ...template.Parameters,
3029
+ [parameter.key]: { Type: getParameterType(parameter) }
3030
+ };
3031
+ }
3032
+ };
3033
+ /**
3034
+ * Add `Code` property to every AWS::Lambda::Function resource or `CodeUri`
3035
+ * property to every AWS::Serverless::Function resource if they are NOT
3036
+ * already defined.
3037
+ */
3038
+ const addLambdaCodeToResources = (template) => {
3039
+ for (const resource of Object.values(template.Resources)) {
3040
+ if (resource.Type === "AWS::Lambda::Function" && !resource.Properties?.Code) resource.Properties = {
3041
+ ...resource.Properties,
3042
+ Code: {
3043
+ S3Bucket: { Ref: "LambdaS3Bucket" },
3044
+ S3Key: { Ref: "LambdaS3Key" },
3045
+ S3ObjectVersion: { Ref: "LambdaS3ObjectVersion" }
3046
+ }
3047
+ };
3048
+ if (resource.Type === "AWS::Serverless::Function" && !resource.Properties?.CodeUri) resource.Properties = {
3049
+ ...resource.Properties,
3050
+ CodeUri: {
3051
+ Bucket: { Ref: "LambdaS3Bucket" },
3052
+ Key: { Ref: "LambdaS3Key" },
3053
+ Version: { Ref: "LambdaS3ObjectVersion" }
3054
+ }
3055
+ };
3056
+ }
3057
+ };
3058
+ const addLambdaS3Parameters = ({ template, params, bucket, key, versionId }) => {
3059
+ template.Parameters = {
3060
+ LambdaS3Bucket: { Type: "String" },
3061
+ LambdaS3Key: { Type: "String" },
3062
+ LambdaS3ObjectVersion: { Type: "String" },
3063
+ ...template.Parameters
3064
+ };
3065
+ params.Parameters.push(
3066
+ {
3067
+ ParameterKey: "LambdaS3Bucket",
3068
+ ParameterValue: bucket
3069
+ },
3070
+ {
3071
+ ParameterKey: "LambdaS3Key",
3072
+ ParameterValue: key
3073
+ },
2997
3074
  /**
2998
- * Add Parameters passed on CLI to CloudFormation template if they don't exist.
2999
- * Also, automatically add the Type of the parameter.
3075
+ * Used by CloudFormation AWS::Lambda::Function
3076
+ * @see {@link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html}
3077
+ * and by CloudFormation AWS::Serverless::Function
3078
+ * @see {@link https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-functioncode.html}
3000
3079
  */
3001
- if (parameters) for (const parameter of parameters) {
3002
- if (cloudFormationTemplate.Parameters?.[parameter.key]) continue;
3003
- if (!cloudFormationTemplate.Parameters) cloudFormationTemplate.Parameters = {};
3004
- const type = (() => {
3005
- if (typeof parameter.value === "string") return "String";
3006
- if (typeof parameter.value === "number") return "Number";
3007
- throw new Error(`Parameter assertion failed. Parameter ${parameter.key} value ${parameter.value} is not mapped.`);
3008
- })();
3009
- cloudFormationTemplate.Parameters[parameter.key] = { Type: type };
3080
+ {
3081
+ ParameterKey: "LambdaS3ObjectVersion",
3082
+ ParameterValue: versionId
3010
3083
  }
3084
+ );
3085
+ addLambdaCodeToResources(template);
3086
+ };
3087
+ const deployCloudFormationLambdaCode = async ({ template, params, stackName, cliOptions }) => {
3088
+ const { lambdaEntryPoints, lambdaSourcemap } = cliOptions;
3089
+ const finalLambdaEntryPoints = lambdaEntryPoints && lambdaEntryPoints.length > 0 ? lambdaEntryPoints : getLambdaEntryPointsFromTemplate(template);
3090
+ const response = await deployLambdaCode({
3091
+ lambdaDockerfile: cliOptions.lambdaDockerfile,
3092
+ lambdaExternal: cliOptions.lambdaExternal,
3093
+ lambdaEntryPoints: finalLambdaEntryPoints,
3094
+ lambdaEntryPointsBaseDir: cliOptions.lambdaEntryPointsBaseDir,
3095
+ lambdaFormat: cliOptions.lambdaFormat,
3096
+ lambdaImage: cliOptions.lambdaImage,
3097
+ lambdaOutdir: cliOptions.lambdaOutdir,
3098
+ lambdaSourcemap,
3099
+ stackName
3100
+ });
3101
+ if (lambdaSourcemap && finalLambdaEntryPoints.length > 0) addSourceMapsNodeOptions(template);
3102
+ if (!response) return;
3103
+ const { bucket, key, versionId, imageUri } = response;
3104
+ if (imageUri) {
3105
+ template.Parameters = {
3106
+ LambdaImageUri: { Type: "String" },
3107
+ ...template.Parameters
3108
+ };
3109
+ params.Parameters.push({
3110
+ ParameterKey: "LambdaImageUri",
3111
+ ParameterValue: imageUri
3112
+ });
3113
+ } else if (bucket && key && versionId) addLambdaS3Parameters({
3114
+ template,
3115
+ params,
3116
+ bucket,
3117
+ key,
3118
+ versionId
3119
+ });
3120
+ };
3121
+ const deployCloudFormation = async (cliOptions) => {
3122
+ try {
3123
+ const { parameters, template, templatePath } = cliOptions;
3124
+ const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$8 });
3125
+ const cloudFormationTemplate = template ? { ...template } : await findAndReadCloudFormationTemplate({
3126
+ templatePath,
3127
+ options: getCloudformationTemplateOptions({
3128
+ stackName,
3129
+ cliOptions
3130
+ })
3131
+ });
3132
+ addCliParametersToTemplate({
3133
+ template: cloudFormationTemplate,
3134
+ parameters
3135
+ });
3011
3136
  await validateTemplate({
3012
3137
  stackName,
3013
3138
  template: cloudFormationTemplate
@@ -3023,96 +3148,12 @@ const deployCloudFormation = async (cliOptions) => {
3023
3148
  };
3024
3149
  }) || []
3025
3150
  };
3026
- const deployCloudFormationDeployLambdaCode = async () => {
3027
- const response = await deployLambdaCode({
3028
- lambdaDockerfile,
3029
- lambdaExternal,
3030
- lambdaEntryPoints: (() => {
3031
- if (lambdaEntryPoints && lambdaEntryPoints.length > 0) return lambdaEntryPoints;
3032
- return getLambdaEntryPointsFromTemplate(cloudFormationTemplate);
3033
- })(),
3034
- lambdaEntryPointsBaseDir,
3035
- lambdaFormat,
3036
- lambdaImage,
3037
- lambdaOutdir,
3038
- stackName
3039
- });
3040
- if (response) {
3041
- const { bucket, key, versionId, imageUri } = response;
3042
- if (imageUri) {
3043
- cloudFormationTemplate.Parameters = {
3044
- LambdaImageUri: { Type: "String" },
3045
- ...cloudFormationTemplate.Parameters
3046
- };
3047
- params.Parameters.push({
3048
- ParameterKey: "LambdaImageUri",
3049
- ParameterValue: imageUri
3050
- });
3051
- } else if (bucket && key && versionId) {
3052
- /**
3053
- * Add Parameters to CloudFormation template.
3054
- */
3055
- cloudFormationTemplate.Parameters = {
3056
- LambdaS3Bucket: { Type: "String" },
3057
- LambdaS3Key: { Type: "String" },
3058
- LambdaS3ObjectVersion: { Type: "String" },
3059
- ...cloudFormationTemplate.Parameters
3060
- };
3061
- /**
3062
- * Add S3Bucket and S3Key to params.
3063
- */
3064
- params.Parameters.push(
3065
- {
3066
- ParameterKey: "LambdaS3Bucket",
3067
- ParameterValue: bucket
3068
- },
3069
- {
3070
- ParameterKey: "LambdaS3Key",
3071
- ParameterValue: key
3072
- },
3073
- /**
3074
- * Used by CloudFormation AWS::Lambda::Function
3075
- * @see {@link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html}
3076
- * and by CloudFormation AWS::Serverless::Function
3077
- * @see {@link https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-functioncode.html}
3078
- */
3079
- {
3080
- ParameterKey: "LambdaS3ObjectVersion",
3081
- ParameterValue: versionId
3082
- }
3083
- );
3084
- /**
3085
- * Add `Code` property to every AWS::Lambda::Function resource or
3086
- * `CodeUri` property to every AWS::Serverless::Function resource if
3087
- * they are NOT already defined.
3088
- */
3089
- for (const key of Object.keys(cloudFormationTemplate.Resources)) {
3090
- const resource = cloudFormationTemplate.Resources[key];
3091
- if (resource.Type === "AWS::Lambda::Function") {
3092
- if (!resource.Properties?.Code) resource.Properties = {
3093
- ...resource.Properties,
3094
- Code: {
3095
- S3Bucket: { Ref: "LambdaS3Bucket" },
3096
- S3Key: { Ref: "LambdaS3Key" },
3097
- S3ObjectVersion: { Ref: "LambdaS3ObjectVersion" }
3098
- }
3099
- };
3100
- }
3101
- if (resource.Type === "AWS::Serverless::Function") {
3102
- if (!resource.Properties?.CodeUri) resource.Properties = {
3103
- ...resource.Properties,
3104
- CodeUri: {
3105
- Bucket: { Ref: "LambdaS3Bucket" },
3106
- Key: { Ref: "LambdaS3Key" },
3107
- Version: { Ref: "LambdaS3ObjectVersion" }
3108
- }
3109
- };
3110
- }
3111
- }
3112
- }
3113
- }
3114
- };
3115
- await deployCloudFormationDeployLambdaCode();
3151
+ await deployCloudFormationLambdaCode({
3152
+ template: cloudFormationTemplate,
3153
+ params,
3154
+ stackName,
3155
+ cliOptions
3156
+ });
3116
3157
  return await deploy({
3117
3158
  params,
3118
3159
  template: cloudFormationTemplate
@@ -3763,12 +3804,37 @@ const BUCKET_CORS_CONFIGURATION = { CorsRules: [{
3763
3804
  Id: "OpenCors",
3764
3805
  MaxAge: 600
3765
3806
  }] };
3807
+ const CLOUDFRONT_CACHE_POLICY_LOGICAL_ID = "CachePolicy";
3766
3808
  /**
3767
- * Name: Managed-CachingDisabled
3768
- * ID: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
3769
- * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html
3809
+ * CloudFront compresses only when the cache policy accepts gzip/brotli, which
3810
+ * `Managed-CachingDisabled` cannot. Each deploy invalidates `/*`.
3811
+ *
3812
+ * `Managed-CachingOptimized` would leave `Origin` and the
3813
+ * `Access-Control-Request-*` headers out of the cache key, so a response cached
3814
+ * for a same-origin request would answer a CORS one without CORS headers when
3815
+ * they come from the bucket (`vary` in `responseHeaders`).
3816
+ *
3817
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html
3770
3818
  */
3771
- const CACHE_POLICY_ID = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
3819
+ const CACHE_POLICY_CONFIG = {
3820
+ DefaultTTL: 3600 * 24,
3821
+ MaxTTL: 3600 * 24 * 365,
3822
+ MinTTL: 0,
3823
+ ParametersInCacheKeyAndForwardedToOrigin: {
3824
+ CookiesConfig: { CookieBehavior: "none" },
3825
+ EnableAcceptEncodingBrotli: true,
3826
+ EnableAcceptEncodingGzip: true,
3827
+ HeadersConfig: {
3828
+ HeaderBehavior: "whitelist",
3829
+ Headers: [
3830
+ "Access-Control-Request-Headers",
3831
+ "Access-Control-Request-Method",
3832
+ "Origin"
3833
+ ]
3834
+ },
3835
+ QueryStringsConfig: { QueryStringBehavior: "none" }
3836
+ }
3837
+ };
3772
3838
  /**
3773
3839
  * Name: Managed-CORS-S3Origin
3774
3840
  * ID: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf
@@ -3922,7 +3988,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, redirectToT
3922
3988
  * CachePolicyId property:
3923
3989
  * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-cachepolicyid
3924
3990
  */
3925
- CachePolicyId: CACHE_POLICY_ID,
3991
+ CachePolicyId: { Ref: CLOUDFRONT_CACHE_POLICY_LOGICAL_ID },
3926
3992
  ResponseHeadersPolicyId: getResponseHeadersPolicyId({
3927
3993
  responseHeaders,
3928
3994
  responseHeadersPolicy
@@ -3944,6 +4010,18 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, redirectToT
3944
4010
  }]
3945
4011
  } }
3946
4012
  },
4013
+ [CLOUDFRONT_CACHE_POLICY_LOGICAL_ID]: {
4014
+ Type: "AWS::CloudFront::CachePolicy",
4015
+ Properties: { CachePolicyConfig: {
4016
+ ...CACHE_POLICY_CONFIG,
4017
+ Comment: { "Fn::Sub": ["Cache policy for ${Project} project.", { Project: { Ref: "Project" } }] },
4018
+ /**
4019
+ * Cache policy names must be unique per AWS account, like the
4020
+ * response headers policy's.
4021
+ */
4022
+ Name: { Ref: "AWS::StackName" }
4023
+ } }
4024
+ },
3947
4025
  [CLOUDFRONT_ORIGIN_ACCESS_CONTROL_LOGICAL_ID]: {
3948
4026
  Type: "AWS::CloudFront::OriginAccessControl",
3949
4027
  Properties: { OriginAccessControlConfig: {
@@ -4701,6 +4779,11 @@ const options$2 = {
4701
4779
  describe: "Output directory for built Lambda code.",
4702
4780
  type: "string"
4703
4781
  },
4782
+ "lambda-sourcemap": {
4783
+ default: false,
4784
+ describe: "Ship a source map with the Lambda bundle and set NODE_OPTIONS=--enable-source-maps, so stack traces point at source files.",
4785
+ type: "boolean"
4786
+ },
4704
4787
  "lambda-runtime": {
4705
4788
  choices: [
4706
4789
  "nodejs20.x",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "homepage": "https://ttoss.dev/docs/carlin/",
@@ -57,8 +57,8 @@
57
57
  "ts-node": "^10.9.2",
58
58
  "uglify-js": "^3.19.3",
59
59
  "yargs": "^17.7.2",
60
- "@ttoss/cloudformation": "^0.16.1",
61
60
  "@ttoss/config": "^1.41.0",
61
+ "@ttoss/cloudformation": "^0.16.1",
62
62
  "@ttoss/read-config-file": "^2.5.1"
63
63
  },
64
64
  "devDependencies": {