@rayselfs/cf-rule-engine 1.9.0 → 1.9.2

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/dist/adapters/viewer-request-async.d.cts +23 -0
  2. package/dist/adapters/viewer-request-async.d.ts +23 -0
  3. package/dist/behaviors/construct-response.d.cts +2 -2
  4. package/dist/behaviors/construct-response.d.ts +2 -2
  5. package/dist/behaviors/image-optimize.d.cts +24 -13
  6. package/dist/behaviors/image-optimize.d.ts +24 -13
  7. package/dist/behaviors/index.cjs +3 -3
  8. package/dist/behaviors/index.d.cts +2 -2
  9. package/dist/behaviors/index.d.ts +2 -2
  10. package/dist/behaviors/index.js +2 -2
  11. package/dist/behaviors/kvs.d.cts +28 -0
  12. package/dist/behaviors/kvs.d.ts +28 -0
  13. package/dist/behaviors/redirect.d.cts +2 -2
  14. package/dist/behaviors/redirect.d.ts +2 -2
  15. package/dist/behaviors/set-cors-headers.cjs +3 -3
  16. package/dist/behaviors/set-cors-headers.d.cts +15 -5
  17. package/dist/behaviors/set-cors-headers.d.ts +15 -5
  18. package/dist/behaviors/set-cors-headers.js +2 -2
  19. package/dist/behaviors/set-csp.d.cts +2 -2
  20. package/dist/behaviors/set-csp.d.ts +2 -2
  21. package/dist/behaviors/set-security-headers.d.cts +2 -2
  22. package/dist/behaviors/set-security-headers.d.ts +2 -2
  23. package/dist/{chunk-ZEFLAOTL.cjs → chunk-7T4G7UF7.cjs} +2 -2
  24. package/dist/{chunk-EMDI676G.cjs → chunk-CLGM2TGT.cjs} +5 -5
  25. package/dist/{chunk-H3RK4USR.js → chunk-GKE3YDHR.js} +1 -1
  26. package/dist/chunk-HMQIXEFJ.cjs +62 -0
  27. package/dist/{chunk-VQGBRWJK.js → chunk-HWJFOKZX.js} +1 -1
  28. package/dist/{chunk-Y7TIDVVC.js → chunk-I7YELJ2P.js} +1 -1
  29. package/dist/{chunk-EEZ7NUJG.js → chunk-NJD4L4Q3.js} +3 -0
  30. package/dist/chunk-SC6UPQYF.js +62 -0
  31. package/dist/{chunk-IHVOAORH.cjs → chunk-TJ2POKWD.cjs} +2 -2
  32. package/dist/{chunk-7EA7GFWX.js → chunk-VRSD6YHP.js} +2 -2
  33. package/dist/{chunk-LVOM5GJ6.cjs → chunk-WUFGMLE7.cjs} +2 -2
  34. package/dist/{chunk-ULICUDDH.cjs → chunk-YNKZGZ7I.cjs} +3 -0
  35. package/dist/core/types.d.cts +8 -8
  36. package/dist/core/types.d.ts +8 -8
  37. package/dist/criteria/file-extension.d.cts +3 -3
  38. package/dist/criteria/file-extension.d.ts +3 -3
  39. package/dist/criteria/index.cjs +13 -13
  40. package/dist/criteria/index.js +16 -16
  41. package/dist/criteria/kvs.d.cts +28 -0
  42. package/dist/criteria/kvs.d.ts +28 -0
  43. package/dist/criteria/path-matches.cjs +3 -3
  44. package/dist/criteria/path-matches.js +2 -2
  45. package/dist/criteria/user-agent-matches.cjs +3 -3
  46. package/dist/criteria/user-agent-matches.js +2 -2
  47. package/dist/helpers/index.cjs +10 -8
  48. package/dist/helpers/index.js +9 -7
  49. package/dist/helpers/preflight-request.cjs +4 -4
  50. package/dist/helpers/preflight-request.js +3 -3
  51. package/dist/helpers/whitelist.cjs +7 -5
  52. package/dist/helpers/whitelist.d.cts +2 -37
  53. package/dist/helpers/whitelist.d.ts +2 -37
  54. package/dist/helpers/whitelist.js +6 -4
  55. package/dist/shared/kvs.d.cts +7 -2
  56. package/dist/shared/kvs.d.ts +7 -2
  57. package/dist/shared/wildcard.cjs +2 -2
  58. package/dist/shared/wildcard.js +1 -1
  59. package/package.json +1 -1
  60. package/dist/chunk-IHDSTTO2.js +0 -32
  61. package/dist/chunk-ISXKMJCN.cjs +0 -32
@@ -1,5 +1,28 @@
1
1
  import { Rule } from '../core/types.cjs';
2
2
 
3
+ /**
4
+ * Creates a CloudFront Function viewer-request handler where rules are resolved
5
+ * asynchronously before each request — for example, loading redirect maps or
6
+ * CIDR lists from CloudFront KeyValueStore at startup.
7
+ *
8
+ * The `setup` function receives the raw CF event and returns a `Rule[]`. It is
9
+ * called once per invocation, so any async initialization (e.g. KVS reads)
10
+ * should be cached outside the handler when possible.
11
+ *
12
+ * @param setup - Async factory that receives the CF event and returns the ordered rule list.
13
+ * @returns An async CloudFront Function handler `async (event) => request | response`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { rule } from '@rayselfs/cf-rule-engine'
18
+ * import { kvsRedirect } from '@rayselfs/cf-rule-engine/behaviors/kvs'
19
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
20
+ *
21
+ * export default defineViewerRequestAsync(async () => [
22
+ * await kvsRedirect(handle, 'redirects'),
23
+ * ])
24
+ * ```
25
+ */
3
26
  declare function defineViewerRequestAsync(setup: (event: unknown) => Promise<Rule[]>): (event: unknown) => Promise<unknown>;
4
27
 
5
28
  export { defineViewerRequestAsync };
@@ -1,5 +1,28 @@
1
1
  import { Rule } from '../core/types.js';
2
2
 
3
+ /**
4
+ * Creates a CloudFront Function viewer-request handler where rules are resolved
5
+ * asynchronously before each request — for example, loading redirect maps or
6
+ * CIDR lists from CloudFront KeyValueStore at startup.
7
+ *
8
+ * The `setup` function receives the raw CF event and returns a `Rule[]`. It is
9
+ * called once per invocation, so any async initialization (e.g. KVS reads)
10
+ * should be cached outside the handler when possible.
11
+ *
12
+ * @param setup - Async factory that receives the CF event and returns the ordered rule list.
13
+ * @returns An async CloudFront Function handler `async (event) => request | response`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { rule } from '@rayselfs/cf-rule-engine'
18
+ * import { kvsRedirect } from '@rayselfs/cf-rule-engine/behaviors/kvs'
19
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
20
+ *
21
+ * export default defineViewerRequestAsync(async () => [
22
+ * await kvsRedirect(handle, 'redirects'),
23
+ * ])
24
+ * ```
25
+ */
3
26
  declare function defineViewerRequestAsync(setup: (event: unknown) => Promise<Rule[]>): (event: unknown) => Promise<unknown>;
4
27
 
5
28
  export { defineViewerRequestAsync };
@@ -3,7 +3,7 @@ import { BehaviorFn } from '../core/types.cjs';
3
3
  /**
4
4
  * Options for constructing a synthetic HTTP response at the edge.
5
5
  */
6
- interface ConstructResponseOptions {
6
+ type ConstructResponseOptions = {
7
7
  /**
8
8
  * The HTTP status code for the response (e.g. `200`, `403`, `404`).
9
9
  */
@@ -24,7 +24,7 @@ interface ConstructResponseOptions {
24
24
  * @example `{ 'x-request-id': '123', 'retry-after': '60' }`
25
25
  */
26
26
  headers?: Record<string, string>;
27
- }
27
+ };
28
28
  /**
29
29
  * Constructs and returns a synthetic HTTP response directly from the edge,
30
30
  * without forwarding the request to the origin.
@@ -3,7 +3,7 @@ import { BehaviorFn } from '../core/types.js';
3
3
  /**
4
4
  * Options for constructing a synthetic HTTP response at the edge.
5
5
  */
6
- interface ConstructResponseOptions {
6
+ type ConstructResponseOptions = {
7
7
  /**
8
8
  * The HTTP status code for the response (e.g. `200`, `403`, `404`).
9
9
  */
@@ -24,7 +24,7 @@ interface ConstructResponseOptions {
24
24
  * @example `{ 'x-request-id': '123', 'retry-after': '60' }`
25
25
  */
26
26
  headers?: Record<string, string>;
27
- }
27
+ };
28
28
  /**
29
29
  * Constructs and returns a synthetic HTTP response directly from the edge,
30
30
  * without forwarding the request to the origin.
@@ -5,8 +5,13 @@ import { HttpRequest, BehaviorFn } from '../core/types.cjs';
5
5
  *
6
6
  * Determines which request headers are injected so the proxy knows where to
7
7
  * fetch the source image:
8
- * - gateway: injects X-Img-Source-Type=gateway and X-Img-Upstream-Gateway
9
- * - s3: injects X-Img-Source-Type=s3 and X-Img-Source-Bucket
8
+ * - `s3`: injects `X-Img-Source-Type: s3` and `X-Img-Source-Bucket`
9
+ * - `gateway`: injects `X-Img-Source-Type: gateway` and `X-Img-Upstream-Gateway`
10
+ * (proxy treats any non-`s3` value as a gateway fallback)
11
+ *
12
+ * **Required for all requests** — the proxy always resolves the upstream source,
13
+ * even when no optimization params are present (pass-through mode). If origin
14
+ * headers are missing, the proxy returns an error.
10
15
  */
11
16
  type ImageOriginConfig = {
12
17
  type: 'gateway';
@@ -32,7 +37,7 @@ type ImageOriginResolver = ImageOriginConfig | ((request: HttpRequest) => ImageO
32
37
  * the normalized `imwidth`, `f`, and `q` params to drive imgproxy transformation
33
38
  * and S3 caching.
34
39
  */
35
- interface ImageOptimizeOptions {
40
+ type ImageOptimizeOptions = {
36
41
  /** Ordered list of breakpoint widths (px). Request widths snap to the nearest ceiling breakpoint. */
37
42
  breakpoints: number[];
38
43
  /** Preferred format priority. Defaults to ['avif', 'webp', 'jpeg']. */
@@ -45,13 +50,13 @@ interface ImageOptimizeOptions {
45
50
  imformatParam?: string;
46
51
  /**
47
52
  * Origin configuration for image-optimize-proxy.
48
- * When provided, injects the corresponding X-Img-* request headers so the
49
- * proxy knows how to resolve the source image. This removes the need to
50
- * configure CloudFront origin custom headers separately in Terraform.
51
- *
52
- * Accepts either a static config object or a resolver function that receives
53
- * the request and returns the appropriate origin (or undefined to skip).
54
- */
53
+ * When provided, injects the corresponding X-Img-* request headers so the
54
+ * proxy knows how to resolve the source image. This removes the need to
55
+ * configure CloudFront origin custom headers separately in Terraform.
56
+ *
57
+ * Accepts either a static config object or a resolver function that receives
58
+ * the request and returns the appropriate origin (or undefined to skip).
59
+ */
55
60
  origin?: ImageOriginResolver;
56
61
  /**
57
62
  * CloudFront origin verification secret.
@@ -59,16 +64,16 @@ interface ImageOptimizeOptions {
59
64
  * The proxy validates this header to ensure requests originate from CloudFront.
60
65
  */
61
66
  originSecret?: string;
62
- }
67
+ };
63
68
  /** Resolved normalized image parameters. */
64
- interface ResolvedImageParams {
69
+ type ResolvedImageParams = {
65
70
  /** Width snapped to nearest ceiling breakpoint. */
66
71
  breakpoint: number;
67
72
  /** Resolved output format. */
68
73
  format: 'avif' | 'webp' | 'jpeg';
69
74
  /** Quality value (1-100). */
70
75
  quality: number;
71
- }
76
+ };
72
77
  /**
73
78
  * Resolves normalized image parameters (breakpoint, format, quality) from a request.
74
79
  *
@@ -101,6 +106,12 @@ declare function resolveImageParams(request: Pick<HttpRequest, 'querystring' | '
101
106
  * or X-Img-Source-Bucket headers (eliminates need for Terraform origin custom headers)
102
107
  * - When `originSecret` is set, injects X-Origin-Verify header
103
108
  *
109
+ * ⚠️ **Origin headers are required even for pass-through requests.** The proxy
110
+ * always resolves the upstream source regardless of whether optimization params
111
+ * are present. If `origin` is not configured here, set `X-Img-Upstream-Gateway`
112
+ * or `X-Img-Source-Type` / `X-Img-Source-Bucket` as CloudFront origin custom
113
+ * headers in Terraform — otherwise the proxy returns an error for every request.
114
+ *
104
115
  * Architecture:
105
116
  * CF Function (viewer-request): imageOptimize — normalize querystring + inject origin headers
106
117
  * image-optimize-proxy (origin): reads imwidth/f/q + X-Img-* headers, calls imgproxy sidecar, caches to S3
@@ -5,8 +5,13 @@ import { HttpRequest, BehaviorFn } from '../core/types.js';
5
5
  *
6
6
  * Determines which request headers are injected so the proxy knows where to
7
7
  * fetch the source image:
8
- * - gateway: injects X-Img-Source-Type=gateway and X-Img-Upstream-Gateway
9
- * - s3: injects X-Img-Source-Type=s3 and X-Img-Source-Bucket
8
+ * - `s3`: injects `X-Img-Source-Type: s3` and `X-Img-Source-Bucket`
9
+ * - `gateway`: injects `X-Img-Source-Type: gateway` and `X-Img-Upstream-Gateway`
10
+ * (proxy treats any non-`s3` value as a gateway fallback)
11
+ *
12
+ * **Required for all requests** — the proxy always resolves the upstream source,
13
+ * even when no optimization params are present (pass-through mode). If origin
14
+ * headers are missing, the proxy returns an error.
10
15
  */
11
16
  type ImageOriginConfig = {
12
17
  type: 'gateway';
@@ -32,7 +37,7 @@ type ImageOriginResolver = ImageOriginConfig | ((request: HttpRequest) => ImageO
32
37
  * the normalized `imwidth`, `f`, and `q` params to drive imgproxy transformation
33
38
  * and S3 caching.
34
39
  */
35
- interface ImageOptimizeOptions {
40
+ type ImageOptimizeOptions = {
36
41
  /** Ordered list of breakpoint widths (px). Request widths snap to the nearest ceiling breakpoint. */
37
42
  breakpoints: number[];
38
43
  /** Preferred format priority. Defaults to ['avif', 'webp', 'jpeg']. */
@@ -45,13 +50,13 @@ interface ImageOptimizeOptions {
45
50
  imformatParam?: string;
46
51
  /**
47
52
  * Origin configuration for image-optimize-proxy.
48
- * When provided, injects the corresponding X-Img-* request headers so the
49
- * proxy knows how to resolve the source image. This removes the need to
50
- * configure CloudFront origin custom headers separately in Terraform.
51
- *
52
- * Accepts either a static config object or a resolver function that receives
53
- * the request and returns the appropriate origin (or undefined to skip).
54
- */
53
+ * When provided, injects the corresponding X-Img-* request headers so the
54
+ * proxy knows how to resolve the source image. This removes the need to
55
+ * configure CloudFront origin custom headers separately in Terraform.
56
+ *
57
+ * Accepts either a static config object or a resolver function that receives
58
+ * the request and returns the appropriate origin (or undefined to skip).
59
+ */
55
60
  origin?: ImageOriginResolver;
56
61
  /**
57
62
  * CloudFront origin verification secret.
@@ -59,16 +64,16 @@ interface ImageOptimizeOptions {
59
64
  * The proxy validates this header to ensure requests originate from CloudFront.
60
65
  */
61
66
  originSecret?: string;
62
- }
67
+ };
63
68
  /** Resolved normalized image parameters. */
64
- interface ResolvedImageParams {
69
+ type ResolvedImageParams = {
65
70
  /** Width snapped to nearest ceiling breakpoint. */
66
71
  breakpoint: number;
67
72
  /** Resolved output format. */
68
73
  format: 'avif' | 'webp' | 'jpeg';
69
74
  /** Quality value (1-100). */
70
75
  quality: number;
71
- }
76
+ };
72
77
  /**
73
78
  * Resolves normalized image parameters (breakpoint, format, quality) from a request.
74
79
  *
@@ -101,6 +106,12 @@ declare function resolveImageParams(request: Pick<HttpRequest, 'querystring' | '
101
106
  * or X-Img-Source-Bucket headers (eliminates need for Terraform origin custom headers)
102
107
  * - When `originSecret` is set, injects X-Origin-Verify header
103
108
  *
109
+ * ⚠️ **Origin headers are required even for pass-through requests.** The proxy
110
+ * always resolves the upstream source regardless of whether optimization params
111
+ * are present. If `origin` is not configured here, set `X-Img-Upstream-Gateway`
112
+ * or `X-Img-Source-Type` / `X-Img-Source-Bucket` as CloudFront origin custom
113
+ * headers in Terraform — otherwise the proxy returns an error for every request.
114
+ *
104
115
  * Architecture:
105
116
  * CF Function (viewer-request): imageOptimize — normalize querystring + inject origin headers
106
117
  * image-optimize-proxy (origin): reads imwidth/f/q + X-Img-* headers, calls imgproxy sidecar, caches to S3
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkIHVOAORHcjs = require('../chunk-IHVOAORH.cjs');
4
- require('../chunk-ULICUDDH.cjs');
3
+ var _chunkTJ2POKWDcjs = require('../chunk-TJ2POKWD.cjs');
4
+ require('../chunk-YNKZGZ7I.cjs');
5
5
 
6
6
 
7
7
  var _chunkZXS23HXAcjs = require('../chunk-ZXS23HXA.cjs');
@@ -124,4 +124,4 @@ function verifyToken(options) {
124
124
 
125
125
 
126
126
 
127
- exports.constructResponse = _chunkOSGZTNTScjs.constructResponse; exports.copyHeader = _chunkJU5WX5RUcjs.copyHeader; exports.directoryIndex = _chunkLTLBEBKLcjs.directoryIndex; exports.imageOptimize = _chunkKXC6ES3Bcjs.imageOptimize; exports.redirect = _chunkWWSRNCUPcjs.redirect; exports.removeResponseHeaders = _chunkSGEBNQR2cjs.removeResponseHeaders; exports.rewriteUri = _chunkBSH5JZBLcjs.rewriteUri; exports.setCacheControl = _chunkCV234DQTcjs.setCacheControl; exports.setCorsHeaders = _chunkIHVOAORHcjs.setCorsHeaders; exports.setCsp = _chunkZXS23HXAcjs.setCsp; exports.setRequestHeader = _chunkPPUHEL4Hcjs.setRequestHeader; exports.setResponseHeader = _chunkB4WEJSEZcjs.setResponseHeader; exports.setSecurityHeaders = _chunk3UXNXJ6Ncjs.setSecurityHeaders; exports.stripQueryParams = _chunkMSES76XKcjs.stripQueryParams; exports.verifyToken = verifyToken;
127
+ exports.constructResponse = _chunkOSGZTNTScjs.constructResponse; exports.copyHeader = _chunkJU5WX5RUcjs.copyHeader; exports.directoryIndex = _chunkLTLBEBKLcjs.directoryIndex; exports.imageOptimize = _chunkKXC6ES3Bcjs.imageOptimize; exports.redirect = _chunkWWSRNCUPcjs.redirect; exports.removeResponseHeaders = _chunkSGEBNQR2cjs.removeResponseHeaders; exports.rewriteUri = _chunkBSH5JZBLcjs.rewriteUri; exports.setCacheControl = _chunkCV234DQTcjs.setCacheControl; exports.setCorsHeaders = _chunkTJ2POKWDcjs.setCorsHeaders; exports.setCsp = _chunkZXS23HXAcjs.setCsp; exports.setRequestHeader = _chunkPPUHEL4Hcjs.setRequestHeader; exports.setResponseHeader = _chunkB4WEJSEZcjs.setResponseHeader; exports.setSecurityHeaders = _chunk3UXNXJ6Ncjs.setSecurityHeaders; exports.stripQueryParams = _chunkMSES76XKcjs.stripQueryParams; exports.verifyToken = verifyToken;
@@ -21,11 +21,11 @@ export { ResponseBehaviorFn, ResponseRule } from '../core/types.cjs';
21
21
  * Token format: `exp=<unix>~acl=<path>~hmac=<hex>`
22
22
  * The `key` is the hex-encoded HMAC-SHA256 secret (Akamai `verifyTokenAuthorization.key`).
23
23
  */
24
- interface VerifyTokenOptions {
24
+ type VerifyTokenOptions = {
25
25
  key: string;
26
26
  param?: string;
27
27
  failureStatus?: 401 | 403;
28
- }
28
+ };
29
29
  /**
30
30
  * Validates an Akamai Edge Auth Token 2.0 (HMAC-SHA256) from the request querystring.
31
31
  * Returns 403 on missing / expired / invalid token; continues on success.
@@ -21,11 +21,11 @@ export { ResponseBehaviorFn, ResponseRule } from '../core/types.js';
21
21
  * Token format: `exp=<unix>~acl=<path>~hmac=<hex>`
22
22
  * The `key` is the hex-encoded HMAC-SHA256 secret (Akamai `verifyTokenAuthorization.key`).
23
23
  */
24
- interface VerifyTokenOptions {
24
+ type VerifyTokenOptions = {
25
25
  key: string;
26
26
  param?: string;
27
27
  failureStatus?: 401 | 403;
28
- }
28
+ };
29
29
  /**
30
30
  * Validates an Akamai Edge Auth Token 2.0 (HMAC-SHA256) from the request querystring.
31
31
  * Returns 403 on missing / expired / invalid token; continues on success.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  setCorsHeaders
3
- } from "../chunk-H3RK4USR.js";
4
- import "../chunk-EEZ7NUJG.js";
3
+ } from "../chunk-GKE3YDHR.js";
4
+ import "../chunk-NJD4L4Q3.js";
5
5
  import {
6
6
  setCsp
7
7
  } from "../chunk-XUI4Y22M.js";
@@ -1,6 +1,34 @@
1
1
  import { BehaviorFn } from '../core/types.cjs';
2
2
  import { KvsHandle } from '../shared/kvs.cjs';
3
3
 
4
+ /**
5
+ * Loads a redirect map from CloudFront KeyValueStore and returns a `BehaviorFn`
6
+ * that performs 301/302 redirects based on exact URI matches.
7
+ *
8
+ * The KVS value at `key` must be a JSON-encoded `Record<string, string>` mapping
9
+ * source URIs to destination URLs (e.g. `{ "/old": "https://example.com/new" }`).
10
+ * Requests whose URI does not appear in the map are passed through unchanged.
11
+ *
12
+ * Intended for use with `defineViewerRequestAsync` — the KVS read happens once
13
+ * at setup time and the resulting map is captured in the returned closure.
14
+ *
15
+ * @param handle - KVS handle (from `@aws-sdk/cloudfront-keyvaluestore` or equivalent).
16
+ * @param key - The KVS key whose value is a JSON redirect map.
17
+ * @param statusCode - HTTP redirect status code. Defaults to `301`.
18
+ * @returns A `BehaviorFn` to pass to `rule()`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
23
+ * import { rule } from '@rayselfs/cf-rule-engine'
24
+ * import { kvsRedirect } from '@rayselfs/cf-rule-engine/behaviors/kvs'
25
+ *
26
+ * export default defineViewerRequestAsync(async (event) => {
27
+ * const handle = CloudFront.createKeyValueStore(event)
28
+ * return [rule(await kvsRedirect(handle, 'redirects'))]
29
+ * })
30
+ * ```
31
+ */
4
32
  declare function kvsRedirect(handle: KvsHandle, key: string, statusCode?: number): Promise<BehaviorFn>;
5
33
 
6
34
  export { kvsRedirect };
@@ -1,6 +1,34 @@
1
1
  import { BehaviorFn } from '../core/types.js';
2
2
  import { KvsHandle } from '../shared/kvs.js';
3
3
 
4
+ /**
5
+ * Loads a redirect map from CloudFront KeyValueStore and returns a `BehaviorFn`
6
+ * that performs 301/302 redirects based on exact URI matches.
7
+ *
8
+ * The KVS value at `key` must be a JSON-encoded `Record<string, string>` mapping
9
+ * source URIs to destination URLs (e.g. `{ "/old": "https://example.com/new" }`).
10
+ * Requests whose URI does not appear in the map are passed through unchanged.
11
+ *
12
+ * Intended for use with `defineViewerRequestAsync` — the KVS read happens once
13
+ * at setup time and the resulting map is captured in the returned closure.
14
+ *
15
+ * @param handle - KVS handle (from `@aws-sdk/cloudfront-keyvaluestore` or equivalent).
16
+ * @param key - The KVS key whose value is a JSON redirect map.
17
+ * @param statusCode - HTTP redirect status code. Defaults to `301`.
18
+ * @returns A `BehaviorFn` to pass to `rule()`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
23
+ * import { rule } from '@rayselfs/cf-rule-engine'
24
+ * import { kvsRedirect } from '@rayselfs/cf-rule-engine/behaviors/kvs'
25
+ *
26
+ * export default defineViewerRequestAsync(async (event) => {
27
+ * const handle = CloudFront.createKeyValueStore(event)
28
+ * return [rule(await kvsRedirect(handle, 'redirects'))]
29
+ * })
30
+ * ```
31
+ */
4
32
  declare function kvsRedirect(handle: KvsHandle, key: string, statusCode?: number): Promise<BehaviorFn>;
5
33
 
6
34
  export { kvsRedirect };
@@ -3,14 +3,14 @@ import { BehaviorFn } from '../core/types.cjs';
3
3
  /**
4
4
  * Options for configuring redirect behavior.
5
5
  */
6
- interface RedirectOptions {
6
+ type RedirectOptions = {
7
7
  /**
8
8
  * When `true`, the original request's query string is appended to the redirect
9
9
  * `location` URL. Useful for preserving search params during path migrations.
10
10
  * Default: `false`.
11
11
  */
12
12
  preserveQuerystring?: boolean;
13
- }
13
+ };
14
14
  /**
15
15
  * Redirects the request to the specified URL with the given HTTP status code.
16
16
  *
@@ -3,14 +3,14 @@ import { BehaviorFn } from '../core/types.js';
3
3
  /**
4
4
  * Options for configuring redirect behavior.
5
5
  */
6
- interface RedirectOptions {
6
+ type RedirectOptions = {
7
7
  /**
8
8
  * When `true`, the original request's query string is appended to the redirect
9
9
  * `location` URL. Useful for preserving search params during path migrations.
10
10
  * Default: `false`.
11
11
  */
12
12
  preserveQuerystring?: boolean;
13
- }
13
+ };
14
14
  /**
15
15
  * Redirects the request to the specified URL with the given HTTP status code.
16
16
  *
@@ -2,11 +2,11 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkIHVOAORHcjs = require('../chunk-IHVOAORH.cjs');
6
- require('../chunk-ULICUDDH.cjs');
5
+ var _chunkTJ2POKWDcjs = require('../chunk-TJ2POKWD.cjs');
6
+ require('../chunk-YNKZGZ7I.cjs');
7
7
  require('../chunk-75ZPJI57.cjs');
8
8
 
9
9
 
10
10
 
11
11
 
12
- exports.ORIGIN_ECHO = _chunkIHVOAORHcjs.ORIGIN_ECHO; exports.ORIGIN_WILDCARD = _chunkIHVOAORHcjs.ORIGIN_WILDCARD; exports.setCorsHeaders = _chunkIHVOAORHcjs.setCorsHeaders;
12
+ exports.ORIGIN_ECHO = _chunkTJ2POKWDcjs.ORIGIN_ECHO; exports.ORIGIN_WILDCARD = _chunkTJ2POKWDcjs.ORIGIN_WILDCARD; exports.setCorsHeaders = _chunkTJ2POKWDcjs.setCorsHeaders;
@@ -16,14 +16,11 @@ type Origin = `https://${string}` | `http://${string}`;
16
16
  * - `ORIGIN_ECHO` (`'echo'`) — echo any request `Origin` if present, skip if none
17
17
  */
18
18
  type OriginPolicy = OriginWildcard | Origin[] | OriginEcho;
19
- /**
20
- * Standard HTTP methods allowed in `Access-Control-Allow-Methods`.
21
- */
22
19
  type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT';
23
20
  /**
24
21
  * CORS configuration options for `setCorsHeaders` and `preflightRequest`.
25
22
  */
26
- interface CorsOptions {
23
+ type CorsOptions = {
27
24
  /**
28
25
  * Origin policy. See `OriginPolicy` for details.
29
26
  */
@@ -54,7 +51,20 @@ interface CorsOptions {
54
51
  * Omit to exclude the header.
55
52
  */
56
53
  maxAge?: number;
57
- }
54
+ };
55
+ /**
56
+ * Sets CORS response headers with configurable origin policy.
57
+ *
58
+ * @param options - CORS configuration. `allowedOrigins` is required.
59
+ * @returns A `ResponseBehaviorFn` to use directly in `defineViewerResponse` or wrapped in a `ResponseRule`.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * setCorsHeaders({ allowedOrigins: ORIGIN_WILDCARD })
64
+ * setCorsHeaders({ allowedOrigins: ['https://*.viverse.com'] })
65
+ * setCorsHeaders({ allowedOrigins: ORIGIN_ECHO, allowCredentials: true })
66
+ * ```
67
+ */
58
68
  declare function setCorsHeaders(options: CorsOptions): ResponseBehaviorFn;
59
69
 
60
70
  export { type CorsOptions, type Methods, ORIGIN_ECHO, ORIGIN_WILDCARD, type Origin, type OriginEcho, type OriginPolicy, type OriginWildcard, setCorsHeaders };
@@ -16,14 +16,11 @@ type Origin = `https://${string}` | `http://${string}`;
16
16
  * - `ORIGIN_ECHO` (`'echo'`) — echo any request `Origin` if present, skip if none
17
17
  */
18
18
  type OriginPolicy = OriginWildcard | Origin[] | OriginEcho;
19
- /**
20
- * Standard HTTP methods allowed in `Access-Control-Allow-Methods`.
21
- */
22
19
  type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT';
23
20
  /**
24
21
  * CORS configuration options for `setCorsHeaders` and `preflightRequest`.
25
22
  */
26
- interface CorsOptions {
23
+ type CorsOptions = {
27
24
  /**
28
25
  * Origin policy. See `OriginPolicy` for details.
29
26
  */
@@ -54,7 +51,20 @@ interface CorsOptions {
54
51
  * Omit to exclude the header.
55
52
  */
56
53
  maxAge?: number;
57
- }
54
+ };
55
+ /**
56
+ * Sets CORS response headers with configurable origin policy.
57
+ *
58
+ * @param options - CORS configuration. `allowedOrigins` is required.
59
+ * @returns A `ResponseBehaviorFn` to use directly in `defineViewerResponse` or wrapped in a `ResponseRule`.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * setCorsHeaders({ allowedOrigins: ORIGIN_WILDCARD })
64
+ * setCorsHeaders({ allowedOrigins: ['https://*.viverse.com'] })
65
+ * setCorsHeaders({ allowedOrigins: ORIGIN_ECHO, allowCredentials: true })
66
+ * ```
67
+ */
58
68
  declare function setCorsHeaders(options: CorsOptions): ResponseBehaviorFn;
59
69
 
60
70
  export { type CorsOptions, type Methods, ORIGIN_ECHO, ORIGIN_WILDCARD, type Origin, type OriginEcho, type OriginPolicy, type OriginWildcard, setCorsHeaders };
@@ -2,8 +2,8 @@ import {
2
2
  ORIGIN_ECHO,
3
3
  ORIGIN_WILDCARD,
4
4
  setCorsHeaders
5
- } from "../chunk-H3RK4USR.js";
6
- import "../chunk-EEZ7NUJG.js";
5
+ } from "../chunk-GKE3YDHR.js";
6
+ import "../chunk-NJD4L4Q3.js";
7
7
  import "../chunk-MLKGABMK.js";
8
8
  export {
9
9
  ORIGIN_ECHO,
@@ -3,7 +3,7 @@ import { ResponseBehaviorFn } from '../core/types.cjs';
3
3
  /**
4
4
  * Configuration for the `Content-Security-Policy` header.
5
5
  */
6
- interface CspOptions {
6
+ type CspOptions = {
7
7
  /**
8
8
  * Map of CSP directive names to their values.
9
9
  * Each entry becomes one `<directive> <value>` segment in the header,
@@ -16,7 +16,7 @@ interface CspOptions {
16
16
  * ```
17
17
  */
18
18
  directives: Record<string, string>;
19
- }
19
+ };
20
20
  /**
21
21
  * Sets the `Content-Security-Policy` response header from a directives map.
22
22
  *
@@ -3,7 +3,7 @@ import { ResponseBehaviorFn } from '../core/types.js';
3
3
  /**
4
4
  * Configuration for the `Content-Security-Policy` header.
5
5
  */
6
- interface CspOptions {
6
+ type CspOptions = {
7
7
  /**
8
8
  * Map of CSP directive names to their values.
9
9
  * Each entry becomes one `<directive> <value>` segment in the header,
@@ -16,7 +16,7 @@ interface CspOptions {
16
16
  * ```
17
17
  */
18
18
  directives: Record<string, string>;
19
- }
19
+ };
20
20
  /**
21
21
  * Sets the `Content-Security-Policy` response header from a directives map.
22
22
  *
@@ -8,7 +8,7 @@ import { ResponseBehaviorFn } from '../core/types.cjs';
8
8
  *
9
9
  * Pass at least one field.
10
10
  */
11
- interface SecurityHeadersOptions {
11
+ type SecurityHeadersOptions = {
12
12
  /**
13
13
  * Value for the `Strict-Transport-Security` header.
14
14
  * Example: `'max-age=31536000; includeSubDomains'`
@@ -31,7 +31,7 @@ interface SecurityHeadersOptions {
31
31
  * Note: deprecated in modern browsers but still used for legacy compatibility.
32
32
  */
33
33
  xXssProtection?: string;
34
- }
34
+ };
35
35
  /**
36
36
  * Sets security headers on the outgoing response.
37
37
  *
@@ -8,7 +8,7 @@ import { ResponseBehaviorFn } from '../core/types.js';
8
8
  *
9
9
  * Pass at least one field.
10
10
  */
11
- interface SecurityHeadersOptions {
11
+ type SecurityHeadersOptions = {
12
12
  /**
13
13
  * Value for the `Strict-Transport-Security` header.
14
14
  * Example: `'max-age=31536000; includeSubDomains'`
@@ -31,7 +31,7 @@ interface SecurityHeadersOptions {
31
31
  * Note: deprecated in modern browsers but still used for legacy compatibility.
32
32
  */
33
33
  xXssProtection?: string;
34
- }
34
+ };
35
35
  /**
36
36
  * Sets security headers on the outgoing response.
37
37
  *
@@ -1,12 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkULICUDDHcjs = require('./chunk-ULICUDDH.cjs');
3
+ var _chunkYNKZGZ7Icjs = require('./chunk-YNKZGZ7I.cjs');
4
4
 
5
5
  // src/criteria/path-matches.ts
6
6
  function pathMatches(patterns) {
7
7
  return (req) => {
8
8
  const path = req.uri.split("?")[0];
9
- return _chunkULICUDDHcjs.matchesAnyWildcard.call(void 0, path, patterns);
9
+ return _chunkYNKZGZ7Icjs.matchesAnyWildcard.call(void 0, path, patterns);
10
10
  };
11
11
  }
12
12
 
@@ -4,10 +4,10 @@ var _chunkOTFDML3Kcjs = require('./chunk-OTFDML3K.cjs');
4
4
 
5
5
 
6
6
 
7
- var _chunkIHVOAORHcjs = require('./chunk-IHVOAORH.cjs');
7
+ var _chunkTJ2POKWDcjs = require('./chunk-TJ2POKWD.cjs');
8
8
 
9
9
 
10
- var _chunkULICUDDHcjs = require('./chunk-ULICUDDH.cjs');
10
+ var _chunkYNKZGZ7Icjs = require('./chunk-YNKZGZ7I.cjs');
11
11
 
12
12
  // src/helpers/preflight-request.ts
13
13
  function preflightRequest(options) {
@@ -20,13 +20,13 @@ function preflightRequest(options) {
20
20
  criteria: _chunkOTFDML3Kcjs.methodIs.call(void 0, ["OPTIONS"]),
21
21
  behavior: (request) => {
22
22
  let allowOrigin;
23
- if (allowedOrigins === _chunkIHVOAORHcjs.ORIGIN_WILDCARD) {
23
+ if (allowedOrigins === _chunkTJ2POKWDcjs.ORIGIN_WILDCARD) {
24
24
  allowOrigin = "*";
25
- } else if (allowedOrigins === _chunkIHVOAORHcjs.ORIGIN_ECHO) {
25
+ } else if (allowedOrigins === _chunkTJ2POKWDcjs.ORIGIN_ECHO) {
26
26
  allowOrigin = _optionalChain([request, 'access', _ => _.headers, 'access', _2 => _2["origin"], 'optionalAccess', _3 => _3.value]);
27
27
  } else {
28
28
  const originHeader = _optionalChain([request, 'access', _4 => _4.headers, 'access', _5 => _5["origin"], 'optionalAccess', _6 => _6.value]);
29
- if (originHeader && allowedOrigins.some((p) => _chunkULICUDDHcjs.matchesOriginPattern.call(void 0, originHeader, p))) {
29
+ if (originHeader && allowedOrigins.some((p) => _chunkYNKZGZ7Icjs.matchesOriginPattern.call(void 0, originHeader, p))) {
30
30
  allowOrigin = originHeader;
31
31
  }
32
32
  }