@rayselfs/cf-rule-engine 1.9.0 → 1.9.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.
@@ -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
@@ -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,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
  *
@@ -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 };
@@ -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,5 +1,5 @@
1
1
  /** Represents an HTTP request with URI, method, headers, and querystring. */
2
- interface HttpRequest {
2
+ type HttpRequest = {
3
3
  uri: string;
4
4
  method: string;
5
5
  protocol: string;
@@ -11,16 +11,16 @@ interface HttpRequest {
11
11
  }>;
12
12
  clientIp: string;
13
13
  country?: string;
14
- }
14
+ };
15
15
  /** Represents an HTTP response with status code and headers. */
16
- interface HttpResponse {
16
+ type HttpResponse = {
17
17
  statusCode: number;
18
18
  statusDescription?: string;
19
19
  headers: Record<string, {
20
20
  value: string;
21
21
  }>;
22
22
  body?: string;
23
- }
23
+ };
24
24
  /** A function that evaluates criteria against a request and returns a boolean. */
25
25
  type CriteriaFn = (request: HttpRequest) => boolean;
26
26
  /** Result of a behavior function: either continue processing or respond. */
@@ -36,15 +36,15 @@ type BehaviorFn = (request: HttpRequest) => BehaviorResult;
36
36
  /** A function that modifies an HTTP response. */
37
37
  type ResponseBehaviorFn = (request: HttpRequest, response: HttpResponse) => HttpResponse;
38
38
  /** A response rule: an optional criteria guard plus a ResponseBehaviorFn. */
39
- interface ResponseRule {
39
+ type ResponseRule = {
40
40
  criteria?: CriteriaFn;
41
41
  behavior: ResponseBehaviorFn;
42
- }
42
+ };
43
43
  /** A rule combining optional criteria and a behavior function. */
44
- interface Rule {
44
+ type Rule = {
45
45
  criteria?: CriteriaFn;
46
46
  behavior: BehaviorFn;
47
- }
47
+ };
48
48
  /** Handler for CloudFront viewer request events. */
49
49
  type ViewerRequestHandler = (event: unknown) => unknown;
50
50
  /** Handler for CloudFront viewer response events. */
@@ -1,5 +1,5 @@
1
1
  /** Represents an HTTP request with URI, method, headers, and querystring. */
2
- interface HttpRequest {
2
+ type HttpRequest = {
3
3
  uri: string;
4
4
  method: string;
5
5
  protocol: string;
@@ -11,16 +11,16 @@ interface HttpRequest {
11
11
  }>;
12
12
  clientIp: string;
13
13
  country?: string;
14
- }
14
+ };
15
15
  /** Represents an HTTP response with status code and headers. */
16
- interface HttpResponse {
16
+ type HttpResponse = {
17
17
  statusCode: number;
18
18
  statusDescription?: string;
19
19
  headers: Record<string, {
20
20
  value: string;
21
21
  }>;
22
22
  body?: string;
23
- }
23
+ };
24
24
  /** A function that evaluates criteria against a request and returns a boolean. */
25
25
  type CriteriaFn = (request: HttpRequest) => boolean;
26
26
  /** Result of a behavior function: either continue processing or respond. */
@@ -36,15 +36,15 @@ type BehaviorFn = (request: HttpRequest) => BehaviorResult;
36
36
  /** A function that modifies an HTTP response. */
37
37
  type ResponseBehaviorFn = (request: HttpRequest, response: HttpResponse) => HttpResponse;
38
38
  /** A response rule: an optional criteria guard plus a ResponseBehaviorFn. */
39
- interface ResponseRule {
39
+ type ResponseRule = {
40
40
  criteria?: CriteriaFn;
41
41
  behavior: ResponseBehaviorFn;
42
- }
42
+ };
43
43
  /** A rule combining optional criteria and a behavior function. */
44
- interface Rule {
44
+ type Rule = {
45
45
  criteria?: CriteriaFn;
46
46
  behavior: BehaviorFn;
47
- }
47
+ };
48
48
  /** Handler for CloudFront viewer request events. */
49
49
  type ViewerRequestHandler = (event: unknown) => unknown;
50
50
  /** Handler for CloudFront viewer response events. */
@@ -20,11 +20,11 @@ import { CriteriaFn } from '../core/types.cjs';
20
20
  *
21
21
  * // Apply long-lived cache to static assets
22
22
  * rule(fileExtension(['js', 'css', 'woff2', 'woff']),
23
- * setCacheControl({ maxAge: 31536000 }))
23
+ * setCacheControl('public, max-age=31536000, immutable'))
24
24
  *
25
25
  * // Apply image optimization for image requests
26
- * rule(fileExtension(['jpg', 'jpeg', 'png', 'gif', 'webp']),
27
- * imageOptimize())
26
+ * rule(fileExtension(['jpg', 'jpeg', 'png', 'gif']),
27
+ * imageOptimize({ breakpoints: [320, 640, 960, 1280, 1920] }))
28
28
  * ```
29
29
  */
30
30
  declare function fileExtension(extensions: string[]): CriteriaFn;
@@ -20,11 +20,11 @@ import { CriteriaFn } from '../core/types.js';
20
20
  *
21
21
  * // Apply long-lived cache to static assets
22
22
  * rule(fileExtension(['js', 'css', 'woff2', 'woff']),
23
- * setCacheControl({ maxAge: 31536000 }))
23
+ * setCacheControl('public, max-age=31536000, immutable'))
24
24
  *
25
25
  * // Apply image optimization for image requests
26
- * rule(fileExtension(['jpg', 'jpeg', 'png', 'gif', 'webp']),
27
- * imageOptimize())
26
+ * rule(fileExtension(['jpg', 'jpeg', 'png', 'gif']),
27
+ * imageOptimize({ breakpoints: [320, 640, 960, 1280, 1920] }))
28
28
  * ```
29
29
  */
30
30
  declare function fileExtension(extensions: string[]): CriteriaFn;
@@ -1,8 +1,5 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkVEEOQ7TScjs = require('../chunk-VEEOQ7TS.cjs');
4
-
5
-
6
3
  var _chunkG7JGTBTTcjs = require('../chunk-G7JGTBTT.cjs');
7
4
 
8
5
 
@@ -12,26 +9,29 @@ var _chunkZEFLAOTLcjs = require('../chunk-ZEFLAOTL.cjs');
12
9
  var _chunkLVOM5GJ6cjs = require('../chunk-LVOM5GJ6.cjs');
13
10
 
14
11
 
15
- var _chunkOTFDML3Kcjs = require('../chunk-OTFDML3K.cjs');
12
+ var _chunk32SMWYAFcjs = require('../chunk-32SMWYAF.cjs');
16
13
 
17
14
 
18
- var _chunkOSZWDCTScjs = require('../chunk-OSZWDCTS.cjs');
15
+ var _chunkL7NBJ4JAcjs = require('../chunk-L7NBJ4JA.cjs');
19
16
 
20
17
 
21
- var _chunkU54FZCOHcjs = require('../chunk-U54FZCOH.cjs');
18
+ var _chunkJGJW7D2Ncjs = require('../chunk-JGJW7D2N.cjs');
22
19
 
23
20
 
24
- var _chunk32SMWYAFcjs = require('../chunk-32SMWYAF.cjs');
21
+ var _chunkMK4QBCD5cjs = require('../chunk-MK4QBCD5.cjs');
22
+ require('../chunk-WZKRNMF2.cjs');
25
23
 
26
24
 
27
- var _chunkL7NBJ4JAcjs = require('../chunk-L7NBJ4JA.cjs');
25
+ var _chunkOTFDML3Kcjs = require('../chunk-OTFDML3K.cjs');
28
26
 
29
27
 
30
- var _chunkJGJW7D2Ncjs = require('../chunk-JGJW7D2N.cjs');
28
+ var _chunkVEEOQ7TScjs = require('../chunk-VEEOQ7TS.cjs');
31
29
 
32
30
 
33
- var _chunkMK4QBCD5cjs = require('../chunk-MK4QBCD5.cjs');
34
- require('../chunk-WZKRNMF2.cjs');
31
+ var _chunkOSZWDCTScjs = require('../chunk-OSZWDCTS.cjs');
32
+
33
+
34
+ var _chunkU54FZCOHcjs = require('../chunk-U54FZCOH.cjs');
35
35
  require('../chunk-ULICUDDH.cjs');
36
36
  require('../chunk-75ZPJI57.cjs');
37
37
 
@@ -1,6 +1,3 @@
1
- import {
2
- pathEquals
3
- } from "../chunk-UD456E4I.js";
4
1
  import {
5
2
  pathPrefix
6
3
  } from "../chunk-XLSZ5RB7.js";
@@ -10,15 +7,6 @@ import {
10
7
  import {
11
8
  userAgentMatches
12
9
  } from "../chunk-VQGBRWJK.js";
13
- import {
14
- methodIs
15
- } from "../chunk-PY3JMRDG.js";
16
- import {
17
- countryIs
18
- } from "../chunk-5CPBXZ4X.js";
19
- import {
20
- fileExtension
21
- } from "../chunk-LBJUCJF2.js";
22
10
  import {
23
11
  headerContains
24
12
  } from "../chunk-SRQF5UEJ.js";
@@ -32,6 +20,18 @@ import {
32
20
  ipCidr
33
21
  } from "../chunk-YHTUV2SA.js";
34
22
  import "../chunk-NWRGD3AH.js";
23
+ import {
24
+ methodIs
25
+ } from "../chunk-PY3JMRDG.js";
26
+ import {
27
+ pathEquals
28
+ } from "../chunk-UD456E4I.js";
29
+ import {
30
+ countryIs
31
+ } from "../chunk-5CPBXZ4X.js";
32
+ import {
33
+ fileExtension
34
+ } from "../chunk-LBJUCJF2.js";
35
35
  import "../chunk-EEZ7NUJG.js";
36
36
  import "../chunk-MLKGABMK.js";
37
37
  export {
@@ -1,6 +1,34 @@
1
1
  import { CriteriaFn } from '../core/types.cjs';
2
2
  import { KvsHandle } from '../shared/kvs.cjs';
3
3
 
4
+ /**
5
+ * Loads a CIDR allowlist from CloudFront KeyValueStore and returns a `CriteriaFn`
6
+ * that matches client IPs against the loaded ranges.
7
+ *
8
+ * The KVS value at `key` must be a JSON-encoded `string[]` of CIDR ranges
9
+ * (e.g. `["10.0.0.0/8", "203.0.113.0/24"]`). If the key is absent or the value
10
+ * is empty, no IPs will match.
11
+ *
12
+ * Intended for use with `defineViewerRequestAsync` — the KVS read happens once
13
+ * at setup time.
14
+ *
15
+ * @param handle - KVS handle.
16
+ * @param key - The KVS key whose value is a JSON CIDR array.
17
+ * @returns A `CriteriaFn` to pass to `rule()`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
22
+ * import { rule, not } from '@rayselfs/cf-rule-engine'
23
+ * import { kvsIpCidr } from '@rayselfs/cf-rule-engine/criteria/kvs'
24
+ * import { redirect } from '@rayselfs/cf-rule-engine/behaviors'
25
+ *
26
+ * export default defineViewerRequestAsync(async (event) => {
27
+ * const handle = CloudFront.createKeyValueStore(event)
28
+ * return [rule(not(await kvsIpCidr(handle, 'allowed-cidrs')), redirect(302, 'https://www.example.com'))]
29
+ * })
30
+ * ```
31
+ */
4
32
  declare function kvsIpCidr(handle: KvsHandle, key: string): Promise<CriteriaFn>;
5
33
 
6
34
  export { kvsIpCidr };
@@ -1,6 +1,34 @@
1
1
  import { CriteriaFn } from '../core/types.js';
2
2
  import { KvsHandle } from '../shared/kvs.js';
3
3
 
4
+ /**
5
+ * Loads a CIDR allowlist from CloudFront KeyValueStore and returns a `CriteriaFn`
6
+ * that matches client IPs against the loaded ranges.
7
+ *
8
+ * The KVS value at `key` must be a JSON-encoded `string[]` of CIDR ranges
9
+ * (e.g. `["10.0.0.0/8", "203.0.113.0/24"]`). If the key is absent or the value
10
+ * is empty, no IPs will match.
11
+ *
12
+ * Intended for use with `defineViewerRequestAsync` — the KVS read happens once
13
+ * at setup time.
14
+ *
15
+ * @param handle - KVS handle.
16
+ * @param key - The KVS key whose value is a JSON CIDR array.
17
+ * @returns A `CriteriaFn` to pass to `rule()`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { defineViewerRequestAsync } from '@rayselfs/cf-rule-engine/adapters/viewer-request'
22
+ * import { rule, not } from '@rayselfs/cf-rule-engine'
23
+ * import { kvsIpCidr } from '@rayselfs/cf-rule-engine/criteria/kvs'
24
+ * import { redirect } from '@rayselfs/cf-rule-engine/behaviors'
25
+ *
26
+ * export default defineViewerRequestAsync(async (event) => {
27
+ * const handle = CloudFront.createKeyValueStore(event)
28
+ * return [rule(not(await kvsIpCidr(handle, 'allowed-cidrs')), redirect(302, 'https://www.example.com'))]
29
+ * })
30
+ * ```
31
+ */
4
32
  declare function kvsIpCidr(handle: KvsHandle, key: string): Promise<CriteriaFn>;
5
33
 
6
34
  export { kvsIpCidr };
@@ -9,12 +9,12 @@ var _chunkEMDI676Gcjs = require('../chunk-EMDI676G.cjs');
9
9
  var _chunkLSCC62CZcjs = require('../chunk-LSCC62CZ.cjs');
10
10
  require('../chunk-ZEFLAOTL.cjs');
11
11
  require('../chunk-LVOM5GJ6.cjs');
12
- require('../chunk-OTFDML3K.cjs');
13
12
 
14
13
 
15
14
  var _chunkL7NBJ4JAcjs = require('../chunk-L7NBJ4JA.cjs');
16
15
  require('../chunk-MK4QBCD5.cjs');
17
16
  require('../chunk-WZKRNMF2.cjs');
17
+ require('../chunk-OTFDML3K.cjs');
18
18
  require('../chunk-IHVOAORH.cjs');
19
19
  require('../chunk-ULICUDDH.cjs');
20
20
 
@@ -9,12 +9,12 @@ import {
9
9
  } from "../chunk-C32DL3EP.js";
10
10
  import "../chunk-Y7TIDVVC.js";
11
11
  import "../chunk-VQGBRWJK.js";
12
- import "../chunk-PY3JMRDG.js";
13
12
  import {
14
13
  headerEquals
15
14
  } from "../chunk-BZQJYOU2.js";
16
15
  import "../chunk-YHTUV2SA.js";
17
16
  import "../chunk-NWRGD3AH.js";
17
+ import "../chunk-PY3JMRDG.js";
18
18
  import "../chunk-H3RK4USR.js";
19
19
  import "../chunk-EEZ7NUJG.js";
20
20
  import {
@@ -3,7 +3,7 @@ import { Rule } from '../core/types.cjs';
3
3
  /**
4
4
  * Configuration options for the IP/User-Agent access whitelist.
5
5
  */
6
- interface WhitelistOptions {
6
+ type WhitelistOptions = {
7
7
  /**
8
8
  * CIDR ranges to allow (e.g. office IPs, VPN, stage VPCs).
9
9
  * At least one of `cidrs` or `userAgents` must be non-empty, otherwise
@@ -32,7 +32,7 @@ interface WhitelistOptions {
32
32
  * @example `['/api/health', '/public/*']`
33
33
  */
34
34
  bypassPaths?: string[];
35
- }
35
+ };
36
36
  /**
37
37
  * Creates a `Rule` that restricts access by IP CIDR range and/or User-Agent
38
38
  * pattern. Any request that does not match an allowed CIDR or User-Agent
@@ -3,7 +3,7 @@ import { Rule } from '../core/types.js';
3
3
  /**
4
4
  * Configuration options for the IP/User-Agent access whitelist.
5
5
  */
6
- interface WhitelistOptions {
6
+ type WhitelistOptions = {
7
7
  /**
8
8
  * CIDR ranges to allow (e.g. office IPs, VPN, stage VPCs).
9
9
  * At least one of `cidrs` or `userAgents` must be non-empty, otherwise
@@ -32,7 +32,7 @@ interface WhitelistOptions {
32
32
  * @example `['/api/health', '/public/*']`
33
33
  */
34
34
  bypassPaths?: string[];
35
- }
35
+ };
36
36
  /**
37
37
  * Creates a `Rule` that restricts access by IP CIDR range and/or User-Agent
38
38
  * pattern. Any request that does not match an allowed CIDR or User-Agent
@@ -1,5 +1,10 @@
1
- interface KvsHandle {
1
+ /**
2
+ * Minimal interface for a CloudFront KeyValueStore handle.
3
+ * Compatible with the handle returned by `CloudFront.createKeyValueStore(event)`
4
+ * in the CF Function runtime.
5
+ */
6
+ type KvsHandle = {
2
7
  get(key: string): Promise<string | undefined>;
3
- }
8
+ };
4
9
 
5
10
  export type { KvsHandle };
@@ -1,5 +1,10 @@
1
- interface KvsHandle {
1
+ /**
2
+ * Minimal interface for a CloudFront KeyValueStore handle.
3
+ * Compatible with the handle returned by `CloudFront.createKeyValueStore(event)`
4
+ * in the CF Function runtime.
5
+ */
6
+ type KvsHandle = {
2
7
  get(key: string): Promise<string | undefined>;
3
- }
8
+ };
4
9
 
5
10
  export type { KvsHandle };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rayselfs/cf-rule-engine",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "Composable, tree-shakeable CloudFront Function rules",
5
5
  "license": "MIT",
6
6
  "sideEffects": false,