carlin 2.0.0 → 2.2.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 +360 -10
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -3370,11 +3370,256 @@ const invalidateCloudFront = async ({ outputs }) => {
3370
3370
  } else log.info(logPrefix$5, `Cannot invalidate because distribution does not exist.`);
3371
3371
  };
3372
3372
  //#endregion
3373
+ //#region src/deploy/staticApp/responseHeaders.ts
3374
+ /**
3375
+ * The header names emitted by the `SecurityHeadersConfig` of the baseline
3376
+ * policy, mapped to the config key that emits them. Each key is optional in
3377
+ * `SecurityHeadersConfig`, so a user-defined header of the same name replaces
3378
+ * the baseline one by removing the key.
3379
+ */
3380
+ const SECURITY_HEADERS_CONFIG_KEYS = {
3381
+ "content-security-policy": "ContentSecurityPolicy",
3382
+ "referrer-policy": "ReferrerPolicy",
3383
+ "strict-transport-security": "StrictTransportSecurity",
3384
+ "x-content-type-options": "ContentTypeOptions",
3385
+ "x-frame-options": "FrameOptions",
3386
+ "x-xss-protection": "XSSProtection"
3387
+ };
3388
+ /**
3389
+ * The header names emitted by the `CorsConfig` of the baseline policy.
3390
+ * `CorsConfig` requires its fields as a unit, so a single header cannot be
3391
+ * replaced without inventing semantics for the others. Defining one of these
3392
+ * is an error instead.
3393
+ */
3394
+ const CORS_CONFIG_HEADERS = [
3395
+ "access-control-allow-credentials",
3396
+ "access-control-allow-headers",
3397
+ "access-control-allow-methods",
3398
+ "access-control-allow-origin",
3399
+ "access-control-expose-headers",
3400
+ "access-control-max-age"
3401
+ ];
3402
+ /**
3403
+ * https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
3404
+ */
3405
+ const HEADER_NAME_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
3406
+ /**
3407
+ * Configuration of the managed policy
3408
+ * `CORS-with-preflight-and-SecurityHeadersPolicy`
3409
+ * (`eaab4381-ed33-4a86-88ca-d9558dc6cd63`), which every static app deploy has
3410
+ * used since CloudFront support was added.
3411
+ *
3412
+ * A custom policy replaces the managed one instead of extending it, so the
3413
+ * managed settings are reproduced here to keep deploys that define response
3414
+ * headers equivalent to the ones that don't.
3415
+ *
3416
+ * Transcribed 2026-08-22 from
3417
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html
3418
+ *
3419
+ * `AccessControlAllowHeaders` is required by CloudFormation but isn't listed
3420
+ * on that page. It mirrors the `AllowedHeaders` of the bucket CORS rules.
3421
+ *
3422
+ * Note the `Override` flags are not uniform: `X-Content-Type-Options` is the
3423
+ * only header the managed policy overrides the origin for.
3424
+ */
3425
+ const BASELINE_RESPONSE_HEADERS_CONFIG = {
3426
+ CorsConfig: {
3427
+ AccessControlAllowCredentials: false,
3428
+ AccessControlAllowHeaders: { Items: ["*"] },
3429
+ AccessControlAllowMethods: { Items: [
3430
+ "DELETE",
3431
+ "GET",
3432
+ "HEAD",
3433
+ "OPTIONS",
3434
+ "PATCH",
3435
+ "POST",
3436
+ "PUT"
3437
+ ] },
3438
+ AccessControlAllowOrigins: { Items: ["*"] },
3439
+ AccessControlExposeHeaders: { Items: ["*"] },
3440
+ OriginOverride: false
3441
+ },
3442
+ SecurityHeadersConfig: {
3443
+ ReferrerPolicy: {
3444
+ Override: false,
3445
+ ReferrerPolicy: "strict-origin-when-cross-origin"
3446
+ },
3447
+ StrictTransportSecurity: {
3448
+ AccessControlMaxAgeSec: 31536e3,
3449
+ IncludeSubdomains: false,
3450
+ Override: false,
3451
+ Preload: false
3452
+ },
3453
+ ContentTypeOptions: { Override: true },
3454
+ FrameOptions: {
3455
+ FrameOption: "SAMEORIGIN",
3456
+ Override: false
3457
+ },
3458
+ XSSProtection: {
3459
+ ModeBlock: true,
3460
+ Override: false,
3461
+ Protection: true
3462
+ }
3463
+ }
3464
+ };
3465
+ const validateResponseHeaders = (responseHeaders) => {
3466
+ const seen = /* @__PURE__ */ new Set();
3467
+ for (const { header } of responseHeaders) {
3468
+ if (!header || !HEADER_NAME_REGEX.test(header)) throw new Error(`"${header}" is not a valid HTTP header name for the response-headers option.`);
3469
+ const headerLowerCase = header.toLowerCase();
3470
+ if (seen.has(headerLowerCase)) throw new Error(`The response header "${header}" was defined more than once. Header names are case-insensitive.`);
3471
+ seen.add(headerLowerCase);
3472
+ if (CORS_CONFIG_HEADERS.includes(headerLowerCase)) throw new Error(`The response header "${header}" is part of the CORS configuration and cannot be defined by the response-headers option. Use the response-headers-policy option to take full control of the policy.`);
3473
+ }
3474
+ };
3475
+ /**
3476
+ * Normalizes the `response-headers` option into a list of headers.
3477
+ *
3478
+ * Accepts the object form, which is the one to prefer:
3479
+ *
3480
+ * ```ts
3481
+ * {
3482
+ * 'content-security-policy': "default-src 'self'",
3483
+ * }
3484
+ * ```
3485
+ *
3486
+ * And the array form, needed only to set `override` per header:
3487
+ *
3488
+ * ```ts
3489
+ * [
3490
+ * { header: 'content-security-policy', value: "default-src 'self'", override: false },
3491
+ * ]
3492
+ * ```
3493
+ */
3494
+ const parseResponseHeaders = (arg) => {
3495
+ if (!arg) return [];
3496
+ const responseHeaders = Array.isArray(arg) ? arg.map(({ header, value, override = true }) => {
3497
+ return {
3498
+ header,
3499
+ value,
3500
+ override
3501
+ };
3502
+ }) : Object.entries(arg).map(([header, value]) => {
3503
+ return {
3504
+ header,
3505
+ value: String(value),
3506
+ override: true
3507
+ };
3508
+ });
3509
+ validateResponseHeaders(responseHeaders);
3510
+ return responseHeaders;
3511
+ };
3512
+ /**
3513
+ * Builds the `ResponseHeadersPolicyConfig` of the policy created when the
3514
+ * response-headers option is defined: the baseline managed policy settings
3515
+ * with the user-defined headers layered on top.
3516
+ */
3517
+ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
3518
+ const securityHeadersConfig = { ...BASELINE_RESPONSE_HEADERS_CONFIG.SecurityHeadersConfig };
3519
+ /**
3520
+ * A user-defined header replaces the baseline one instead of being emitted
3521
+ * alongside it.
3522
+ */
3523
+ for (const { header } of responseHeaders) {
3524
+ const securityHeadersConfigKey = SECURITY_HEADERS_CONFIG_KEYS[header.toLowerCase()];
3525
+ if (securityHeadersConfigKey) delete securityHeadersConfig[securityHeadersConfigKey];
3526
+ }
3527
+ return {
3528
+ Comment: { "Fn::Sub": ["Response headers policy for ${Project} project.", { Project: { Ref: "Project" } }] },
3529
+ CorsConfig: BASELINE_RESPONSE_HEADERS_CONFIG.CorsConfig,
3530
+ CustomHeadersConfig: { Items: responseHeaders.map(({ header, value, override }) => {
3531
+ return {
3532
+ Header: header,
3533
+ Override: override,
3534
+ Value: value
3535
+ };
3536
+ }) },
3537
+ /**
3538
+ * Response headers policy names must be unique per AWS account. Static app
3539
+ * deploys are always in us-east-1, so the stack name cannot collide with a
3540
+ * same-named stack in another region.
3541
+ */
3542
+ Name: { Ref: "AWS::StackName" },
3543
+ ...Object.keys(securityHeadersConfig).length > 0 ? { SecurityHeadersConfig: securityHeadersConfig } : {}
3544
+ };
3545
+ };
3546
+ //#endregion
3547
+ //#region src/deploy/staticApp/viewerRequestFunction.ts
3548
+ /**
3549
+ * Maximum size of a CloudFront Function, in bytes.
3550
+ *
3551
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-function-quotas.html
3552
+ */
3553
+ const MAX_FUNCTION_SIZE_BYTES = 10 * 1024;
3554
+ /**
3555
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html
3556
+ */
3557
+ const FUNCTION_RUNTIME = "cloudfront-js-2.0";
3558
+ /**
3559
+ * `appendIndexHtml` injected into every app-supplied viewer request function.
3560
+ *
3561
+ * A cache behavior takes a single viewer request function, so an app that
3562
+ * supplies its own cannot also associate the shared `AppendIndexDotHtml` of the
3563
+ * base stack. Composing the two by concatenating their sources would not work
3564
+ * either: both would declare `handler`, and the later declaration would win
3565
+ * silently, dropping one of the behaviors.
3566
+ *
3567
+ * Injecting the logic as a named helper instead leaves a single `handler` in the
3568
+ * composed source and makes the order explicit at the call site, which is where
3569
+ * it matters — a function rewriting `/docs/x` to `/docs/x.md` must run before
3570
+ * the index appending, one rewriting `/docs/x` to `/x/docs` after it.
3571
+ *
3572
+ * The body is the base stack `AppendIndexDotHtml` function
3573
+ * (`getCloudFrontTemplate.ts`) with the event unwrapping removed, so both
3574
+ * behave the same. `tests/unit/deploy/staticApp/viewerRequestFunction.test.ts`
3575
+ * asserts they don't drift.
3576
+ */
3577
+ const APPEND_INDEX_HTML_HELPER = `function appendIndexHtml(request) {
3578
+ var uri = request.uri;
3579
+ if (uri.endsWith('/')) {
3580
+ request.uri += 'index.html';
3581
+ } else if (!uri.includes('.')) {
3582
+ request.uri += '/index.html';
3583
+ }
3584
+ return request;
3585
+ }`;
3586
+ /**
3587
+ * The entry point CloudFront calls. A function whose code doesn't declare it
3588
+ * fails at deploy time with an opaque error, so it's checked at synth time.
3589
+ */
3590
+ const HANDLER_DECLARATION_REGEX = /function\s+handler\s*\(/;
3591
+ /**
3592
+ * Reads the file the `viewerRequestFunctionCode` option points to.
3593
+ */
3594
+ const readViewerRequestFunctionCode = ({ filePath }) => {
3595
+ const resolvedPath = path.resolve(filePath);
3596
+ if (!fs.existsSync(resolvedPath)) throw new Error(`The viewer-request-function-code option points to "${filePath}", which doesn't exist.`);
3597
+ return fs.readFileSync(resolvedPath, "utf8");
3598
+ };
3599
+ /**
3600
+ * Composes the source of the per-app `AWS::CloudFront::Function`: the
3601
+ * `appendIndexHtml` helper followed by the app code, which owns the `handler`.
3602
+ */
3603
+ const getViewerRequestFunctionCode = ({ code }) => {
3604
+ if (!code.trim()) throw new Error("The viewer-request-function-code option points to an empty file.");
3605
+ if (!HANDLER_DECLARATION_REGEX.test(code)) throw new Error("The viewer request function code must declare a `function handler(event)`, which is the entry point CloudFront calls.");
3606
+ const functionCode = `${APPEND_INDEX_HTML_HELPER}\n\n${code.trim()}\n`;
3607
+ /**
3608
+ * The helper counts against the app budget, so the size of the composed
3609
+ * source is what CloudFront rejects.
3610
+ */
3611
+ const size = Buffer.byteLength(functionCode, "utf8");
3612
+ if (size > 10240) throw new Error(`The viewer request function is ${size} bytes, above the ${MAX_FUNCTION_SIZE_BYTES} bytes CloudFront allows. The \`appendIndexHtml\` helper carlin injects counts against this budget.`);
3613
+ return functionCode;
3614
+ };
3615
+ //#endregion
3373
3616
  //#region src/deploy/staticApp/staticApp.template.ts
3374
3617
  const PACKAGE_VERSION = getPackageVersion();
3375
3618
  const STATIC_APP_BUCKET_LOGICAL_ID = "StaticBucket";
3376
3619
  const CLOUDFRONT_DISTRIBUTION_LOGICAL_ID = "CloudFrontDistribution";
3377
3620
  const CLOUDFRONT_ORIGIN_ACCESS_CONTROL_LOGICAL_ID = "OriginAccessControl";
3621
+ const CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID = "ResponseHeadersPolicy";
3622
+ const CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID = "ViewerRequestFunction";
3378
3623
  const ROUTE_53_RECORD_SET_GROUP_LOGICAL_ID = "Route53RecordSetGroup";
3379
3624
  const ERROR_DOCUMENT = "404/index.html";
3380
3625
  /**
@@ -3393,8 +3638,31 @@ const ORIGIN_REQUEST_POLICY_ID = "88a5eaf4-2fd4-4709-b370-b4c650ea3fcf";
3393
3638
  * Name: CORS-with-preflight-and-SecurityHeadersPolicy
3394
3639
  * ID: eaab4381-ed33-4a86-88ca-d9558dc6cd63
3395
3640
  * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html
3641
+ *
3642
+ * Used when neither the `responseHeaders` nor the `responseHeadersPolicy`
3643
+ * option is defined. Its settings are reproduced in
3644
+ * `BASELINE_RESPONSE_HEADERS_CONFIG` for the policy created by the
3645
+ * `responseHeaders` option.
3396
3646
  */
3397
3647
  const ORIGIN_RESPONSE_POLICY_ID = "eaab4381-ed33-4a86-88ca-d9558dc6cd63";
3648
+ /**
3649
+ * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-responseheaderspolicy.html
3650
+ */
3651
+ const RESPONSE_HEADERS_POLICY_ID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3652
+ /**
3653
+ * The distribution takes a single response headers policy id, so the three
3654
+ * sources are mutually exclusive:
3655
+ *
3656
+ * 1. `responseHeadersPolicy`: an existing policy id, or the name of an
3657
+ * exported value whose value is a policy id.
3658
+ * 1. `responseHeaders`: the policy created by this template.
3659
+ * 1. Neither: the managed policy used by every deploy so far.
3660
+ */
3661
+ const getResponseHeadersPolicyId = ({ responseHeaders = [], responseHeadersPolicy }) => {
3662
+ if (responseHeadersPolicy) return RESPONSE_HEADERS_POLICY_ID_REGEX.test(responseHeadersPolicy) ? responseHeadersPolicy : { "Fn::ImportValue": responseHeadersPolicy };
3663
+ if (responseHeaders.length > 0) return { "Fn::GetAtt": [CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID, "Id"] };
3664
+ return ORIGIN_RESPONSE_POLICY_ID;
3665
+ };
3398
3666
  const getBucketStaticWebsiteTemplate = ({ spa }) => {
3399
3667
  return {
3400
3668
  AWSTemplateFormatVersion: "2010-09-09",
@@ -3439,7 +3707,7 @@ const getBucketStaticWebsiteTemplate = ({ spa }) => {
3439
3707
  } }
3440
3708
  };
3441
3709
  };
3442
- const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hostedZoneName }) => {
3710
+ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName, viewerRequestFunctionCode }) => {
3443
3711
  const template = {
3444
3712
  AWSTemplateFormatVersion: "2010-09-09",
3445
3713
  Resources: {
@@ -3517,7 +3785,10 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3517
3785
  * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-cachepolicyid
3518
3786
  */
3519
3787
  CachePolicyId: CACHE_POLICY_ID,
3520
- ResponseHeadersPolicyId: ORIGIN_RESPONSE_POLICY_ID,
3788
+ ResponseHeadersPolicyId: getResponseHeadersPolicyId({
3789
+ responseHeaders,
3790
+ responseHeadersPolicy
3791
+ }),
3521
3792
  TargetOriginId: { Ref: STATIC_APP_BUCKET_LOGICAL_ID },
3522
3793
  ViewerProtocolPolicy: "redirect-to-https"
3523
3794
  },
@@ -3544,7 +3815,11 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3544
3815
  SigningBehavior: "always",
3545
3816
  SigningProtocol: "sigv4"
3546
3817
  } }
3547
- }
3818
+ },
3819
+ ...responseHeaders.length > 0 ? { [CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID]: {
3820
+ Type: "AWS::CloudFront::ResponseHeadersPolicy",
3821
+ Properties: { ResponseHeadersPolicyConfig: getResponseHeadersPolicyConfig({ responseHeaders }) }
3822
+ } } : {}
3548
3823
  };
3549
3824
  if (acm) {
3550
3825
  const acmCertificateArn = /^arn:aws:acm:[-a-z0-9]+:\d{12}:certificate\/[-a-z0-9]+$/.test(acm) ? acm : { "Fn::ImportValue": acm };
@@ -3614,7 +3889,37 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3614
3889
  [`Alias${index}URL`]: { Value: `https://${alias}` }
3615
3890
  };
3616
3891
  }, {});
3617
- if (appendIndexHtml) {
3892
+ /**
3893
+ * A cache behavior takes a single viewer request function, so the app
3894
+ * supplied one replaces the shared base stack one instead of being appended
3895
+ * to it. `appendIndexHtml` is available to the app code as a helper, which is
3896
+ * why the two options are mutually exclusive.
3897
+ *
3898
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
3899
+ */
3900
+ if (appendIndexHtml && viewerRequestFunctionCode) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
3901
+ if (viewerRequestFunctionCode) template.Resources[CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID] = {
3902
+ Type: "AWS::CloudFront::Function",
3903
+ Properties: {
3904
+ /**
3905
+ * Function names must be unique per AWS account. Static app deploys are
3906
+ * always in us-east-1, so the stack name cannot collide with a
3907
+ * same-named stack in another region.
3908
+ */
3909
+ Name: { Ref: "AWS::StackName" },
3910
+ FunctionConfig: {
3911
+ Comment: { "Fn::Sub": ["Viewer request function for the ${Project} project.", { Project: { Ref: "Project" } }] },
3912
+ Runtime: FUNCTION_RUNTIME
3913
+ },
3914
+ FunctionCode: getViewerRequestFunctionCode({ code: viewerRequestFunctionCode }),
3915
+ AutoPublish: true
3916
+ }
3917
+ };
3918
+ const viewerRequestFunctionArn = (() => {
3919
+ if (viewerRequestFunctionCode) return { "Fn::GetAtt": [CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID, "FunctionMetadata.FunctionARN"] };
3920
+ if (appendIndexHtml) return { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME };
3921
+ })();
3922
+ if (viewerRequestFunctionArn) {
3618
3923
  if (!template.Resources["CloudFrontDistribution"].Properties) template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties = {};
3619
3924
  template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties.DistributionConfig.DefaultCacheBehavior.FunctionAssociations = [(
3620
3925
  /**
@@ -3622,7 +3927,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3622
3927
  */
3623
3928
  {
3624
3929
  EventType: "viewer-request",
3625
- FunctionARN: { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME }
3930
+ FunctionARN: viewerRequestFunctionArn
3626
3931
  })];
3627
3932
  }
3628
3933
  /**
@@ -3637,15 +3942,18 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3637
3942
  };
3638
3943
  return template;
3639
3944
  };
3640
- const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, spa, hostedZoneName, region }) => {
3945
+ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, viewerRequestFunctionCode }) => {
3641
3946
  if (cloudfront) return getCloudFrontTemplate({
3642
3947
  acm,
3643
3948
  aliases,
3644
3949
  appendIndexHtml,
3645
3950
  cloudfront,
3951
+ responseHeaders,
3952
+ responseHeadersPolicy,
3646
3953
  spa,
3647
3954
  hostedZoneName,
3648
- region
3955
+ region,
3956
+ viewerRequestFunctionCode
3649
3957
  });
3650
3958
  return getBucketStaticWebsiteTemplate({ spa });
3651
3959
  };
@@ -3717,7 +4025,7 @@ const logPrefix$4 = "static-app";
3717
4025
  * 1. Upload static files to the host bucket S3.
3718
4026
  * 1. Remove old deployment versions. Keep only the 3 most recent ones.
3719
4027
  */
3720
- const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, spa, hostedZoneName, region, skipUpload, uploadSourceMaps }) => {
4028
+ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps, viewerRequestFunctionCode }) => {
3721
4029
  try {
3722
4030
  const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$4 });
3723
4031
  const params = { StackName: stackName };
@@ -3726,9 +4034,12 @@ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, clo
3726
4034
  aliases,
3727
4035
  appendIndexHtml,
3728
4036
  cloudfront,
4037
+ responseHeaders,
4038
+ responseHeadersPolicy,
3729
4039
  spa,
3730
4040
  hostedZoneName,
3731
- region
4041
+ region,
4042
+ viewerRequestFunctionCode: viewerRequestFunctionCode ? readViewerRequestFunctionCode({ filePath: viewerRequestFunctionCode }) : void 0
3732
4043
  });
3733
4044
  const bucket = await getStaticAppBucket({ stackName });
3734
4045
  /**
@@ -3816,6 +4127,15 @@ const options$4 = {
3816
4127
  hidden: true,
3817
4128
  type: "string"
3818
4129
  },
4130
+ "response-headers": {
4131
+ coerce: parseResponseHeaders,
4132
+ default: [],
4133
+ describe: "Headers added by CloudFront to every response sent to viewers. Pass an object whose keys are header names and values are header values."
4134
+ },
4135
+ "response-headers-policy": {
4136
+ describe: "The id of an existing CloudFront response headers policy, or the name of the exported variable whose value is the id, that will be associated to the distribution instead of the default one.",
4137
+ type: "string"
4138
+ },
3819
4139
  "skip-upload": {
3820
4140
  default: false,
3821
4141
  describe: "Skip files upload to S3. Useful when wanting update only CloudFormation.",
@@ -3838,13 +4158,43 @@ const options$4 = {
3838
4158
  describe: "Upload source map (`.map`) files to S3. They are excluded by default because the bucket is public and source maps expose the application source.",
3839
4159
  require: false,
3840
4160
  type: "boolean"
4161
+ },
4162
+ "viewer-request-function-code": {
4163
+ describe: "Path to a file whose code runs as the CloudFront viewer request function of the distribution. The file must declare a `function handler(event)`, and may call the `appendIndexHtml(request)` helper carlin injects.",
4164
+ type: "string"
3841
4165
  }
3842
4166
  };
3843
4167
  const deployStaticAppCommand = {
3844
4168
  command: "static-app",
3845
4169
  describe: "Deploy static app.",
3846
4170
  builder: (yargs) => {
3847
- return yargs.options(addGroupToOptions(options$4, "Deploy Static App Options")).middleware(() => {
4171
+ return yargs.options(addGroupToOptions(options$4, "Deploy Static App Options")).check(({ cloudfront, responseHeaders, responseHeadersPolicy }) => {
4172
+ const hasResponseHeaders = responseHeaders?.length > 0;
4173
+ if (hasResponseHeaders && responseHeadersPolicy) throw new Error("The response-headers and response-headers-policy options are mutually exclusive. The distribution takes a single response headers policy.");
4174
+ /**
4175
+ * Response headers are applied by CloudFront, so a bucket only
4176
+ * deploy has nothing to attach them to.
4177
+ */
4178
+ if (!cloudfront && (hasResponseHeaders || responseHeadersPolicy)) throw new Error(`The ${hasResponseHeaders ? "response-headers" : "response-headers-policy"} option requires the cloudfront option.`);
4179
+ return true;
4180
+ }).check(({ appendIndexHtml, cloudfront, viewerRequestFunctionCode }) => {
4181
+ if (!viewerRequestFunctionCode) return true;
4182
+ /**
4183
+ * A cache behavior takes a single viewer request function, and the
4184
+ * shared base stack one is what append-index-html associates. The app
4185
+ * supplied function gets the same behavior by calling the
4186
+ * `appendIndexHtml` helper carlin injects.
4187
+ *
4188
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
4189
+ */
4190
+ if (appendIndexHtml) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
4191
+ /**
4192
+ * The function is associated to a cache behavior, so a bucket only
4193
+ * deploy has nothing to attach it to.
4194
+ */
4195
+ if (!cloudfront) throw new Error("The viewer-request-function-code option requires the cloudfront option.");
4196
+ return true;
4197
+ }).middleware(() => {
3848
4198
  AWS.config.region = CLOUDFRONT_REGION;
3849
4199
  });
3850
4200
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "homepage": "https://ttoss.dev/docs/carlin/",