diff --git a/.changeset/config-api-v6.md b/.changeset/config-api-v6.md new file mode 100644 index 00000000..be5c1fc6 --- /dev/null +++ b/.changeset/config-api-v6.md @@ -0,0 +1,9 @@ +--- +'@aziontech/config': minor +'@aziontech/presets': minor +--- + +Support the Azion API v6 config in the same packages. + +- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments` and `deployments` (the environment and deployment policies are required) and workloads with `bindings` (a binding references an environment and a deployment by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. The v6 API has no `active` in its resources, so the v6 config and manifest do not have it, and the `createSPARules` and `createMPARules` helpers no longer write `active: true` (it is the default of the v4 and v3 rules). +- `@aziontech/presets`: every preset now provides its v6 config in `configs[6]` (`nitro` has no v3 config, as it did not exist on v3). `config` remains the default (v4) config. diff --git a/.changeset/fix-nuxt-manifest.md b/.changeset/fix-nuxt-manifest.md new file mode 100644 index 00000000..efdb425d --- /dev/null +++ b/.changeset/fix-nuxt-manifest.md @@ -0,0 +1,5 @@ +--- +'@aziontech/presets': patch +--- + +Fix the `nuxt` preset prebuild reading a stale or missing manifest. Nuxt >= 4.6 builds into `node_modules/.cache/nuxt/.nuxt` when `.nuxt` already exists, so `.nuxt/manifest/meta` is no longer reliable. The manifest is now read from `.output/public/_nuxt/builds/meta` first, then from the cache dir and `.nuxt`, picking the file that `latest.json` references. diff --git a/.changeset/fix-subpaths-regex.md b/.changeset/fix-subpaths-regex.md new file mode 100644 index 00000000..c96ec034 --- /dev/null +++ b/.changeset/fix-subpaths-regex.md @@ -0,0 +1,5 @@ +--- +'@aziontech/presets': patch +--- + +Fix the regex of the "Redirect to index.html for Subpaths" rule of the `nuxt`, `svelte` and `nitro` presets (v4 and v6 configs). It matched files such as `/logo.png` and skipped the paths without extension such as `/about`, because of `[sS]*` (instead of `[\s\S]*`) and an unescaped `.`. It now matches only the paths that do not end with `/` and have no file extension. diff --git a/package.json b/package.json index 9da3131d..3b32e649 100644 --- a/package.json +++ b/package.json @@ -58,15 +58,20 @@ "prettier": "^3.9.6", "typescript": "^5.9.3", "typescript-eslint": "^8.69.0", - "vite": "^7.3.6", + "vite": "^7.3.7", "vite-plugin-dts": "^4.5.4" }, "pnpm": { + "auditConfig": { + "ignoreGhsas": [ + "GHSA-gcqx-w48m-w2h4" + ] + }, "overrides": { "lodash": ">=4.18.0", "postcss": ">=8.5.18", - "fast-uri": ">=4.1.5", - "qs": ">=6.15.2", + "fast-uri": ">=4.2.3", + "qs": ">=6.16.1", "esbuild": ">=0.28.1", "source-map-js": ">=1.2.2", "brace-expansion@1": "^1.1.17", @@ -77,7 +82,11 @@ "js-yaml@3>argparse": "^2.0.1", "@rushstack/ts-command-line>argparse": "^2.0.1", "@babel/core": ">=7.29.6", - "@babel/plugin-transform-modules-systemjs": ">=7.29.4" + "@babel/plugin-transform-modules-systemjs": ">=7.29.4", + "handlebars": ">=4.7.10", + "vite@7": "^7.3.7", + "minimatch@<11.0.1": ">=11.0.1", + "glob@<14.0.2": ">=14.0.2" } }, "workspaces": [ diff --git a/packages/config/README.md b/packages/config/README.md index d34cf6da..f95210ef 100644 --- a/packages/config/README.md +++ b/packages/config/README.md @@ -2,6 +2,9 @@ This module provides comprehensive configuration and validation for the Azion Platform. It supports applications, workloads, connectors, functions, storage, firewall rules, WAF settings, network lists, custom pages, and purge operations. +> **Config API versions:** the examples below are for the default config (Azion API v4). The package also processes the +> v3 and v6 configs, selected with the `version` field of the config. See [Azion config for the API v6](https://github.com/aziontech/lib/blob/main/packages/config/docs/config-v6.md). + ## Table of Contents - [Installation](#installation) diff --git a/packages/config/docs/config-v6.md b/packages/config/docs/config-v6.md new file mode 100644 index 00000000..a8f61381 --- /dev/null +++ b/packages/config/docs/config-v6.md @@ -0,0 +1,307 @@ +# Azion config for the API v6 + +The Azion API v6 changes how a project is published, so it has its own `azion.config` shape. `@aziontech/config` validates +and processes it into a v6 `manifest.json`, which the Azion CLI uses to create the resources. + +> **Status:** the v6 schemas follow the v6 OpenAPI and may change while the Azion CLI implements the API calls. The v4 config +> is still the default: a config without `version` is a v4 one, and the examples of the README are v4. + +## Using it + +Declare `version: 6` in the config (the type `AzionConfigV6` is exported by the package): + +```typescript +import { defineConfig, processConfig, validateConfig } from '@aziontech/config'; + +const config = defineConfig({ + version: 6, + // ... +}); + +validateConfig(config); // throws on an invalid config +const manifest = processConfig(config); // the v6 manifest, with `version: 6` +``` + +With the Azion Bundler, the version comes from the `version` of the `azion.config`, or from the flag +`--config-version 6` (the flag and the file must not disagree): + +```sh +azbundler build --preset react --config-version 6 +azbundler manifest generate --config-file ./azion.config.ts +``` + +Every preset of `@aziontech/presets` has a v6 config (`configs[6]`). + +## What changes from v4 + +| v4 | v6 | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Saving publishes | Saving writes a draft, and publishing is a separate step done by the CLI | +| `workloads[].domains` and `workloads[].tls.certificate` | `workloads[].bindings[].domains[{ domain, certificate }]`: each binding has the domains and the certificate of an environment | +| No environments | `environments[]`: `name` and `deploymentPolicy` (`single_version` or `versioned_urls`, required and immutable) | +| `workloads[].deployments` with the `strategy` (application, firewall, custom page) | `deployments[]`: `name`, `bindingPolicy` (required), `description`, `deploymentPolicy` (`single_version`, `versioned_urls` or `latest`) and `strategyDefaults.skewProtection`. The application a deployment serves is set by the CLI in a release | +| `active` in applications, rules, functions, function instances, connectors, addresses, firewalls, WAFs, network lists, custom pages and workloads | Removed: the v6 API has no `active` in any resource | +| `edgeCacheEnabled` can be `false` | The cache module cannot be disabled: only `true` | +| Purge `layer`: `cache` or `tiered_cache` | `cache` only | +| Device group `name` of any text | Letters and numbers only (`^[a-zA-Z0-9]+$`) | +| Workload `protocols.http.versions` of any combination | Must include `http1` and `http2` | +| Functions without dependencies | `functions[].dependencies`: up to 20 connectors or network lists the function uses at runtime | +| `tls.ciphers` can be `null` | `tls.ciphers` is not nullable | +| Rule variables of any phase | Each variable is valid only in the phases the API documents | +| Firewall `set_waf.mode`: `learning \| blocking` | `logging \| blocking` | +| `kv` | Not available | + +The behaviors and criterion variables of the rules need the modules the API documents. An application needs +`applicationAcceleratorEnabled` for every variable except `${uri}` and for `forward_cookies`, `filter_request_cookie`, +`rewrite_request`, `capture_match_groups`, `add_request_cookie` and `set_cookie`, `imageProcessorEnabled` for +`optimize_images`, and functions (`functionsEnabled`, or declared `functionsInstances`) for `run_function`. A firewall needs +at least one of its modules (`functions`, `networkProtection`, `waf`) for each behavior, `waf` for the header, `request_args` +and `request_method` variables, `networkProtection` for `network`, and `functions` for `run_function`. The config fails with +a message naming the rule and the module when one is missing. + +A workload with `workloadDomainAllowAccess: true` (the default) cannot be bound to an environment whose `deploymentPolicy` is +`versioned_urls`; for such a workload the default becomes `false`. + +Resource limits also follow the v6 API: names of 100 characters at most for applications and rules, cache max age up to one +year, 23 pages at most in a custom page, storage names with the pattern `^[a-z0-9][a-z0-9-]*[a-z0-9]$`, and so on. + +A **binding** references an environment (declared in `environments`) and a deployment (declared in `deployments`) by name. The +function and connector of the rules, and the WAF of a firewall rule, accept the name of a resource declared in the config, or +its ID (an ID is not validated). + +## Complete example + +This is every resource the v6 config has, with the references between them: + +```typescript +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + entry: './src/index.js', + polyfills: true, + }, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + bindings: { + storage: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + // connectors and network lists the function uses at runtime, which a release includes with it + dependencies: [ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-ip-allowlist' }, + ], + }, + ], + storage: [ + { + name: 'my-bucket-assets', + prefix: 'v1', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: 'my-storage-connector', + type: 'storage', + attributes: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + { + name: 'my-origin', + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'force_https', + host: 'origin.example.com', + followingRedirect: false, + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 3, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + }, + }, + }, + ], + applications: [ + { + name: 'my-app', + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + cache: [ + { + name: 'my-cache', + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 7200 }, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'denylist', list: ['order', 'user'] }, + }, + ], + rules: { + request: [ + { + name: 'Run the function', + description: 'Run the function for the API paths', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], + }, + { + name: 'Serve from the storage', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [ + { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, + { type: 'set_connector', attributes: { value: 'my-storage-connector' } }, + ], + }, + ], + response: [ + { + name: 'Add a header', + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], + }, + ], + }, + functionsInstances: [ + { + name: 'my-function-instance', + ref: 'my-function', + args: { greeting: 'hello' }, + }, + ], + deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }], + }, + ], + customPages: [ + { + name: 'my-custom-pages', + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-storage-connector', ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ], + networkList: [ + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'] }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'] }, + ], + waf: [ + { + name: 'my-waf', + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [ + { threat: 'sql_injection', sensitivity: 'high' }, + { threat: 'cross_site_scripting', sensitivity: 'high' }, + ], + }, + }, + }, + ], + firewall: [ + { + name: 'my-firewall', + debugRules: false, + functions: false, + networkProtection: true, + waf: true, + rules: [ + { + name: 'Allow the trusted networks', + criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], + behaviors: [{ type: 'bypass' }], + }, + { + name: 'Protect with the WAF', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], + }, + ], + }, + ], + environments: [ + { + name: 'production', + description: 'Production environment', + deploymentPolicy: 'single_version', + logVerbosity: 'normal', + robotsPolicy: 'respect_origin', + }, + ], + // the application, firewall and custom page a deployment serves are set by the Azion CLI when it creates the release + deployments: [ + { + name: 'my-deployment', + description: 'Main deployment', + bindingPolicy: 'FLEXIBLE', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + workloads: [ + { + name: 'my-workload', + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { minimumVersion: 'tls_1_3' }, + protocols: { + http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, + }, + bindings: [ + { + environment: 'production', + deployment: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ], + }, + ], + purge: [{ type: 'url', items: ['https://example.com/index.html'], layer: 'cache' }], +}; +``` + +## The manifest + +`processConfig` writes the same blocks as v4 (`build`, `functions`, `storage`, `connectors`, `applications`, `firewall`, +`custom_pages`, ...) plus: + +- `version: 6`. +- `environments` and `deployments`: the environments and the deployments, with the fields the API requires filled with defaults. +- `workloads[].bindings`: each binding names its environment and deployment in `environment_name` and `deployment_name`. + The Azion CLI creates both and resolves the names to their IDs. + +The v6 `tls.ciphers` is left out of the workload when not set. + +## What is not in the v6 config yet + +- `kv`. +- `code` and `azion_form` of the functions: the config keeps `path`. +- Rollout, versions and releases: they are operations of the Azion CLI and the API, not part of the config. diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index 5fae08bb..e360a441 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -6,6 +6,7 @@ import { } from './configProcessor/helpers/convertLegacyConfig'; import { AzionConfig } from './types'; import type { AzionConfigV3 } from './versions/v3/types'; +import type { AzionConfigV6 } from './versions/v6/types'; import { getApplicationName, getFirewallReplacedKeys, getStorage } from './versions/accessors'; import { getPresetApiVersions, resolvePresetConfig } from './versions/presetConfig'; import { @@ -20,7 +21,7 @@ import { DEFAULT_API_VERSION } from './versions/types'; * Helper function to provide IntelliSense for Azion configuration. * Similar to Vite's defineConfig - provides type safety without runtime overhead. * - * Declare `version: 3` to get the Azion API v3 types (the remaining v3 types live under the `V3` namespace). + * Declare `version: 3` or `version: 6` to get the types of that Azion API version (the remaining types live under the `V3` and `V6` namespaces). * * @param {AnyAzionConfig} config - The configuration object for the Azion Platform. * @returns {AzionConfig} The same configuration object (no validation or processing) @@ -39,8 +40,11 @@ import { DEFAULT_API_VERSION } from './versions/types'; * }); */ function defineConfig(config: AzionConfigV3): AzionConfigV3; +function defineConfig(config: AzionConfigV6): AzionConfigV6; function defineConfig(config: AzionConfig): AzionConfig; -function defineConfig(config: AzionConfig | AzionConfigV3): AzionConfig | AzionConfigV3 { +function defineConfig( + config: AzionConfig | AzionConfigV3 | AzionConfigV6, +): AzionConfig | AzionConfigV3 | AzionConfigV6 { return config; } @@ -67,5 +71,6 @@ export { export type * from './types'; export type { AnyAzionConfig, ApiVersion, ConfigByVersion, ConfigVersionModule } from './versions/types'; -export type { AzionConfigV3 }; +export type { AzionConfigV3, AzionConfigV6 }; export type * as V3 from './versions/v3/types'; +export type * as V6 from './versions/v6/types'; diff --git a/packages/config/src/rules/request/createMPA.test.ts b/packages/config/src/rules/request/createMPA.test.ts index 2ae2458f..a2d11f7a 100644 --- a/packages/config/src/rules/request/createMPA.test.ts +++ b/packages/config/src/rules/request/createMPA.test.ts @@ -19,7 +19,6 @@ describe('createMPARules', () => { expect(staticAssetsRule).toEqual({ name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -54,7 +53,6 @@ describe('createMPARules', () => { expect(directoryIndexRule).toEqual({ name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -86,7 +84,6 @@ describe('createMPARules', () => { expect(subpathIndexRule).toEqual({ name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createMPA.ts b/packages/config/src/rules/request/createMPA.ts index 286858ca..20fc5370 100644 --- a/packages/config/src/rules/request/createMPA.ts +++ b/packages/config/src/rules/request/createMPA.ts @@ -30,7 +30,6 @@ export function createMPARules( { name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -62,7 +61,6 @@ export function createMPARules( { name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -91,7 +89,6 @@ export function createMPARules( { name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createSPA.test.ts b/packages/config/src/rules/request/createSPA.test.ts index b7acd3fc..b64b8bec 100644 --- a/packages/config/src/rules/request/createSPA.test.ts +++ b/packages/config/src/rules/request/createSPA.test.ts @@ -19,7 +19,6 @@ describe('createSPARules', () => { expect(staticAssetsRule).toEqual({ name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -54,7 +53,6 @@ describe('createSPARules', () => { expect(indexRedirectRule).toEqual({ name: 'Redirect to index.html', description: 'Handle all routes by rewriting to index.html for client-side routing', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createSPA.ts b/packages/config/src/rules/request/createSPA.ts index e98679a6..d15d4ba7 100644 --- a/packages/config/src/rules/request/createSPA.ts +++ b/packages/config/src/rules/request/createSPA.ts @@ -30,7 +30,6 @@ export function createSPARules( { name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -62,7 +61,6 @@ export function createSPARules( { name: 'Redirect to index.html', description: 'Handle all routes by rewriting to index.html for client-side routing', - active: true, criteria: [ [ { diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index 25771d5a..aa196c50 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from '@jest/globals'; import { getApplicationName, getFirewallReplacedKeys, getStorage } from './accessors'; +import v4Schema from './v4/schemas/schema'; +import v6Schema from './v6/schemas/schema'; const v4 = { applications: [{ name: 'app-1' }, { name: 'app-2' }], @@ -20,6 +22,8 @@ describe('version accessors', () => { expect(getApplicationName(v4)).toBe('app-1'); expect(getApplicationName({})).toBeUndefined(); expect(getApplicationName(v3)).toBeUndefined(); + expect(getApplicationName({ version: 6, applications: [{ name: 'app-6' }] })).toBe('app-6'); + expect(getApplicationName({ version: 6 })).toBeUndefined(); }); it('reads the storage where each version keeps it', () => { @@ -29,6 +33,28 @@ describe('version accessors', () => { prefix: '', }); expect(getStorage(v3)).toEqual({ bucket: 'bucket-3', prefix: 'p3' }); + expect(getStorage({ version: 6, storage: [{ name: 'bucket-6', prefix: 'p6', dir: './dist' }] })).toEqual({ + bucket: 'bucket-6', + prefix: 'p6', + }); + }); + + it('reads the first v6 storage and falls back to an empty prefix, as the prefix is optional in v6', () => { + expect(getStorage({ version: 6, storage: [{ name: 'bucket-6', dir: './dist' }] })).toEqual({ + bucket: 'bucket-6', + prefix: '', + }); + expect( + getStorage({ + version: 6, + storage: [ + { name: 'first-bucket', dir: './a' }, + { name: 'second-bucket', dir: './b' }, + ], + }), + ).toEqual({ bucket: 'first-bucket', prefix: '' }); + expect(getStorage({ version: 6 })).toBeUndefined(); + expect(getStorage({ version: 6, storage: [] })).toBeUndefined(); }); it('returns undefined when the config has no storage', () => { @@ -50,5 +76,22 @@ describe('version accessors', () => { it('lists the preset keys a firewall-only project must not inherit', () => { expect(getFirewallReplacedKeys(4)).toEqual(['applications', 'workloads', 'connectors', 'functions']); expect(getFirewallReplacedKeys(3)).toEqual(['origin', 'cache', 'rules', 'functions']); + expect(getFirewallReplacedKeys(6)).toEqual([ + 'applications', + 'workloads', + 'connectors', + 'functions', + 'environments', + 'deployments', + ]); + }); + + it('lists only keys that exist in the config schema of each version', () => { + const properties = (schema: { definitions: { mainConfig: { properties: object } } }) => + Object.keys(schema.definitions.mainConfig.properties); + const schemas = { 4: properties(v4Schema), 6: properties(v6Schema) }; + + getFirewallReplacedKeys(4).forEach((key) => expect(schemas[4]).toContain(key)); + getFirewallReplacedKeys(6).forEach((key) => expect(schemas[6]).toContain(key)); }); }); diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 67725a98..998e73f7 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -55,8 +55,9 @@ describe('version dispatch', () => { expect(processConfig({ ...config, version: 4 })).toEqual(processConfig(config)); }); - it('does not leak version into the manifest', () => { - expect(processConfig({ ...config, version: 4 })).not.toHaveProperty('version'); + it('writes the version to the manifest, the default one when it is not declared', () => { + expect(processConfig({ ...config, version: 4 })).toHaveProperty('version', 4); + expect(processConfig(config)).toHaveProperty('version', 4); }); it('rejects a config that declares an unsupported version', () => { @@ -106,7 +107,7 @@ describe('v3 support', () => { expect(manifest).toHaveProperty('origin'); expect(manifest).toHaveProperty('rules'); expect(manifest).not.toHaveProperty('applications'); - expect(manifest).not.toHaveProperty('version'); + expect(manifest).toHaveProperty('version', 3); }); it('rejects v3-only fields on a v4 config and vice versa', () => { @@ -121,3 +122,82 @@ describe('v3 support', () => { expect(v4.version).toBeUndefined(); }); }); + +describe('v6 support', () => { + const v6Config = { version: 6 as const, build: { bundler: 'esbuild' as const } }; + + it('is registered and selected by `version: 6`', () => { + expect(resolveApiVersion(v6Config)).toBe(6); + expect(getVersionModule(6).version).toBe(6); + expect(SUPPORTED_API_VERSIONS).toContain(6); + }); + + it('keeps v4 as the default when version is omitted', () => { + expect(DEFAULT_API_VERSION).toBe(4); + expect(resolveApiVersion({ build: {} })).toBe(4); + }); + + it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { + expect(() => validateConfig(v6Config)).not.toThrow(); + expect(() => validateConfig({ version: 6, kv: [] })).toThrow(); + }); + + it('does not accept v6 on the v4 schema nor the other way around', () => { + expect(() => validateConfig({ version: 4, build: {} })).not.toThrow(); + expect(() => validateConfig({ version: 6, origin: [] })).toThrow(); + }); + + it('writes the version, the build and the applications to the v6 manifest', () => { + expect(processConfig(v6Config)).toEqual({ + version: 6, + build: v6Config.build, + functions: [], + applications: [], + firewall: [], + custom_pages: [], + environments: [], + deployments: [], + workloads: [], + }); + }); + + it('processes the v6 applications into the manifest', () => { + const manifest = processConfig({ ...v6Config, applications: [{ name: 'my-app' }] }); + expect(manifest.applications).toEqual([ + { + name: 'my-app', + debug: false, + modules: { + cache: { enabled: true }, + functions: { enabled: false }, + application_accelerator: { enabled: true }, + image_processor: { enabled: false }, + }, + }, + ]); + }); + + it('processes the v6 network lists into the network_list key of the manifest', () => { + const manifest = processConfig({ + ...v6Config, + networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }], + }); + + expect(manifest.network_list).toEqual([{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }]); + }); + + it('forwards the version to manifest helpers', () => { + expect(() => validateManifest({}, undefined, { version: 6 })).not.toThrow(); + expect(() => convertJsonConfigToObject('{', { version: 6 })).toThrow('Invalid JSON configuration.'); + expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6, firewall: [], applications: [] }); + expect(convertJsonConfigToObject(JSON.stringify(processConfig(v6Config)), { version: 6 })).toEqual({ + ...v6Config, + firewall: [], + applications: [], + }); + }); + + it('types defineConfig by the declared version', () => { + expect(defineConfig(v6Config).version).toBe(6); + }); +}); diff --git a/packages/config/src/versions/registry.ts b/packages/config/src/versions/registry.ts index f2a4e9e3..8fccd65f 100644 --- a/packages/config/src/versions/registry.ts +++ b/packages/config/src/versions/registry.ts @@ -1,10 +1,12 @@ import { ApiVersion, ConfigVersionModule, DEFAULT_API_VERSION } from './types'; import v3 from './v3'; import v4 from './v4'; +import v6 from './v6'; const registry: Record = { 3: v3, 4: v4, + 6: v6, }; /** diff --git a/packages/config/src/versions/schemaStrictMode.test.ts b/packages/config/src/versions/schemaStrictMode.test.ts new file mode 100644 index 00000000..3a790da8 --- /dev/null +++ b/packages/config/src/versions/schemaStrictMode.test.ts @@ -0,0 +1,50 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +import v3Schema from './v3/schemas/schema'; +import { schemaManifest as v3Manifest } from './v3/schemas/schemaManifest'; +import v4Schema from './v4/schemas/schema'; +import { schemaManifest as v4Manifest } from './v4/schemas/schemaManifest'; +import v6Schema from './v6/schemas/schema'; +import { schemaManifest as v6Manifest } from './v6/schemas/schemaManifest'; + +// The validators compile the whole schema of a version on every call, even if the config does not use a resource, so a +// schema that breaks the strict mode of ajv (e.g. `pattern` without `type: 'string'`) warns for every config. +// Jest only prints the console of a failing suite, so the warnings are captured here and checked. +function compileWarnings(schema: Record) { + const warnings: string[] = []; + const ajv = new Ajv({ + allErrors: true, + $data: true, + allowUnionTypes: true, + logger: { + log: () => undefined, + warn: (message: unknown) => warnings.push(String(message)), + error: (message: unknown) => warnings.push(String(message)), + }, + }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + ajv.compile(schema); + return warnings; +} + +describe('schemas compile in the strict mode of ajv', () => { + it.each([ + ['v3 config', v3Schema], + ['v3 manifest', v3Manifest], + ['v4 config', v4Schema], + ['v4 manifest', v4Manifest], + ['v6 config', v6Schema], + ['v6 manifest', v6Manifest], + ])('%s has no warnings', (_name, schema) => { + expect(compileWarnings(schema as Record)).toEqual([]); + }); + + it('catches a schema that breaks the strict mode', () => { + const warnings = compileWarnings({ type: 'object', properties: { items: { pattern: '^[0-9]+$' } } }); + + expect(warnings.join('\n')).toContain('missing type "string" for keyword "pattern"'); + }); +}); diff --git a/packages/config/src/versions/shared/converterJsonConfig.ts b/packages/config/src/versions/shared/converterJsonConfig.ts new file mode 100644 index 00000000..ce5db427 --- /dev/null +++ b/packages/config/src/versions/shared/converterJsonConfig.ts @@ -0,0 +1,38 @@ +import type ProcessConfigContext from './processStrategy/processConfigContext'; + +type JsonConfigConverterOptions = { + /** Validates the parsed manifest. Throws on failure. */ + validate: (manifest: Record) => void; + /** Builds the strategy context of the API version. */ + factoryProcessContext: () => ProcessConfigContext; + /** Builds the config object the strategies fill. */ + createConfig: () => TConfig; +}; + +/** + * Creates the function that converts a JSON manifest string into a config object of an API version. + * @throws {Error} The returned function throws if the provided JSON string is invalid. + */ +function createJsonConfigConverter({ + validate, + factoryProcessContext, + createConfig, +}: JsonConfigConverterOptions) { + return function convertJsonConfigToObject(config: string): TConfig { + let configObject: Record; + try { + configObject = JSON.parse(config); + } catch { + throw new Error('Invalid JSON configuration.'); + } + validate(configObject); + const payloadConfig = createConfig(); + const processConfigContext = factoryProcessContext(); + + processConfigContext.transformToConfig(configObject, payloadConfig); + + return payloadConfig; + }; +} + +export { createJsonConfigConverter }; diff --git a/packages/config/src/versions/shared/processStrategy/processConfigContext.ts b/packages/config/src/versions/shared/processStrategy/processConfigContext.ts new file mode 100644 index 00000000..2e8865ef --- /dev/null +++ b/packages/config/src/versions/shared/processStrategy/processConfigContext.ts @@ -0,0 +1,47 @@ +import ProcessConfigStrategy from './processConfigStrategy'; + +/** + * ProcessConfigContext + * @class + * @description This class is responsible for generating the context of the process config. + * `TConfig` is the config shape of the API version. + */ +class ProcessConfigContext { + strategies: { [key: string]: ProcessConfigStrategy }; + constructor() { + this.strategies = {}; + } + + setStrategy(type: string, strategy: ProcessConfigStrategy): void { + this.strategies[type] = strategy; + } + /** + * Transform to manifest is responsible for transforming the config to the manifest. + * @param config Config of the API version + * @param context manifest object + * @returns + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToManifest(config: TConfig, context: any) { + Object.keys(this.strategies).forEach((key) => { + context[key] = this.strategies[key].transformToManifest(config, context); + }); + return context; + } + + /** + * Transform to config is responsible for transforming the payload to the config. + * @param payload Manifest object + * @param transformedPayload Config object of the API version + * @returns + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: TConfig): TConfig { + Object.keys(this.strategies).forEach((key) => { + payload[key] = this.strategies[key].transformToConfig(payload, transformedPayload); + }); + return payload; + } +} + +export default ProcessConfigContext; diff --git a/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts b/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts new file mode 100644 index 00000000..1b35d8cd --- /dev/null +++ b/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts @@ -0,0 +1,18 @@ +/** + * ProcessConfigStrategy + * @class ProcessConfigStrategy + * @description Base class of the process config strategies. `TConfig` is the config shape of the API version. + */ +class ProcessConfigStrategy { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToManifest(config: any, context: any) { + return context; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars + transformToConfig(payload: any, transformedPayload: TConfig): TConfig | any { + return payload; + } +} + +export default ProcessConfigStrategy; diff --git a/packages/config/src/versions/shared/schemas/build.ts b/packages/config/src/versions/shared/schemas/build.ts new file mode 100644 index 00000000..1660aae8 --- /dev/null +++ b/packages/config/src/versions/shared/schemas/build.ts @@ -0,0 +1,92 @@ +import { BUILD_BUNDLERS } from '../../../constants'; + +const buildSchema = { + type: 'object', + properties: { + entry: { + oneOf: [ + { type: 'string' }, + { type: 'array', items: { type: 'string' } }, + { type: 'object', additionalProperties: { type: 'string' } }, + ], + errorMessage: "The 'build.entry' must be a string, array of strings, or object with string values", + }, + bundler: { + type: 'string', + enum: BUILD_BUNDLERS, + errorMessage: "The 'build.bundler' must be either 'webpack' or 'esbuild'", + }, + preset: { + anyOf: [ + { type: 'string' }, + { + type: 'object', + properties: { + metadata: { + type: 'object', + properties: { + name: { + type: 'string', + errorMessage: "The 'name' field in preset metadata must be a string", + }, + ext: { + type: 'string', + errorMessage: "The 'ext' field in preset metadata must be a string", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in preset metadata', + required: "The 'name' field is required in preset metadata", + }, + }, + config: { + $ref: '#/definitions/mainConfig', + }, + handler: { instanceof: 'Function' }, + prebuild: { instanceof: 'Function' }, + postbuild: { instanceof: 'Function' }, + }, + required: ['metadata', 'config'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in preset', + required: "Preset must contain both 'metadata' and 'config' properties", + }, + }, + ], + errorMessage: 'Preset must be either a string or an object with preset properties', + }, + polyfills: { + type: 'boolean', + errorMessage: "The 'build.polyfills' must be a boolean", + }, + worker: { + type: 'boolean', + errorMessage: "The 'build.worker' must be a boolean", + }, + extend: { + instanceof: 'Function', + errorMessage: "The 'build.extend' must be a function", + }, + memoryFS: { + type: 'object', + properties: { + injectionDirs: { + type: 'array', + items: { type: 'string' }, + }, + removePathPrefix: { type: 'string' }, + }, + required: ['injectionDirs', 'removePathPrefix'], + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'build' object", + }, +}; + +export default buildSchema; diff --git a/packages/config/src/versions/shared/validateConfig.ts b/packages/config/src/versions/shared/validateConfig.ts new file mode 100644 index 00000000..af20df11 --- /dev/null +++ b/packages/config/src/versions/shared/validateConfig.ts @@ -0,0 +1,60 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +const MAX_REPORTED_ERRORS = 3; + +function formatErrors(errors: unknown[]) { + const messages = errors + .slice(0, MAX_REPORTED_ERRORS) + .map((error: unknown, index: number) => { + const errorObject = error as { + message: string; + instancePath: string; + params: { missingProperty?: string | undefined }; + }; + + return [ + `📍 Error #${index + 1}:`, + ` Message: ${errorObject.message}`, + errorObject.instancePath ? ` Path: ${errorObject.instancePath}` : null, + errorObject.params?.missingProperty ? ` Missing Property: ${errorObject.params.missingProperty}` : null, + ] + .filter(Boolean) + .join('\n'); + }) + .join('\n\n'); + + const moreErrorsNote = + errors.length > MAX_REPORTED_ERRORS ? `\n\n... and ${errors.length - MAX_REPORTED_ERRORS} more error(s)` : ''; + + return `⛔️ Azion Configuration Validation Failed\n${'-'.repeat(50)}\n${messages}${moreErrorsNote}\n${'-'.repeat(50)}`; +} + +/** + * Creates the config validator of an API version. + * The validator uses AJV (Another JSON Schema Validator) and throws an error that reports the first validation issues. + * @param {object} defaultSchema - JSON Schema of the version's config, used when the caller does not pass one. + * @returns A function that validates a config and throws an error if it fails validation. + */ +function createConfigValidator(defaultSchema: Record) { + return function validateConfig( + config: TConfig | Record, + schema: Record = defaultSchema, + ) { + const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + const validate = ajv.compile(schema); + const valid = validate(config); + + if (!valid) { + if (validate.errors && validate.errors.length > 0) { + throw new Error(formatErrors(validate.errors)); + } + throw new Error('Azion validation failed.'); + } + }; +} + +export { createConfigValidator }; diff --git a/packages/config/src/versions/shared/validateManifest.ts b/packages/config/src/versions/shared/validateManifest.ts new file mode 100644 index 00000000..5cd5333f --- /dev/null +++ b/packages/config/src/versions/shared/validateManifest.ts @@ -0,0 +1,27 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +/** + * Creates the manifest validator of an API version. + * @param {object} defaultSchema - JSON Schema of the version's manifest, used when the caller does not pass one. + * @returns A function that validates a manifest and throws an error if it fails validation. + */ +function createManifestValidator(defaultSchema: Record) { + return function validateManifest(manifest: Record, schema: Record = defaultSchema) { + const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + const validate = ajv.compile(schema); + const valid = validate(manifest); + + if (!valid) { + if (validate.errors && validate.errors.length > 0) { + throw new Error('Azion validation: ' + validate.errors[0].message); + } + throw new Error('Azion validation failed.'); + } + }; +} + +export { createManifestValidator }; diff --git a/packages/config/src/versions/types.ts b/packages/config/src/versions/types.ts index fe3854cf..54b37f86 100644 --- a/packages/config/src/versions/types.ts +++ b/packages/config/src/versions/types.ts @@ -1,6 +1,7 @@ import type { AzionConfig } from '../types'; import type { AzionConfigV3 } from './v3/types'; -import type ProcessConfigContext from './v4/processStrategy/processConfigContext'; +import type { AzionConfigV6 } from './v6/types'; +import type ProcessConfigContext from './shared/processStrategy/processConfigContext'; /** * Config shape of each Azion API version the package knows how to process. @@ -11,6 +12,7 @@ import type ProcessConfigContext from './v4/processStrategy/processConfigContext export interface ConfigByVersion { 3: AzionConfigV3; 4: AzionConfig; + 6: AzionConfigV6; } export type ApiVersion = keyof ConfigByVersion; @@ -32,7 +34,7 @@ export const DEFAULT_API_VERSION: ApiVersion = 4; export interface ConfigVersionModule { version: ApiVersion; /** Builds the strategy context that converts config <-> manifest for this version. */ - factoryProcessContext: () => ProcessConfigContext; + factoryProcessContext: () => ProcessConfigContext; /** Validates a config against this version's schema. Throws on failure. */ validateConfig: (config: AnyAzionConfig | Record, schema?: Record) => void; /** Validates a manifest against this version's manifest schema. Throws on failure. */ diff --git a/packages/config/src/versions/v3/__fixtures__/README.md b/packages/config/src/versions/v3/__fixtures__/README.md index 1fa3cf1c..0b0840c3 100644 --- a/packages/config/src/versions/v3/__fixtures__/README.md +++ b/packages/config/src/versions/v3/__fixtures__/README.md @@ -22,4 +22,7 @@ generates: - `nuxt` does not declare `build.polyfills`, as its v4 config. - `emscripten` uses `bundler: 'webpack'`, as its v4 config (its `extend` is a webpack configuration). +- The manifest of this implementation also carries `version: 3` (written by `VersionProcessConfigStrategy`). The fixtures + do not have it, so `golden.test.ts` and the presets test add it to the expected manifest instead of changing the files. + Everything else is exactly what the original implementation produced. diff --git a/packages/config/src/versions/v3/golden.test.ts b/packages/config/src/versions/v3/golden.test.ts index 86b23676..a3a5199c 100644 --- a/packages/config/src/versions/v3/golden.test.ts +++ b/packages/config/src/versions/v3/golden.test.ts @@ -19,6 +19,7 @@ describe('v3 golden manifests (generated by the original 1.20.x implementation)' const config = { ...read(`${preset}.input.json`), version: 3 }; expect(() => validateConfig(config)).not.toThrow(); - expect(processConfig(config)).toEqual(read(`${preset}.manifest.json`)); + // the fixtures are frozen, so the `version` the v3 manifest carries is added here (see __fixtures__/README.md) + expect(processConfig(config)).toEqual({ version: 3, ...read(`${preset}.manifest.json`) }); }); }); diff --git a/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..12935be2 --- /dev/null +++ b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,40 @@ +import type { AzionConfig } from '../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v3)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 3 })).toBe(3); + }); + + it('should write the API version 3 when the config does not declare one', () => { + expect(strategy.transformToManifest({})).toBe(3); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({ version: 3 }, transformedPayload); + + expect(result).toBe(3); + expect(transformedPayload.version).toBe(3); + }); + + it('should leave the config without version when the manifest has none', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.version).toBeUndefined(); + }); + }); +}); diff --git a/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..ded2f994 --- /dev/null +++ b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,24 @@ +import { AzionConfig } from '../../types'; +import ProcessConfigStrategy from '../processConfigStrategy'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfig) { + return config?.version ?? 3; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfig) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v3/processStrategy/index.ts b/packages/config/src/versions/v3/processStrategy/index.ts index bb8ece4d..f27c15e5 100644 --- a/packages/config/src/versions/v3/processStrategy/index.ts +++ b/packages/config/src/versions/v3/processStrategy/index.ts @@ -9,9 +9,11 @@ import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigS import ProcessConfigContext from './processConfigContext'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; import FirewallProcessConfigStrategy from './implementations/secure/firewallProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('origin', new OriginProcessConfigStrategy()); processConfigContext.setStrategy('cache', new CacheProcessConfigStrategy()); diff --git a/packages/config/src/versions/v4/converterJsonConfig/index.ts b/packages/config/src/versions/v4/converterJsonConfig/index.ts index 07143299..7371ca9e 100644 --- a/packages/config/src/versions/v4/converterJsonConfig/index.ts +++ b/packages/config/src/versions/v4/converterJsonConfig/index.ts @@ -1,4 +1,5 @@ -import { AzionConfig } from '../../../types'; +import type { AzionConfig } from '../../../types'; +import { createJsonConfigConverter } from '../../shared/converterJsonConfig'; import { factoryProcessContext } from '../processStrategy'; import { schemaManifest } from '../schemas/schemaManifest'; import { validateConfig } from '../validateConfig'; @@ -30,20 +31,10 @@ import { validateConfig } from '../validateConfig'; * console.log(configObject); * */ -function convertJsonConfigToObject(config: string): AzionConfig { - let configObject: Record; - try { - configObject = JSON.parse(config); - } catch { - throw new Error('Invalid JSON configuration.'); - } - validateConfig(configObject, schemaManifest); - const payloadConfig: AzionConfig = {}; - const processConfigContext = factoryProcessContext(); - - processConfigContext.transformToConfig(configObject, payloadConfig); - - return payloadConfig; -} +const convertJsonConfigToObject = createJsonConfigConverter({ + validate: (manifest) => validateConfig(manifest, schemaManifest), + factoryProcessContext, + createConfig: () => ({}), +}); export { convertJsonConfigToObject }; diff --git a/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..4e6f6a55 --- /dev/null +++ b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,40 @@ +import type { AzionConfig } from '../../../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v4)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 4 })).toBe(4); + }); + + it('should write the API version 4 when the config does not declare one', () => { + expect(strategy.transformToManifest({})).toBe(4); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({ version: 4 }, transformedPayload); + + expect(result).toBe(4); + expect(transformedPayload.version).toBe(4); + }); + + it('should leave the config without version when the manifest has none', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.version).toBeUndefined(); + }); + }); +}); diff --git a/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..42598957 --- /dev/null +++ b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,26 @@ +import type { AzionConfig } from '../../../../types'; +import { DEFAULT_API_VERSION } from '../../../types'; +import ProcessConfigStrategy from '../processConfigStrategy'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + * A config that does not declare `version` targets the default version. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfig) { + return config?.version ?? DEFAULT_API_VERSION; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfig) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v4/processStrategy/index.ts b/packages/config/src/versions/v4/processStrategy/index.ts index 1dfeea2c..05b00432 100644 --- a/packages/config/src/versions/v4/processStrategy/index.ts +++ b/packages/config/src/versions/v4/processStrategy/index.ts @@ -9,12 +9,14 @@ import FirewallProcessConfigStrategy from './implementations/secure/firewallProc import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; import WorkloadDeploymentsProcessConfigStrategy from './implementations/workloadDeploymentsProcessConfigStrategy'; import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import ProcessConfigContext from './processConfigContext'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); processConfigContext.setStrategy('network_list', new NetworkListProcessConfigStrategy()); diff --git a/packages/config/src/versions/v4/processStrategy/processConfigContext.ts b/packages/config/src/versions/v4/processStrategy/processConfigContext.ts index 566c8356..b2cdb62a 100644 --- a/packages/config/src/versions/v4/processStrategy/processConfigContext.ts +++ b/packages/config/src/versions/v4/processStrategy/processConfigContext.ts @@ -1,47 +1,11 @@ -import { AzionConfig } from '../../../types'; -import ProcessConfigStrategy from './processConfigStrategy'; +import type { AzionConfig } from '../../../types'; +import SharedProcessConfigContext from '../../shared/processStrategy/processConfigContext'; /** * ProcessConfigContext * @class - * @description This class is responsible for generating the context of the process config. + * @description Context of the v4 process config. */ -class ProcessConfigContext { - strategies: { [key: string]: ProcessConfigStrategy }; - constructor() { - this.strategies = {}; - } - - setStrategy(type: string, strategy: ProcessConfigStrategy): void { - this.strategies[type] = strategy; - } - /** - * Transform to manifest is responsible for transforming the config to the manifest. - * @param config AzionConfig - * @param context manifest object - * @returns - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToManifest(config: AzionConfig, context: any) { - Object.keys(this.strategies).forEach((key) => { - context[key] = this.strategies[key].transformToManifest(config, context); - }); - return context; - } - - /** - * Transform to config is responsible for transforming the payload to the config. - * @param payload Manifest object - * @param transformedPayload AzionConfig object - * @returns - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToConfig(payload: any, transformedPayload: AzionConfig): AzionConfig { - Object.keys(this.strategies).forEach((key) => { - payload[key] = this.strategies[key].transformToConfig(payload, transformedPayload); - }); - return payload; - } -} +class ProcessConfigContext extends SharedProcessConfigContext {} export default ProcessConfigContext; diff --git a/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts b/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts index 8d06a946..1b52dbc9 100644 --- a/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts +++ b/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts @@ -1,21 +1,11 @@ +import type { AzionConfig } from '../../../types'; +import SharedProcessConfigStrategy from '../../shared/processStrategy/processConfigStrategy'; + /** * ProcessConfigStrategy * @class ProcessConfigStrategy - * @description This class is the base class for all process config strategies. + * @description Base class of the v4 process config strategies. */ - -import { AzionConfig } from '../../../types'; - -class ProcessConfigStrategy { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToManifest(config: any, context: any) { - return context; - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars - transformToConfig(payload: any, transformedPayload: AzionConfig): AzionConfig | any { - return payload; - } -} +class ProcessConfigStrategy extends SharedProcessConfigStrategy {} export default ProcessConfigStrategy; diff --git a/packages/config/src/versions/v4/schemas/build/index.ts b/packages/config/src/versions/v4/schemas/build/index.ts index 54905f9e..51b2fca5 100644 --- a/packages/config/src/versions/v4/schemas/build/index.ts +++ b/packages/config/src/versions/v4/schemas/build/index.ts @@ -1,92 +1,3 @@ -import { BUILD_BUNDLERS } from '../../../../constants'; - -const buildSchema = { - type: 'object', - properties: { - entry: { - oneOf: [ - { type: 'string' }, - { type: 'array', items: { type: 'string' } }, - { type: 'object', additionalProperties: { type: 'string' } }, - ], - errorMessage: "The 'build.entry' must be a string, array of strings, or object with string values", - }, - bundler: { - type: 'string', - enum: BUILD_BUNDLERS, - errorMessage: "The 'build.bundler' must be either 'webpack' or 'esbuild'", - }, - preset: { - anyOf: [ - { type: 'string' }, - { - type: 'object', - properties: { - metadata: { - type: 'object', - properties: { - name: { - type: 'string', - errorMessage: "The 'name' field in preset metadata must be a string", - }, - ext: { - type: 'string', - errorMessage: "The 'ext' field in preset metadata must be a string", - }, - }, - required: ['name'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in preset metadata', - required: "The 'name' field is required in preset metadata", - }, - }, - config: { - $ref: '#/definitions/mainConfig', - }, - handler: { instanceof: 'Function' }, - prebuild: { instanceof: 'Function' }, - postbuild: { instanceof: 'Function' }, - }, - required: ['metadata', 'config'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in preset', - required: "Preset must contain both 'metadata' and 'config' properties", - }, - }, - ], - errorMessage: 'Preset must be either a string or an object with preset properties', - }, - polyfills: { - type: 'boolean', - errorMessage: "The 'build.polyfills' must be a boolean", - }, - worker: { - type: 'boolean', - errorMessage: "The 'build.worker' must be a boolean", - }, - extend: { - instanceof: 'Function', - errorMessage: "The 'build.extend' must be a function", - }, - memoryFS: { - type: 'object', - properties: { - injectionDirs: { - type: 'array', - items: { type: 'string' }, - }, - removePathPrefix: { type: 'string' }, - }, - required: ['injectionDirs', 'removePathPrefix'], - additionalProperties: false, - }, - }, - additionalProperties: false, - errorMessage: { - additionalProperties: "No additional properties are allowed in the 'build' object", - }, -}; +import buildSchema from '../../../shared/schemas/build'; export default buildSchema; diff --git a/packages/config/src/versions/v4/validateConfig/index.ts b/packages/config/src/versions/v4/validateConfig/index.ts index 6ec57dbc..88a3bdf0 100644 --- a/packages/config/src/versions/v4/validateConfig/index.ts +++ b/packages/config/src/versions/v4/validateConfig/index.ts @@ -1,66 +1,14 @@ -import Ajv from 'ajv'; -import ajvErrors from 'ajv-errors'; -import addKeywords from 'ajv-keywords'; - -import { AzionConfig } from '../../../types'; +import type { AzionConfig } from '../../../types'; +import { createConfigValidator } from '../../shared/validateConfig'; import azionConfigSchema from '../schemas/schema'; /** * Validates the provided configuration against a JSON Schema. - * This function uses AJV (Another JSON Schema Validator) to validate the configuration. - * If the configuration is not valid, an exception is thrown with the error message of the first validation issue encountered. + * If the configuration is not valid, an exception is thrown with the first validation issues encountered. * @param {AzionConfig | Record} config - The configuration to be validated. * @param {object} schema - The JSON Schema to be used for validation. Default is the Azion CDN configuration schema. * @throws {Error} Throws an error if the configuration fails validation. */ -function validateConfig( - config: AzionConfig | Record, - schema: Record = azionConfigSchema, -) { - /* Converts legacy configuration properties to the new `behavior` format. */ - const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); - ajvErrors(ajv); - addKeywords(ajv, ['instanceof']); - const validate = ajv.compile(schema); - const valid = validate(config); - - const handleMessageError = (errors: unknown[]) => { - const messages = errors - ?.slice(0, 3) - ?.map((error: unknown, index: number) => { - const errorObject = error as { - message: string; - instancePath: string; - params: { missingProperty?: string | undefined }; - }; - - const errorDetails = [ - `📍 Error #${index + 1}:`, - ` Message: ${errorObject.message}`, - errorObject.instancePath ? ` Path: ${errorObject.instancePath}` : null, - errorObject.params?.missingProperty ? ` Missing Property: ${errorObject.params.missingProperty}` : null, - ] - .filter(Boolean) - .join('\n'); - - return errorDetails; - }) - .join('\n\n'); - - const totalErrors = errors?.length || 0; - const moreErrorsNote = totalErrors > 3 ? `\n\n... and ${totalErrors - 3} more error(s)` : ''; - - return `⛔️ Azion Configuration Validation Failed\n${'-'.repeat(50)}\n${messages}${moreErrorsNote}\n${'-'.repeat(50)}`; - }; - - if (!valid) { - if (validate.errors && validate.errors.length > 0) { - const messages = handleMessageError(validate.errors); - throw new Error(messages); - } else { - throw new Error('Azion validation failed.'); - } - } -} +const validateConfig = createConfigValidator(azionConfigSchema); export { validateConfig }; diff --git a/packages/config/src/versions/v4/validateManifest/index.ts b/packages/config/src/versions/v4/validateManifest/index.ts index 95a849de..de6e4bee 100644 --- a/packages/config/src/versions/v4/validateManifest/index.ts +++ b/packages/config/src/versions/v4/validateManifest/index.ts @@ -1,32 +1,13 @@ -import Ajv from 'ajv'; -import ajvErrors from 'ajv-errors'; -import addKeywords from 'ajv-keywords'; - +import { createManifestValidator } from '../../shared/validateManifest'; import { schemaManifest as azionManifestSchema } from '../schemas/schemaManifest'; /** * Validates the provided manifest against the Azion Manifest Schema. - * This function uses AJV (Another JSON Schema Validator) to validate the manifest. * If the manifest is not valid, an exception is thrown with the error message of the first validation issue encountered. * @param {Record} manifest - The manifest to be validated. * @param {object} schema - The JSON Schema to be used for validation. Default is the Azion Manifest schema. * @throws {Error} Throws an error if the manifest fails validation. */ -function validateManifest(manifest: Record, schema: Record = azionManifestSchema) { - const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); - ajvErrors(ajv); - addKeywords(ajv, ['instanceof']); - const validate = ajv.compile(schema); - const valid = validate(manifest); - - if (!valid) { - if (validate.errors && validate.errors.length > 0) { - const firstError = validate.errors[0]; - throw new Error('Azion validation: ' + firstError.message); - } else { - throw new Error('Azion validation failed.'); - } - } -} +const validateManifest = createManifestValidator(azionManifestSchema); export { validateManifest }; diff --git a/packages/config/src/versions/v6/azion.config.example.test.ts b/packages/config/src/versions/v6/azion.config.example.test.ts new file mode 100644 index 00000000..e0ad1c5d --- /dev/null +++ b/packages/config/src/versions/v6/azion.config.example.test.ts @@ -0,0 +1,54 @@ +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { processConfig, validateConfig } from '../../configProcessor'; +import config from './azion.config.example'; + +describe('complete azion.config example of the API v6', () => { + it('is a valid v6 config', () => { + expect(() => validateConfig(config)).not.toThrow(); + }); + + it('is processed into a v6 manifest with every resource', () => { + const manifest = processConfig(config); + + expect(manifest.version).toBe(6); + expect(Object.keys(manifest)).toEqual( + expect.arrayContaining([ + 'build', + 'functions', + 'storage', + 'connectors', + 'applications', + 'custom_pages', + 'network_list', + 'waf', + 'firewall', + 'environments', + 'workloads', + 'deployments', + 'purge', + ]), + ); + expect(manifest.deployments).toHaveLength(1); + expect(manifest).not.toHaveProperty('workload_deployments'); + expect(manifest.workloads[0].bindings).toEqual([ + { + environment_name: 'production', + deployment_name: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ]); + expect(manifest.applications[0].device_groups).toEqual([{ name: 'mobile', user_agent: 'Android|iPhone' }]); + }); + + it('is the example of the v6 documentation', () => { + const source = readFileSync(join(__dirname, 'azion.config.example.ts'), 'utf8'); + const body = source.slice( + source.indexOf('const config: AzionConfigV6 = {'), + source.indexOf('export default config;'), + ); + const documentation = readFileSync(join(__dirname, '..', '..', '..', 'docs', 'config-v6.md'), 'utf8'); + + expect(documentation).toContain(body.trim()); + }); +}); diff --git a/packages/config/src/versions/v6/azion.config.example.ts b/packages/config/src/versions/v6/azion.config.example.ts new file mode 100644 index 00000000..e989225b --- /dev/null +++ b/packages/config/src/versions/v6/azion.config.example.ts @@ -0,0 +1,221 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +/** + * Complete example of an azion.config for the Azion API v6. + * It uses every resource the v6 config has. Names reference each other (the Azion CLI resolves them to IDs), and an + * ID can be used instead of a name where the API takes one. + */ +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + entry: './src/index.js', + polyfills: true, + }, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + bindings: { + storage: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + // connectors and network lists the function uses at runtime, which a release includes with it + dependencies: [ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-ip-allowlist' }, + ], + }, + ], + storage: [ + { + name: 'my-bucket-assets', + prefix: 'v1', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: 'my-storage-connector', + type: 'storage', + attributes: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + { + name: 'my-origin', + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'force_https', + host: 'origin.example.com', + followingRedirect: false, + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 3, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + }, + }, + }, + ], + applications: [ + { + name: 'my-app', + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + cache: [ + { + name: 'my-cache', + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 7200 }, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'denylist', list: ['order', 'user'] }, + }, + ], + rules: { + request: [ + { + name: 'Run the function', + description: 'Run the function for the API paths', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], + }, + { + name: 'Serve from the storage', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [ + { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, + { type: 'set_connector', attributes: { value: 'my-storage-connector' } }, + ], + }, + ], + response: [ + { + name: 'Add a header', + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], + }, + ], + }, + functionsInstances: [ + { + name: 'my-function-instance', + ref: 'my-function', + args: { greeting: 'hello' }, + }, + ], + deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }], + }, + ], + customPages: [ + { + name: 'my-custom-pages', + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-storage-connector', ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ], + networkList: [ + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'] }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'] }, + ], + waf: [ + { + name: 'my-waf', + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [ + { threat: 'sql_injection', sensitivity: 'high' }, + { threat: 'cross_site_scripting', sensitivity: 'high' }, + ], + }, + }, + }, + ], + firewall: [ + { + name: 'my-firewall', + debugRules: false, + functions: false, + networkProtection: true, + waf: true, + rules: [ + { + name: 'Allow the trusted networks', + criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], + behaviors: [{ type: 'bypass' }], + }, + { + name: 'Protect with the WAF', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], + }, + ], + }, + ], + environments: [ + { + name: 'production', + description: 'Production environment', + deploymentPolicy: 'single_version', + logVerbosity: 'normal', + robotsPolicy: 'respect_origin', + }, + ], + // the application, firewall and custom page a deployment serves are set by the Azion CLI when it creates the release + deployments: [ + { + name: 'my-deployment', + description: 'Main deployment', + bindingPolicy: 'FLEXIBLE', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + workloads: [ + { + name: 'my-workload', + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { minimumVersion: 'tls_1_3' }, + protocols: { + http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, + }, + bindings: [ + { + environment: 'production', + deployment: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ], + }, + ], + purge: [{ type: 'url', items: ['https://example.com/index.html'], layer: 'cache' }], +}; + +export default config; diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts new file mode 100644 index 00000000..bfcea8a0 --- /dev/null +++ b/packages/config/src/versions/v6/constants.ts @@ -0,0 +1,288 @@ +// Constants of the Azion API v6 config. Variables are the ones of `ApplicationCriterionField` of the v6 API. + +/** Variables available in the request and in the response phase. */ +export const COMMON_VARIABLES = [ + 'args', + 'device_group', + 'geoip_city_continent_code', + 'geoip_city_country_code', + 'geoip_city_country_name', + 'geoip_city', + 'geoip_continent_code', + 'geoip_country_code', + 'geoip_country_name', + 'geoip_region_name', + 'geoip_region', + 'host', + 'domain', + 'remote_addr', + 'remote_user', + 'request_method', + 'request_uri', + 'request', + 'scheme', + 'uri', + 'server_addr', + 'server_port', + 'ssl_client_cert', + 'ssl_client_escaped_cert', + 'ssl_client_fingerprint', + 'ssl_client_i_dn', + 'ssl_client_s_dn_parsed', + 'ssl_client_s_dn', + 'ssl_client_serial', + 'ssl_client_v_end', + 'ssl_client_v_remain', + 'ssl_client_v_start', + 'ssl_client_verify', + 'tcpinfo_rtt', + 'remote_port', + 'request_body', +] as const; + +/** Variables available only in the response phase. */ +export const RESPONSE_ONLY_VARIABLES = ['status', 'upstream_addr', 'upstream_status'] as const; + +export const SPECIAL_VARIABLES = ['cookie_time_offset', 'encode_base64'] as const; + +export const ALL_REQUEST_VARIABLES = [...COMMON_VARIABLES] as const; + +export const ALL_RESPONSE_VARIABLES = [...COMMON_VARIABLES, ...RESPONSE_ONLY_VARIABLES] as const; + +export const RULE_OPERATORS_WITH_VALUE = [ + 'is_equal', + 'is_not_equal', + 'starts_with', + 'does_not_start_with', + 'matches', + 'does_not_match', +] as const; + +export const RULE_OPERATORS_WITHOUT_VALUE = ['exists', 'does_not_exist'] as const; + +export const RULE_CONDITIONALS = ['if', 'and', 'or'] as const; + +export const NO_ARGS_BEHAVIORS = [ + 'deny', + 'no_content', + 'deliver', + 'finish_request_phase', + 'forward_cookies', + 'optimize_images', + 'bypass_cache', + 'enable_gzip', + 'redirect_http_to_https', +] as const; + +export const STRING_BEHAVIORS = ['redirect_to_301', 'redirect_to_302', 'rewrite_request'] as const; + +export const ID_BEHAVIORS = ['run_function', 'set_cache_policy', 'set_connector', 'set_origin'] as const; + +export const HEADER_BEHAVIORS = [ + 'add_request_header', + 'add_response_header', + 'filter_request_header', + 'filter_response_header', +] as const; + +export const COOKIE_BEHAVIORS = [ + 'add_request_cookie', + 'filter_request_cookie', + 'set_cookie', + 'filter_response_cookie', +] as const; + +export const WORKLOAD_INFRASTRUCTURE = [1, 2] as const; + +export const WORKLOAD_TLS_CIPHERS = [1, 2, 3, 4, 5, 6, 7, 8] as const; + +export const WORKLOAD_TLS_VERSIONS = ['', 'tls_1_0', 'tls_1_1', 'tls_1_2', 'tls_1_3'] as const; + +export const WORKLOAD_MTLS_VERIFICATION = ['enforce', 'permissive'] as const; + +export const WORKLOAD_HTTP_VERSIONS = ['http1', 'http2', 'http3'] as const; + +export const ENVIRONMENT_LOG_VERBOSITY = ['normal', 'verbose'] as const; + +export const ENVIRONMENT_ROBOTS_POLICIES = ['index', 'noindex', 'respect_origin'] as const; + +export const ENVIRONMENT_BRANCH_TRACKING_MODES = ['branch_is', 'branch_starts_with', 'branch_ends_with'] as const; + +export const ENVIRONMENT_DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls'] as const; + +export const DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls', 'latest'] as const; + +export const DEPLOYMENT_BINDING_POLICIES = ['STRICT', 'FLEXIBLE'] as const; + +export const FUNCTION_DEPENDENCY_TYPES = ['connector', 'network_list'] as const; + +/** + * Module of an application that each request phase behavior needs enabled (`RequestPhaseBehaviorRequest`). + */ +export const APPLICATION_REQUEST_BEHAVIOR_MODULES = { + forward_cookies: 'application_accelerator', + optimize_images: 'image_processor', + bypass_cache: 'cache', + filter_request_cookie: 'application_accelerator', + run_function: 'functions', + rewrite_request: 'application_accelerator', + capture_match_groups: 'application_accelerator', + add_request_cookie: 'application_accelerator', +} as const; + +/** + * Module of an application that each response phase behavior needs enabled (`ResponsePhaseBehaviorRequest`). + */ +export const APPLICATION_RESPONSE_BEHAVIOR_MODULES = { + run_function: 'functions', + set_cookie: 'application_accelerator', + capture_match_groups: 'application_accelerator', +} as const; + +/** + * Every criterion variable of an application rule except `${uri}` needs the application accelerator module. + */ +export const APPLICATION_ACCELERATOR_FREE_VARIABLES = ['uri'] as const; + +export const FIREWALL_MODULES = ['waf', 'network_protection', 'functions'] as const; + +/** + * Modules of a firewall of which at least one must be enabled for each behavior (`FirewallBehaviorRequest`). + */ +export const FIREWALL_BEHAVIOR_MODULES: Record = { + deny: FIREWALL_MODULES, + drop: FIREWALL_MODULES, + bypass: FIREWALL_MODULES, + set_custom_response: FIREWALL_MODULES, + set_rate_limit: FIREWALL_MODULES, + set_waf: FIREWALL_MODULES, + run_function: ['functions'], +}; + +/** + * Modules of a firewall of which at least one must be enabled for each criterion variable + * (`FirewallCriterionFieldRequest`). A variable that is not listed does not need any module. + */ +export const FIREWALL_VARIABLE_MODULES: Record = { + header_accept: ['waf'], + header_accept_encoding: ['waf'], + header_accept_language: ['waf'], + header_cookie: ['waf'], + header_origin: ['waf'], + header_referer: ['waf'], + header_user_agent: ['waf'], + host: FIREWALL_MODULES, + network: ['network_protection'], + request_args: ['waf'], + request_method: ['waf'], + request_uri: FIREWALL_MODULES, + scheme: FIREWALL_MODULES, +}; + +export const WORKLOADS_ACCESS_TYPES = ['read_only', 'read_write', 'restricted'] as const; + +export const CONNECTOR_TYPES = ['http', 'storage', 'live_ingest'] as const; + +export const CONNECTOR_DNS_RESOLUTION = ['both', 'force_ipv4', 'force_ipv6'] as const; + +export const CONNECTOR_TRANSPORT_POLICY = ['preserve', 'force_https', 'force_http'] as const; + +export const CONNECTOR_HTTP_VERSION_POLICY = ['http1_1'] as const; + +export const CONNECTOR_LOAD_BALANCE_METHOD = ['round_robin', 'least_conn', 'ip_hash'] as const; + +export const CONNECTOR_SERVER_ROLES = ['primary', 'backup'] as const; + +export const CONNECTOR_HMAC_TYPE = ['aws4_hmac_sha256'] as const; + +export const CONNECTOR_LIVE_INGEST_REGIONS = ['us-east-1', 'us-east-2', 'br-east-1', 'br-east-2', 'br-east-3'] as const; + +export const FIREWALL_VARIABLES = [ + 'header_accept', + 'header_accept_encoding', + 'header_accept_language', + 'header_cookie', + 'header_origin', + 'header_referer', + 'header_user_agent', + 'host', + 'network', + 'request_args', + 'request_method', + 'request_uri', + 'scheme', + 'client_certificate_validation', + 'ssl_verification_status', +] as const; + +export const FIREWALL_RULE_OPERATORS = [ + 'is_equal', + 'is_not_equal', + 'starts_with', + 'does_not_start_with', + 'matches', + 'does_not_match', + 'exists', + 'does_not_exist', + 'is_in_list', + 'is_not_in_list', +] as const; + +export const FIREWALL_RULE_CONDITIONAL = ['if', 'and', 'or'] as const; + +export const FIREWALL_NO_ARGS_BEHAVIORS = ['deny', 'drop', 'bypass'] as const; + +export const FIREWALL_RATE_LIMIT_TYPES = ['second', 'minute'] as const; + +export const FIREWALL_RATE_LIMIT_BY = ['client_ip', 'global'] as const; + +export const FIREWALL_WAF_MODES = ['logging', 'blocking'] as const; + +export const WAF_ENGINE_VERSIONS = ['2021-Q3'] as const; + +export const WAF_ENGINE_TYPES = ['score'] as const; + +export const WAF_RULESETS = [1] as const; + +export const WAF_THREAT_TYPES = [ + 'cross_site_scripting', + 'directory_traversal', + 'evading_tricks', + 'file_upload', + 'identified_attack', + 'remote_file_inclusion', + 'sql_injection', + 'unwanted_access', +] as const; + +export const WAF_SENSITIVITY = ['highest', 'high', 'medium', 'low', 'lowest'] as const; + +export const NETWORK_LIST_TYPES = ['ip_cidr', 'asn', 'countries'] as const; + +export const CUSTOM_PAGE_ERROR_CODES = [ + 'default', + '400', + '401', + '403', + '404', + '405', + '406', + '408', + '409', + '410', + '411', + '414', + '415', + '416', + '426', + '429', + '431', + '500', + '501', + '502', + '503', + '504', + '505', +] as const; + +export const CUSTOM_PAGE_TYPES = ['page_connector'] as const; diff --git a/packages/config/src/versions/v6/converterJsonConfig/index.ts b/packages/config/src/versions/v6/converterJsonConfig/index.ts new file mode 100644 index 00000000..c7a68f11 --- /dev/null +++ b/packages/config/src/versions/v6/converterJsonConfig/index.ts @@ -0,0 +1,18 @@ +import { createJsonConfigConverter } from '../../shared/converterJsonConfig'; +import { factoryProcessContext } from '../processStrategy'; +import type { AzionConfigV6 } from '../types'; +import { validateManifest } from '../validateManifest'; + +/** + * Converts a JSON manifest string to an AzionConfigV6 object. + * @param {string} config - The JSON string to be converted. + * @returns {AzionConfigV6} The AzionConfigV6 object. + * @throws {Error} Throws an error if the provided JSON string is invalid. + */ +const convertJsonConfigToObject = createJsonConfigConverter({ + validate: (manifest) => validateManifest(manifest), + factoryProcessContext, + createConfig: () => ({ version: 6 }), +}); + +export { convertJsonConfigToObject }; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts new file mode 100644 index 00000000..68d458ef --- /dev/null +++ b/packages/config/src/versions/v6/index.ts @@ -0,0 +1,30 @@ +import type { ConfigVersionAccessors, ConfigVersionModule } from '../types'; +import { convertJsonConfigToObject } from './converterJsonConfig'; +import { factoryProcessContext } from './processStrategy'; +import { validateConfig } from './validateConfig'; +import type { AzionConfigV6 } from './types'; +import { validateManifest } from './validateManifest'; + +const accessors: ConfigVersionAccessors = { + getApplicationName: (config) => (config as AzionConfigV6).applications?.[0]?.name, + getStorage: (config) => { + // TODO: multiple storage support + const storage = (config as AzionConfigV6).storage?.[0]; + return storage ? { bucket: storage.name, prefix: storage.prefix ?? '' } : undefined; + }, + // the keys of a preset that only serve an application, which a firewall-only project does not have. The environments + // and the deployments only exist to bind a workload to an application, so they go along with the workloads + firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments', 'deployments'], +}; + +// v6 has its own AzionConfig type, which is not assignable to the default (v4) one used by the shared contract +const v6 = { + version: 6, + factoryProcessContext, + validateConfig, + validateManifest, + convertJsonConfigToObject, + accessors, +} as unknown as ConfigVersionModule; + +export default v6; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts new file mode 100644 index 00000000..b2904f7e --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts @@ -0,0 +1,305 @@ +import type { AzionConfigV6 } from '../../../types'; +import ApplicationProcessConfigStrategy from './applicationProcessConfigStrategy'; + +describe('ApplicationProcessConfigStrategy (v6)', () => { + let strategy: ApplicationProcessConfigStrategy; + + beforeEach(() => { + strategy = new ApplicationProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no applications', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults to a minimal application', () => { + const result = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(result).toEqual([ + { + name: 'my-app', + debug: false, + modules: { + cache: { enabled: true }, + functions: { enabled: false }, + application_accelerator: { enabled: true }, + image_processor: { enabled: false }, + }, + }, + ]); + }); + + it('should map every field of the application to the manifest', () => { + const result = strategy.transformToManifest({ + version: 6, + applications: [ + { + name: 'my-app', + debug: true, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: true, + }, + ], + }); + + expect(result).toEqual([ + { + name: 'my-app', + debug: true, + modules: { + cache: { enabled: true }, + functions: { enabled: true }, + application_accelerator: { enabled: false }, + image_processor: { enabled: true }, + }, + }, + ]); + }); + }); + + describe('rules and function instances', () => { + const config: AzionConfigV6 = { + version: 6, + functions: [{ name: 'fn', path: './fn.js' }], + applications: [ + { + name: 'my-app', + rules: { + request: [ + { + name: 'Execute Function', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + ], + }, + functionsInstances: [{ name: 'instance', ref: 'fn' }], + }, + ], + }; + + it('should write rules and function instances to the manifest', () => { + const [application] = strategy.transformToManifest(config); + + expect(application.rules).toHaveLength(1); + expect(application.rules[0]).toEqual(expect.objectContaining({ phase: 'request' })); + expect(application.functions_instances).toEqual([{ name: 'instance', function: 'fn', args: {} }]); + }); + + it('should write the cache settings to the manifest as cache_settings and read them back', () => { + const withCache: AzionConfigV6 = { + version: 6, + applications: [{ name: 'my-app', cache: [{ name: 'my-cache', browser: { maxAgeSeconds: 7200 } }] }], + }; + const [application] = strategy.transformToManifest(withCache); + + expect(application.cache_settings).toHaveLength(1); + expect(application.cache_settings[0]).toEqual( + expect.objectContaining({ name: 'my-cache', browser_cache: { behavior: 'override', max_age: 7200 } }), + ); + + const transformedPayload: AzionConfigV6 = { version: 6 }; + strategy.transformToConfig({ applications: [application] }, transformedPayload); + + expect(transformedPayload.applications?.[0].cache?.[0]).toEqual( + expect.objectContaining({ name: 'my-cache', browser: { maxAgeSeconds: 7200 } }), + ); + }); + + it('should not write cache_settings when the application has no cache', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('cache_settings'); + }); + + it('should enable the functions module when the application has function instances', () => { + const [application] = strategy.transformToManifest(config); + expect(application.modules.functions.enabled).toBe(true); + }); + + it('should round trip the device groups through the manifest', () => { + const deviceGroups = [{ name: 'mobile', userAgent: 'Android|iPhone' }]; + const [application] = strategy.transformToManifest({ + version: 6, + applications: [{ name: 'my-app', deviceGroups }], + }); + + expect(application.device_groups).toEqual([{ name: 'mobile', user_agent: 'Android|iPhone' }]); + + const transformedPayload: AzionConfigV6 = { version: 6 }; + strategy.transformToConfig({ applications: [application] }, transformedPayload); + + expect(transformedPayload.applications?.[0].deviceGroups).toEqual(deviceGroups); + }); + + it('should not write device_groups when the application has none', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('device_groups'); + }); + + it('should not write rules and function instances when the application has none', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('rules'); + expect(application).not.toHaveProperty('functions_instances'); + }); + + it('should round trip rules and function instances through the manifest', () => { + const manifest = { applications: strategy.transformToManifest(config) }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig(manifest, transformedPayload); + const [application] = transformedPayload.applications!; + + expect(application.rules?.request?.[0].name).toBe('Execute Function'); + expect(application.functionsInstances).toEqual([{ name: 'instance', ref: 'fn', args: {} }]); + expect(application.functionsEnabled).toBe(true); + }); + }); + + describe('transformToConfig', () => { + it('should set an empty array when the manifest has no applications', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toEqual([]); + expect(transformedPayload.applications).toEqual([]); + }); + + it('should map the manifest application back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + const payload = { + applications: [ + { + name: 'my-app', + debug: true, + modules: { + cache: { enabled: false }, + functions: { enabled: true }, + application_accelerator: { enabled: false }, + image_processor: { enabled: true }, + }, + }, + ], + }; + + strategy.transformToConfig(payload, transformedPayload); + + expect(transformedPayload.applications).toEqual([ + { + name: 'my-app', + debug: true, + edgeCacheEnabled: false, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: true, + }, + ]); + }); + + it('should round trip a config through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + applications: [ + { + name: 'my-app', + debug: false, + edgeCacheEnabled: true, + functionsEnabled: false, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + }, + ], + }; + const manifest = { applications: strategy.transformToManifest(config) }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig(manifest, transformedPayload); + + expect(transformedPayload).toEqual(config); + }); + }); + + describe('modules the rules need', () => { + const request = (behaviors: object[], variable = '${uri}') => ({ + request: [ + { + name: 'rule', + criteria: [[{ variable, conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors, + }, + ], + }); + const manifest = (application: object) => + strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app', ...application }] } as AzionConfigV6); + + it('should write the cache module as enabled', () => { + expect(manifest({})[0].modules.cache).toEqual({ enabled: true }); + }); + + it('should accept the behaviors of the modules that are enabled', () => { + expect(() => + manifest({ + imageProcessorEnabled: true, + functionsEnabled: true, + rules: request([{ type: 'optimize_images' }, { type: 'run_function', attributes: { value: 10 } }]), + }), + ).not.toThrow(); + }); + + it('should throw when a behavior needs a module that is disabled', () => { + expect(() => manifest({ rules: request([{ type: 'optimize_images' }]) })).toThrow( + 'Application "my-app" rule "rule" uses the behavior "optimize_images", which needs the image_processor module: enable it with imageProcessorEnabled.', + ); + expect(() => + manifest({ + applicationAcceleratorEnabled: false, + rules: request([{ type: 'rewrite_request', attributes: { value: '/x' } }]), + }), + ).toThrow('which needs the application_accelerator module'); + expect(() => manifest({ rules: request([{ type: 'run_function', attributes: { value: 10 } }]) })).toThrow( + 'which needs the functions module', + ); + }); + + it('should not need the functions module flag when the application has function instances', () => { + expect(() => + manifest({ + functionsInstances: [{ name: 'instance', ref: 10 }], + rules: request([{ type: 'run_function', attributes: { value: 10 } }]), + }), + ).not.toThrow(); + }); + + it('should throw for a variable other than uri when the application accelerator is disabled', () => { + expect(() => + manifest({ applicationAcceleratorEnabled: false, rules: request([{ type: 'deliver' }], '${host}') }), + ).toThrow('uses the variable "host", which needs the application_accelerator module'); + expect(() => + manifest({ applicationAcceleratorEnabled: false, rules: request([{ type: 'deliver' }]) }), + ).not.toThrow(); + }); + + it('should check the response rules too', () => { + expect(() => + manifest({ + applicationAcceleratorEnabled: false, + rules: { + response: [ + { + name: 'r', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'set_cookie', attributes: { value: 'a=b' } }], + }, + ], + }, + }), + ).toThrow('uses the behavior "set_cookie", which needs the application_accelerator module'); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts new file mode 100644 index 00000000..ffe1b174 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -0,0 +1,141 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import { + APPLICATION_ACCELERATOR_FREE_VARIABLES, + APPLICATION_REQUEST_BEHAVIOR_MODULES, + APPLICATION_RESPONSE_BEHAVIOR_MODULES, +} from '../../../constants'; +import type { AzionApplicationV6, AzionConfigV6, AzionRuleV6 } from '../../../types'; +import CacheProcessConfigStrategy from './cacheProcessConfigStrategy'; +import DeviceGroupsProcessConfigStrategy from './deviceGroupsProcessConfigStrategy'; +import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; +import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; + +/** + * ApplicationProcessConfigStrategy + * @class ApplicationProcessConfigStrategy + * @description Converts the v6 applications between the config and the manifest. + * The cache module cannot be disabled, and the behaviors and criterion variables of the rules need the modules the API + * documents (`RequestPhaseBehaviorRequest`, `ResponsePhaseBehaviorRequest` and the criterion fields). + */ +class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { + private cacheStrategy = new CacheProcessConfigStrategy(); + private rulesStrategy = new RulesProcessConfigStrategy(); + private functionInstancesStrategy = new FunctionInstancesProcessConfigStrategy(); + private deviceGroupsStrategy = new DeviceGroupsProcessConfigStrategy(); + + /** + * Validate that the modules the rules need are enabled + */ + private validateModules(app: AzionApplicationV6, modules: Record) { + const flags: Record = { + functions: 'functionsEnabled (or declare functionsInstances)', + application_accelerator: 'applicationAcceleratorEnabled', + image_processor: 'imageProcessorEnabled', + cache: 'edgeCacheEnabled', + }; + const check = (rule: AzionRuleV6, behaviorModules: Record) => { + rule.behaviors.forEach((behavior) => { + const module = behaviorModules[behavior.type]; + if (module && !modules[module]?.enabled) { + throw new Error( + `Application "${app.name}" rule "${rule.name}" uses the behavior "${behavior.type}", which needs the ${module} module: enable it with ${flags[module]}.`, + ); + } + }); + rule.criteria.flat().forEach((criterion) => { + const variable = String(criterion.variable).replace(/^\$\{|\}$/g, ''); + if ( + !(APPLICATION_ACCELERATOR_FREE_VARIABLES as readonly string[]).includes(variable) && + !modules.application_accelerator.enabled + ) { + throw new Error( + `Application "${app.name}" rule "${rule.name}" uses the variable "${variable}", which needs the application_accelerator module: enable it with ${flags.application_accelerator}.`, + ); + } + }); + }; + + app.rules?.request?.forEach((rule) => check(rule, APPLICATION_REQUEST_BEHAVIOR_MODULES)); + app.rules?.response?.forEach((rule) => check(rule, APPLICATION_RESPONSE_BEHAVIOR_MODULES)); + } + + transformToManifest(config: AzionConfigV6) { + if (!config.applications || !Array.isArray(config.applications)) { + return []; + } + + return config.applications.map((app: AzionApplicationV6) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const application: Record = { + name: app.name, + debug: app.debug ?? false, + modules: { + cache: { + enabled: true, + }, + functions: { + enabled: + app.functionsEnabled || (app.functionsInstances && app.functionsInstances.length > 0) ? true : false, + }, + application_accelerator: { + enabled: app.applicationAcceleratorEnabled ?? true, + }, + image_processor: { + enabled: app.imageProcessorEnabled ?? false, + }, + }, + }; + + this.validateModules(app, application.modules); + + if (app.cache) { + application.cache_settings = this.cacheStrategy.transformToManifest(app.cache); + } + + if (app.rules) { + application.rules = this.rulesStrategy.transformToManifest(app.rules, config.functions, config.connectors); + } + + if (app.functionsInstances) { + application.functions_instances = this.functionInstancesStrategy.transformToManifest( + app.functionsInstances, + config, + ); + } + + if (app.deviceGroups) { + application.device_groups = this.deviceGroupsStrategy.transformToManifest(app.deviceGroups); + } + + return application; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + if (!payload.applications || !Array.isArray(payload.applications)) { + transformedPayload.applications = []; + return transformedPayload.applications; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.applications = payload.applications.map((app: any) => ({ + name: app.name, + debug: app.debug, + edgeCacheEnabled: app.modules?.cache?.enabled, + functionsEnabled: app.modules?.functions?.enabled, + applicationAcceleratorEnabled: app.modules?.application_accelerator?.enabled, + imageProcessorEnabled: app.modules?.image_processor?.enabled, + cache: app.cache_settings ? this.cacheStrategy.transformToConfig(app.cache_settings) : undefined, + rules: app.rules ? this.rulesStrategy.transformToConfig(app.rules) : undefined, + functionsInstances: app.functions_instances + ? this.functionInstancesStrategy.transformToConfig(app.functions_instances) + : undefined, + deviceGroups: app.device_groups ? this.deviceGroupsStrategy.transformToConfig(app.device_groups) : undefined, + })); + + return transformedPayload.applications; + } +} + +export default ApplicationProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.test.ts new file mode 100644 index 00000000..43e5402d --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.test.ts @@ -0,0 +1,138 @@ +import type { AzionCache } from '../../../../../types'; +import CacheProcessConfigStrategy from './cacheProcessConfigStrategy'; + +describe('CacheProcessConfigStrategy (v6)', () => { + let strategy: CacheProcessConfigStrategy; + + beforeEach(() => { + strategy = new CacheProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no cache settings', () => { + expect(strategy.transformToManifest([])).toEqual([]); + expect(strategy.transformToManifest(undefined as unknown as AzionCache[])).toEqual([]); + }); + + it('should apply the defaults to a minimal cache setting', () => { + expect(strategy.transformToManifest([{ name: 'my-cache' }])).toEqual([ + { + name: 'my-cache', + browser_cache: { behavior: 'honor', max_age: 0 }, + modules: { + cache: { + behavior: 'honor', + max_age: 60, + stale_cache: { enabled: false }, + large_file_cache: { enabled: false, offset: 1024 }, + tiered_cache: { enabled: false }, + }, + application_accelerator: { + cache_vary_by_method: [], + cache_vary_by_querystring: { behavior: 'ignore', fields: [], sort_enabled: false }, + cache_vary_by_cookies: { behavior: 'ignore', cookie_names: [] }, + cache_vary_by_devices: { behavior: 'ignore', device_group: [] }, + }, + }, + }, + ]); + }); + + it('should map every field of the cache setting to the manifest', () => { + const [cache] = strategy.transformToManifest([ + { + name: 'my-cache', + stale: true, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'br-east-1' }, + methods: { post: true, options: true }, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 86400 }, + cacheByCookie: { option: 'allowlist', list: ['session'] }, + cacheByQueryString: { option: 'denylist', list: ['utm'] }, + }, + ]); + + expect(cache).toEqual({ + name: 'my-cache', + browser_cache: { behavior: 'override', max_age: 7200 }, + modules: { + cache: { + behavior: 'override', + max_age: 86400, + stale_cache: { enabled: true }, + large_file_cache: { enabled: false, offset: 1024 }, + tiered_cache: { enabled: true, topology: 'br-east-1' }, + }, + application_accelerator: { + cache_vary_by_method: ['post', 'options'], + cache_vary_by_querystring: { behavior: 'denylist', fields: ['utm'], sort_enabled: true }, + cache_vary_by_cookies: { behavior: 'allowlist', cookie_names: ['session'] }, + cache_vary_by_devices: { behavior: 'ignore', device_group: [] }, + }, + }, + }); + }); + + it('should evaluate a mathematical expression as the max age', () => { + const [cache] = strategy.transformToManifest([ + { name: 'my-cache', browser: { maxAgeSeconds: '60 * 60' }, edge: { maxAgeSeconds: '60 * 60 * 24 * 7' } }, + ]); + + expect(cache.browser_cache.max_age).toBe(3600); + expect(cache.modules.cache.max_age).toBe(604800); + }); + + it('should accept the limits of the max age and throw out of them (v6 API: 0 to 31536000)', () => { + const withMaxAge = (browser: number | string, edge: number | string) => + strategy.transformToManifest([ + { name: 'my-cache', browser: { maxAgeSeconds: browser }, edge: { maxAgeSeconds: edge } }, + ]); + + expect(() => withMaxAge(0, 31536000)).not.toThrow(); + expect(() => withMaxAge('60 * 60 * 24 * 365', 10)).not.toThrow(); + expect(() => withMaxAge('60 * 60 * 24 * 366', 10)).toThrow( + 'Cache "my-cache" has browser.maxAgeSeconds "60 * 60 * 24 * 366" which is not a number of seconds between 0 and 31536000.', + ); + expect(() => withMaxAge(10, 31536001)).toThrow('edge.maxAgeSeconds'); + expect(() => withMaxAge(-1, 10)).toThrow('browser.maxAgeSeconds'); + expect(() => withMaxAge('1 / 0', 10)).toThrow('which is not a number of seconds'); + }); + + it('should throw when the max age is not a mathematical expression', () => { + expect(() => + strategy.transformToManifest([{ name: 'my-cache', browser: { maxAgeSeconds: 'process.exit()' } }]), + ).toThrow('Expression is not purely mathematical: process.exit()'); + }); + + it('should leave the topology out when the tiered cache is not enabled', () => { + const [cache] = strategy.transformToManifest([ + { name: 'my-cache', tieredCache: { enabled: false, topology: 'us-east-1' } }, + ]); + + expect(cache.modules.cache.tiered_cache).toEqual({ enabled: false }); + }); + }); + + describe('transformToConfig', () => { + it('should return an empty array when there is nothing to convert', () => { + expect(strategy.transformToConfig([])).toEqual([]); + }); + + it('should round trip a cache setting through the manifest', () => { + const cache: AzionCache = { + name: 'my-cache', + stale: true, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 86400 }, + methods: { post: true, options: false }, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'allowlist', list: ['q'] }, + cacheByCookie: { option: 'denylist', list: ['c'] }, + }; + + expect(strategy.transformToConfig(strategy.transformToManifest([cache]))).toEqual([cache]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts new file mode 100644 index 00000000..1975b1d7 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts @@ -0,0 +1,178 @@ +import { all, create } from 'mathjs'; +import type { AzionCache } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +const math = create(all); + +const MAX_AGE_SECONDS = 31536000; + +/** + * CacheProcessConfigStrategy V6 + * @class CacheProcessConfigStrategy + * @description This class is implementation of the Cache ProcessConfig Strategy for API V6. + */ +class CacheProcessConfigStrategy extends ProcessConfigStrategy { + // Helper function to safely evaluate mathematical expressions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private evaluateMathExpression = (expression: any) => { + if (typeof expression === 'number') { + return expression; + } + if (/^[0-9+\-*/.() ]+$/.test(expression)) { + return math.evaluate(expression); + } + throw new Error(`Expression is not purely mathematical: ${expression}`); + }; + + // The v6 API accepts a max age from 0 to 1 year, and an expression is only evaluated here + private evaluateMaxAge = (expression: unknown, field: string, cacheName: string) => { + const seconds = this.evaluateMathExpression(expression); + if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0 || seconds > MAX_AGE_SECONDS) { + throw new Error( + `Cache "${cacheName}" has ${field} "${String(expression)}" which is not a number of seconds between 0 and ${MAX_AGE_SECONDS}.`, + ); + } + return seconds; + }; + + /** + * Transform azion.config cache settings to V6 manifest format + */ + transformToManifest(applicationCache: AzionCache[]) { + if (!Array.isArray(applicationCache) || applicationCache.length === 0) { + return []; + } + + return applicationCache.map((cache) => { + const maxAgeSecondsBrowser = cache?.browser + ? this.evaluateMaxAge(cache.browser.maxAgeSeconds, 'browser.maxAgeSeconds', cache.name) + : 0; + const maxAgeSecondsEdge = cache?.edge + ? this.evaluateMaxAge(cache.edge.maxAgeSeconds, 'edge.maxAgeSeconds', cache.name) + : 60; + + // Build cache_vary_by_method array based on methods configuration + const cacheVaryByMethod: string[] = []; + if (cache?.methods?.post) cacheVaryByMethod.push('post'); + if (cache?.methods?.options) cacheVaryByMethod.push('options'); + + // Build cache_vary_by_querystring object + const cacheVaryByQuerystring = { + behavior: cache?.cacheByQueryString?.option || 'ignore', + fields: cache?.cacheByQueryString?.list || [], + sort_enabled: cache?.queryStringSort || false, + }; + + // Build cache_vary_by_cookies object + const cacheVaryByCookies = { + behavior: cache?.cacheByCookie?.option || 'ignore', + cookie_names: cache?.cacheByCookie?.list || [], + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const cachePayload: any = { + name: cache.name, + browser_cache: { + behavior: cache?.browser ? 'override' : 'honor', + max_age: maxAgeSecondsBrowser, + }, + modules: { + cache: { + behavior: cache?.edge ? 'override' : 'honor', + max_age: maxAgeSecondsEdge, + stale_cache: { + enabled: cache?.stale || false, + }, + large_file_cache: { + enabled: false, // Default for now, could be extended later + offset: 1024, // Default offset + }, + tiered_cache: { + enabled: cache?.tieredCache?.enabled || false, + }, + }, + application_accelerator: { + cache_vary_by_method: cacheVaryByMethod, + cache_vary_by_querystring: cacheVaryByQuerystring, + cache_vary_by_cookies: cacheVaryByCookies, + cache_vary_by_devices: { + behavior: 'ignore', // Default behavior + device_group: [], + }, + }, + }, + }; + + if (cache?.tieredCache?.enabled === true) { + cachePayload.modules.cache.tiered_cache.topology = cache.tieredCache.topology; + } + + return cachePayload; + }); + } + + /** + * Transform V6 manifest format back to azion.config cache settings + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(cacheSettings: any[]) { + if (!Array.isArray(cacheSettings) || cacheSettings.length === 0) { + return []; + } + + return cacheSettings.map((cache) => { + const maxAgeSecondsBrowser = cache.browser_cache?.max_age + ? this.evaluateMathExpression(cache.browser_cache.max_age) + : 0; + const maxAgeSecondsEdge = cache.modules?.cache?.max_age + ? this.evaluateMathExpression(cache.modules.cache.max_age) + : 60; + + const cacheSetting: AzionCache = { + name: cache.name, + stale: cache.modules?.cache?.stale_cache?.enabled || false, + browser: { + maxAgeSeconds: maxAgeSecondsBrowser, + }, + edge: { + maxAgeSeconds: maxAgeSecondsEdge, + }, + methods: { + post: cache.modules?.application_accelerator?.cache_vary_by_method?.includes('post') || false, + options: cache.modules?.application_accelerator?.cache_vary_by_method?.includes('options') || false, + }, + queryStringSort: cache.modules?.application_accelerator?.cache_vary_by_querystring?.sort_enabled || false, + tieredCache: { + enabled: cache.modules?.cache?.tiered_cache?.enabled || false, + }, + }; + + if (cacheSetting.tieredCache && cacheSetting.tieredCache.enabled === true) { + cacheSetting.tieredCache.topology = cache.modules?.cache?.tiered_cache?.topology; + } + + // Handle cache by query string + if (cache.modules?.application_accelerator?.cache_vary_by_querystring) { + const queryStringConfig = cache.modules.application_accelerator.cache_vary_by_querystring; + cacheSetting.cacheByQueryString = { + option: queryStringConfig.behavior, + list: queryStringConfig.fields || [], + }; + } + + // Handle cache by cookie + if (cache.modules?.application_accelerator?.cache_vary_by_cookies) { + const cookieConfig = cache.modules.application_accelerator.cache_vary_by_cookies; + cacheSetting.cacheByCookie = { + option: cookieConfig.behavior, + list: cookieConfig.cookie_names || [], + }; + } + + return cacheSetting; + }); + } +} + +export default CacheProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.test.ts new file mode 100644 index 00000000..f90c99c6 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.test.ts @@ -0,0 +1,37 @@ +import DeviceGroupsProcessConfigStrategy from './deviceGroupsProcessConfigStrategy'; + +describe('DeviceGroupsProcessConfigStrategy (v6)', () => { + const strategy = new DeviceGroupsProcessConfigStrategy(); + + describe('transformToManifest', () => { + it('should map each device group to the manifest', () => { + expect( + strategy.transformToManifest([ + { name: 'mobile', userAgent: 'Android|iPhone' }, + { name: 'desktop', userAgent: 'Windows|Macintosh' }, + ]), + ).toEqual([ + { name: 'mobile', user_agent: 'Android|iPhone' }, + { name: 'desktop', user_agent: 'Windows|Macintosh' }, + ]); + }); + + it('should return undefined when there are no device groups', () => { + expect(strategy.transformToManifest([])).toBeUndefined(); + expect(strategy.transformToManifest(undefined as never)).toBeUndefined(); + }); + }); + + describe('transformToConfig', () => { + it('should map the manifest device groups back to the config', () => { + expect(strategy.transformToConfig([{ name: 'mobile', user_agent: 'Android|iPhone' }])).toEqual([ + { name: 'mobile', userAgent: 'Android|iPhone' }, + ]); + }); + + it('should return an empty array when there are no device groups', () => { + expect(strategy.transformToConfig([])).toEqual([]); + expect(strategy.transformToConfig(undefined as never)).toEqual([]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts new file mode 100644 index 00000000..9f0e6ef3 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts @@ -0,0 +1,39 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionDeviceGroupV6 } from '../../../types'; + +/** + * DeviceGroupsProcessConfigStrategy V6 + * @class DeviceGroupsProcessConfigStrategy + * @description Converts the device groups of a v6 application between the config and the manifest. + */ +class DeviceGroupsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config device groups to the v6 manifest format + */ + transformToManifest(deviceGroups: AzionDeviceGroupV6[]) { + if (!Array.isArray(deviceGroups) || deviceGroups.length === 0) { + return; + } + + return deviceGroups.map((deviceGroup) => ({ + name: deviceGroup.name, + user_agent: deviceGroup.userAgent, + })); + } + + /** + * Transform the v6 manifest format back to azion.config device groups + */ + transformToConfig(payload: Array<{ name: string; user_agent: string }>): AzionDeviceGroupV6[] { + if (!Array.isArray(payload) || payload.length === 0) { + return []; + } + + return payload.map((deviceGroup) => ({ + name: deviceGroup.name, + userAgent: deviceGroup.user_agent, + })); + } +} + +export default DeviceGroupsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..886a57fd --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts @@ -0,0 +1,53 @@ +import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; + +describe('FunctionInstancesProcessConfigStrategy (v6)', () => { + let strategy: FunctionInstancesProcessConfigStrategy; + + beforeEach(() => { + strategy = new FunctionInstancesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + const config = { version: 6 as const, functions: [{ name: 'fn', path: './fn.js' }] }; + + it('should return undefined when there are no instances', () => { + expect(strategy.transformToManifest([], config)).toBeUndefined(); + }); + + it('should map an instance to the manifest and apply the defaults', () => { + expect(strategy.transformToManifest([{ name: 'instance', ref: 'fn' }], config)).toEqual([ + { name: 'instance', function: 'fn', args: {} }, + ]); + expect(strategy.transformToManifest([{ name: 'i', ref: 'fn', args: { a: 1 } }], config)).toEqual([ + { name: 'i', function: 'fn', args: { a: 1 } }, + ]); + }); + + it('should throw when a referenced function name is not defined', () => { + expect(() => strategy.transformToManifest([{ name: 'instance', ref: 'missing' }], config)).toThrow( + 'Function instance "instance" references non-existent Function "missing".', + ); + expect(() => strategy.transformToManifest([{ name: 'instance', ref: 'fn' }], { version: 6 })).toThrow( + 'references non-existent Function "fn"', + ); + }); + + it('should not validate a function referenced by id', () => { + expect(strategy.transformToManifest([{ name: 'instance', ref: 10 }], { version: 6 })).toEqual([ + { name: 'instance', function: 10, args: {} }, + ]); + }); + }); + + describe('transformToConfig', () => { + it('should return an empty array when there is nothing to convert', () => { + expect(strategy.transformToConfig([])).toEqual([]); + }); + + it('should map the manifest instances back to the config', () => { + expect(strategy.transformToConfig([{ name: 'i', function: 10, args: { a: 1 } }])).toEqual([ + { name: 'i', ref: 10, args: { a: 1 } }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts new file mode 100644 index 00000000..dec21149 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts @@ -0,0 +1,67 @@ +import type { AzionFunctionInstance } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionFunctionV6 } from '../../../types'; + +/** + * FunctionInstancesProcessConfigStrategy V6 + * @class FunctionInstancesProcessConfigStrategy + * @description This class is implementation of the Function Instances Process Config Strategy for API V6. + */ +class FunctionInstancesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that referenced Function exists + */ + private validateFunctionReference( + functions: AzionFunctionV6[] | undefined, + functionNameOrId: string | number, + instanceName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof functionNameOrId === 'string') { + if (!Array.isArray(functions) || !functions.find((func) => func.name === functionNameOrId)) { + throw new Error(`Function instance "${instanceName}" references non-existent Function "${functionNameOrId}".`); + } + } + } + + /** + * Transform azion.config Function Instances to V6 manifest format + */ + transformToManifest(functionInstances: AzionFunctionInstance[], config: AzionConfigV6) { + if (!Array.isArray(functionInstances) || functionInstances.length === 0) { + return; + } + + return functionInstances.map((instance) => { + // Validate Function reference + this.validateFunctionReference(config.functions, instance.ref, instance.name); + + return { + name: instance.name, + function: instance.ref, + args: instance.args || {}, + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config Function Instances + * Note: the API returns function as ID, but azion.config expects function name. + * The CLI should resolve ID to name before calling this method. + */ + transformToConfig( + payload: Array<{ name: string; function: number | string; args?: Record }>, + ): AzionFunctionInstance[] { + if (!Array.isArray(payload) || payload.length === 0) { + return []; + } + + return payload.map((instance) => ({ + name: instance.name, + ref: instance.function, + args: instance.args, + })); + } +} + +export default FunctionInstancesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..4d41f6de --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts @@ -0,0 +1,140 @@ +import type { AzionManifestRule, AzionRules } from '../../../../../types'; +import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; + +describe('RulesProcessConfigStrategy (v6)', () => { + let strategy: RulesProcessConfigStrategy; + + const rules: AzionRules = { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + ], + response: [ + { + name: 'Add header', + criteria: [[{ variable: 'status', conditional: 'if', operator: 'exists' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], + }, + ], + }; + + const manifest: AzionManifestRule[] = [ + { + phase: 'request', + rule: { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + }, + { + phase: 'response', + rule: { + name: 'Add header', + description: undefined, + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'exists' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], + }, + }, + ]; + + beforeEach(() => { + strategy = new RulesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no rules', () => { + expect(strategy.transformToManifest({})).toEqual([]); + }); + + it('should map request and response rules with their phase, wrapping the variables in ${}', () => { + expect(strategy.transformToManifest(rules, [{ name: 'fn', path: './fn.js' }])).toEqual(manifest); + }); + + it('should throw when run_function references a function that is not defined', () => { + expect(() => strategy.transformToManifest(rules, [{ name: 'other', path: './o.js' }])).toThrow( + 'Function "fn" referenced in rule "Execute Function" is not defined in the functions array.', + ); + }); + + it('should not validate a function referenced by id', () => { + const byId: AzionRules = { + request: [{ ...rules.request![0], behaviors: [{ type: 'run_function', attributes: { value: 10 } }] }], + }; + expect(() => strategy.transformToManifest(byId, [])).not.toThrow(); + }); + + describe('connector references', () => { + const connectorRules: AzionRules = { + request: [ + { + name: 'Deliver static assets', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '\\.js$' }]], + behaviors: [{ type: 'set_connector', attributes: { value: 'my-connector' } }], + }, + ], + }; + + it('should accept a set_connector that references a declared connector', () => { + expect(() => + strategy.transformToManifest(connectorRules, undefined, [ + { name: 'my-connector', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]), + ).not.toThrow(); + }); + + it('should throw when set_connector references a connector that is not declared', () => { + expect(() => + strategy.transformToManifest(connectorRules, undefined, [ + { name: 'other', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]), + ).toThrow( + 'Connector "my-connector" referenced in rule "Deliver static assets" is not defined in the connectors array.', + ); + }); + + it('should validate response rules too', () => { + expect(() => strategy.transformToManifest({ response: connectorRules.request }, undefined, [])).toThrow( + 'Connector "my-connector" referenced in rule', + ); + }); + + it('should not validate a connector referenced by id, nor when the config has no connectors', () => { + const byId: AzionRules = { + request: [ + { ...connectorRules.request![0], behaviors: [{ type: 'set_connector', attributes: { value: 10 } }] }, + ], + }; + expect(() => strategy.transformToManifest(byId, undefined, [])).not.toThrow(); + expect(() => strategy.transformToManifest(connectorRules)).not.toThrow(); + }); + }); + + it('should not validate the function references when the config has no functions', () => { + expect(() => strategy.transformToManifest(rules)).not.toThrow(); + }); + }); + + describe('transformToConfig', () => { + it('should return empty rules when the manifest is not an array', () => { + expect(strategy.transformToConfig(undefined as unknown as AzionManifestRule[])).toEqual({ + request: [], + response: [], + }); + }); + + it('should split the manifest rules by phase back into the config', () => { + const result = strategy.transformToConfig(manifest); + + expect(result.request).toHaveLength(1); + expect(result.response).toHaveLength(1); + expect(result.request![0]).toEqual(expect.objectContaining({ name: 'Execute Function' })); + expect(result.response![0]).toEqual(expect.objectContaining({ name: 'Add header' })); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts new file mode 100644 index 00000000..899e0583 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts @@ -0,0 +1,209 @@ +import type { + AzionManifestRule, + AzionRule, + AzionRuleBehavior, + AzionRuleCriteriaArray, + AzionRules, + RuleVariable, +} from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionConnectorV6, AzionFunctionV6 } from '../../../types'; + +/** + * RulesProcessConfigStrategy + * @class RulesProcessConfigStrategy + * @description This class is implementation of the Rules ProcessConfig Strategy for V6. + */ +class RulesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validates function references in rules + */ + private validateFunctionReferences(applicationRules: AzionRules, functions?: AzionFunctionV6[]) { + if (!functions) return; + + const definedFunctions = new Set(functions.map((f) => f.name)); + + // Check request rules + if (applicationRules.request) { + for (const rule of applicationRules.request) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'run_function' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedFunctions.has(behavior.attributes.value)) { + throw new Error( + `Function "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the functions array.`, + ); + } + } + } + } + } + + // Check response rules + if (applicationRules.response) { + for (const rule of applicationRules.response) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'run_function' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedFunctions.has(behavior.attributes.value)) { + throw new Error( + `Function "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the functions array.`, + ); + } + } + } + } + } + } + + /** + * Validates connector references in rules + */ + private validateConnectorReferences(applicationRules: AzionRules, connectors?: AzionConnectorV6[]) { + if (!connectors) return; + + const definedConnectors = new Set(connectors.map((c) => c.name)); + + for (const rule of [...(applicationRules.request ?? []), ...(applicationRules.response ?? [])]) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'set_connector' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedConnectors.has(behavior.attributes.value)) { + throw new Error( + `Connector "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the connectors array.`, + ); + } + } + } + } + } + + /** + * Transforms azion.config rules to API manifest format + */ + transformToManifest( + applicationRules: AzionRules, + functions?: AzionFunctionV6[], + connectors?: AzionConnectorV6[], + ): AzionManifestRule[] { + // Validate function references + this.validateFunctionReferences(applicationRules, functions); + + // Validate connector references + this.validateConnectorReferences(applicationRules, connectors); + + const payload: AzionManifestRule[] = []; + + if (!applicationRules || Object.keys(applicationRules).length === 0) { + return payload; + } + + // Process request rules + if (Array.isArray(applicationRules.request)) { + applicationRules.request.forEach((rule) => { + const manifestRule: AzionManifestRule = { + phase: 'request', + rule: { + name: rule.name, + description: rule.description, + criteria: rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ) as AzionRuleCriteriaArray, + behaviors: rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }, + }; + payload.push(manifestRule); + }); + } + + // Process response rules + if (Array.isArray(applicationRules.response)) { + applicationRules.response.forEach((rule) => { + const manifestRule: AzionManifestRule = { + phase: 'response', + rule: { + name: rule.name, + description: rule.description, + criteria: rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ) as AzionRuleCriteriaArray, + behaviors: rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }, + }; + payload.push(manifestRule); + }); + } + + return payload; + } + + /** + * Transforms API manifest format back to azion.config rules + */ + transformToConfig(rulesPayload: AzionManifestRule[]): AzionRules { + if (!Array.isArray(rulesPayload)) { + return { request: [], response: [] }; + } + + const rules: AzionRules = { + request: [], + response: [], + }; + + rulesPayload.forEach((manifestRule) => { + const rule: AzionRule = { + name: manifestRule.rule.name, + description: manifestRule.rule.description, + criteria: manifestRule.rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => { + const baseCriterion = { + variable: criterion.variable as RuleVariable, + conditional: criterion.conditional, + operator: criterion.operator, + }; + + // Add argument if present + if ('argument' in criterion && criterion.argument !== undefined) { + return { + ...baseCriterion, + argument: criterion.argument, + }; + } + + return baseCriterion; + }), + ) as AzionRuleCriteriaArray, + behaviors: manifestRule.rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }; + + if (manifestRule.phase === 'request') { + rules.request!.push(rule); + } else if (manifestRule.phase === 'response') { + rules.response!.push(rule); + } + }); + + return rules; + } +} + +export default RulesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts new file mode 100644 index 00000000..65ea1c84 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts @@ -0,0 +1,57 @@ +import type { AzionBuild } from '../../../../types'; +import type { AzionConfigV6 } from '../../types'; +import BuildProcessConfigStrategy from './buildProcessConfigStrategy'; + +describe('BuildProcessConfigStrategy (v6)', () => { + let strategy: BuildProcessConfigStrategy; + + beforeEach(() => { + strategy = new BuildProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when no build configuration is provided', () => { + const config: AzionConfigV6 = { version: 6 }; + expect(strategy.transformToManifest(config)).toBeUndefined(); + }); + + it('should transform a complete build configuration to manifest format', () => { + const buildConfig: AzionBuild = { + bundler: 'esbuild', + entry: { main: './src/index.js', worker: './src/worker.js' }, + polyfills: true, + worker: true, + preset: 'next', + memoryFS: { injectionDirs: ['./src/injected'], removePathPrefix: './src' }, + }; + + const result = strategy.transformToManifest({ version: 6, build: buildConfig }); + + expect(result).toEqual(buildConfig); + }); + }); + + describe('transformToConfig', () => { + it('should not set build when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.build).toBeUndefined(); + }); + + it('should transform a build manifest to config format and replace an existing build', () => { + const newBuildConfig: AzionBuild = { bundler: 'esbuild', entry: './src/new-index.js' }; + const transformedPayload: AzionConfigV6 = { + version: 6, + build: { bundler: 'webpack', entry: './src/old-index.js' }, + }; + + const result = strategy.transformToConfig({ build: newBuildConfig }, transformedPayload); + + expect(result).toEqual(newBuildConfig); + expect(transformedPayload.build).toEqual(newBuildConfig); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts new file mode 100644 index 00000000..f01b23c6 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts @@ -0,0 +1,28 @@ +import type { AzionBuild } from '../../../../types'; +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * BuildProcessConfigStrategy + * @class BuildProcessConfigStrategy + * @description This class is implementation of the v6 Build Process Config Strategy. + */ +class BuildProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + const build = config?.build; + if (!build) { + return; + } + const payload: AzionBuild = build; + return payload; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const build = payload?.build; + transformedPayload.build = build; + return transformedPayload.build; + } +} + +export default BuildProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts new file mode 100644 index 00000000..d7f53b49 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts @@ -0,0 +1,222 @@ +import type { AzionConfigV6, AzionConnectorV6 } from '../../types'; +import ConnectorProcessConfigStrategy from './connectorProcessConfigStrategy'; + +describe('ConnectorProcessConfigStrategy (v6)', () => { + let strategy: ConnectorProcessConfigStrategy; + + const toManifest = (connectors: AzionConnectorV6[]) => + strategy.transformToManifest({ version: 6, connectors }) as Record[]; + + beforeEach(() => { + strategy = new ConnectorProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there are no connectors', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(toManifest([])).toBeUndefined(); + }); + + it('should map a storage connector, leaving the prefix out when it is not set', () => { + expect( + toManifest([ + { name: 'with-prefix', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'no-prefix', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]), + ).toEqual([ + { name: 'with-prefix', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'no-prefix', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]); + }); + + it('should map a live ingest connector', () => { + expect(toManifest([{ name: 'ingest', type: 'live_ingest', attributes: { region: 'br-east-1' } }])).toEqual([ + { name: 'ingest', type: 'live_ingest', attributes: { region: 'br-east-1' } }, + ]); + }); + + it('should apply the defaults to an http connector with only the addresses and no null module configs', () => { + const [connector] = toManifest([ + { name: 'origin', type: 'http', attributes: { addresses: [{ address: 'origin.example.com' }] } }, + ]); + + expect(connector).toEqual({ + name: 'origin', + type: 'http', + attributes: { + addresses: [{ address: 'origin.example.com', http_port: 80, https_port: 443 }], + connection_options: { + dns_resolution: 'both', + transport_policy: 'preserve', + http_version_policy: 'http1_1', + host: '${host}', + path_prefix: '', + following_redirect: false, + real_ip_header: 'X-Real-IP', + real_port_header: 'X-Real-PORT', + }, + modules: { + load_balancer: { enabled: false }, + origin_shield: { enabled: false }, + }, + }, + }); + }); + + it('should map every field of an http connector to the manifest', () => { + const [connector] = toManifest([ + { + name: 'origin', + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpPort: 8080, + httpsPort: 8443, + modules: { loadBalancer: { serverRole: 'backup', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'force_ipv6', + transportPolicy: 'force_https', + httpVersionPolicy: 'http1_1', + host: 'example.com', + pathPrefix: '/api', + followingRedirect: true, + realIpHeader: 'X-Client-IP', + realPortHeader: 'X-Client-Port', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'ip_hash', maxRetries: 2, connectionTimeout: 10, readWriteTimeout: 20 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }, + }, + ]); + + expect(connector).toEqual({ + name: 'origin', + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + http_port: 8080, + https_port: 8443, + modules: { load_balancer: { server_role: 'backup', weight: 10 } }, + }, + ], + connection_options: { + dns_resolution: 'force_ipv6', + transport_policy: 'force_https', + http_version_policy: 'http1_1', + host: 'example.com', + path_prefix: '/api', + following_redirect: true, + real_ip_header: 'X-Client-IP', + real_port_header: 'X-Client-Port', + }, + modules: { + load_balancer: { + enabled: true, + config: { method: 'ip_hash', max_retries: 2, connection_timeout: 10, read_write_timeout: 20 }, + }, + origin_shield: { + enabled: true, + config: { + origin_ip_acl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', access_key: 'key', secret_key: 'secret' }, + }, + }, + }, + }, + }, + }, + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set connectors when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.connectors).toBeUndefined(); + }); + + it('should round trip storage, live ingest and http connectors through the manifest', () => { + const connectors: AzionConnectorV6[] = [ + { name: 'files', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'ingest', type: 'live_ingest', attributes: { region: 'us-east-2' } }, + { + name: 'origin', + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpPort: 80, + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 5 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'preserve', + httpVersionPolicy: 'http1_1', + host: '${host}', + pathPrefix: '', + followingRedirect: false, + realIpHeader: 'X-Real-IP', + realPortHeader: 'X-Real-PORT', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 0, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: false }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }, + }, + ]; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ connectors: toManifest(connectors) }, transformedPayload); + + expect(transformedPayload.connectors).toEqual(connectors); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts new file mode 100644 index 00000000..3755c174 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts @@ -0,0 +1,221 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionConnectorV6 } from '../../types'; + +/** + * ConnectorProcessConfigStrategy V6 + * @class ConnectorProcessConfigStrategy + * @description Converts the v6 connectors (http, storage and live ingest) between the config and the manifest. + * The v6 API does not accept null in the module configs, so they are left out of the manifest when the config has none. + */ +class ConnectorProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config connectors to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const connectors = config?.connectors; + if (!connectors || connectors.length === 0) { + return; + } + + return connectors.map((connector: AzionConnectorV6) => { + const baseConnector = { + name: connector.name, + type: connector.type, + }; + + if (connector.type === 'storage') { + return { + ...baseConnector, + attributes: { + bucket: connector.attributes.bucket, + ...(connector.attributes.prefix !== undefined && { prefix: connector.attributes.prefix }), + }, + }; + } + + if (connector.type === 'live_ingest') { + return { + ...baseConnector, + attributes: { + region: connector.attributes.region, + }, + }; + } + + const { addresses, connectionOptions, modules } = connector.attributes; + const loadBalancer = modules?.loadBalancer; + const originShield = modules?.originShield; + const hmac = originShield?.config?.hmac; + + return { + ...baseConnector, + attributes: { + addresses: addresses.map((addr) => ({ + address: addr.address, + http_port: addr.httpPort ?? 80, + https_port: addr.httpsPort ?? 443, + ...(addr.modules?.loadBalancer && { + modules: { + load_balancer: { + ...(addr.modules.loadBalancer.serverRole && { server_role: addr.modules.loadBalancer.serverRole }), + ...(addr.modules.loadBalancer.weight !== undefined && { weight: addr.modules.loadBalancer.weight }), + }, + }, + }), + })), + connection_options: { + dns_resolution: connectionOptions?.dnsResolution ?? 'both', + transport_policy: connectionOptions?.transportPolicy ?? 'preserve', + http_version_policy: connectionOptions?.httpVersionPolicy ?? 'http1_1', + host: connectionOptions?.host ?? '${host}', + path_prefix: connectionOptions?.pathPrefix ?? '', + following_redirect: connectionOptions?.followingRedirect ?? false, + real_ip_header: connectionOptions?.realIpHeader ?? 'X-Real-IP', + real_port_header: connectionOptions?.realPortHeader ?? 'X-Real-PORT', + }, + modules: { + load_balancer: { + enabled: loadBalancer?.enabled ?? false, + ...(loadBalancer?.config && { + config: { + method: loadBalancer.config.method ?? 'round_robin', + max_retries: loadBalancer.config.maxRetries ?? 0, + connection_timeout: loadBalancer.config.connectionTimeout ?? 60, + read_write_timeout: loadBalancer.config.readWriteTimeout ?? 120, + }, + }), + }, + origin_shield: { + enabled: originShield?.enabled ?? false, + ...(originShield?.config && { + config: { + origin_ip_acl: { + enabled: originShield.config.originIpAcl?.enabled ?? false, + }, + ...(hmac && { + hmac: { + enabled: hmac.enabled ?? false, + ...(hmac.config && { + config: { + type: hmac.config.type, + attributes: { + region: hmac.config.attributes.region, + service: hmac.config.attributes.service ?? 's3', + access_key: hmac.config.attributes.accessKey, + secret_key: hmac.config.attributes.secretKey, + }, + }, + }), + }, + }), + }, + }), + }, + }, + }, + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config connectors + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { connectors?: any[] }, transformedPayload: AzionConfigV6) { + if (!payload.connectors || payload.connectors.length === 0) { + return; + } + + transformedPayload.connectors = payload.connectors.map((connector) => { + const baseConnector = { + name: connector.name, + type: connector.type, + }; + + if (connector.type === 'storage') { + return { + ...baseConnector, + attributes: { + bucket: connector.attributes.bucket, + prefix: connector.attributes.prefix, + }, + } as AzionConnectorV6; + } + + if (connector.type === 'live_ingest') { + return { + ...baseConnector, + attributes: { region: connector.attributes.region }, + } as AzionConnectorV6; + } + + const { addresses, connection_options: options, modules } = connector.attributes; + const loadBalancer = modules?.load_balancer; + const originShield = modules?.origin_shield; + const hmac = originShield?.config?.hmac; + + return { + ...baseConnector, + attributes: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + addresses: addresses.map((addr: any) => ({ + address: addr.address, + httpPort: addr.http_port, + httpsPort: addr.https_port, + modules: addr.modules?.load_balancer && { + loadBalancer: { + serverRole: addr.modules.load_balancer.server_role, + weight: addr.modules.load_balancer.weight, + }, + }, + })), + connectionOptions: options && { + dnsResolution: options.dns_resolution, + transportPolicy: options.transport_policy, + httpVersionPolicy: options.http_version_policy, + host: options.host, + pathPrefix: options.path_prefix, + followingRedirect: options.following_redirect, + realIpHeader: options.real_ip_header, + realPortHeader: options.real_port_header, + }, + modules: modules && { + loadBalancer: loadBalancer && { + enabled: loadBalancer.enabled, + config: loadBalancer.config && { + method: loadBalancer.config.method, + maxRetries: loadBalancer.config.max_retries, + connectionTimeout: loadBalancer.config.connection_timeout, + readWriteTimeout: loadBalancer.config.read_write_timeout, + }, + }, + originShield: originShield && { + enabled: originShield.enabled, + config: originShield.config && { + originIpAcl: originShield.config.origin_ip_acl && { + enabled: originShield.config.origin_ip_acl.enabled, + }, + hmac: hmac && { + enabled: hmac.enabled, + config: hmac.config && { + type: hmac.config.type, + attributes: { + region: hmac.config.attributes.region, + service: hmac.config.attributes.service, + accessKey: hmac.config.attributes.access_key, + secretKey: hmac.config.attributes.secret_key, + }, + }, + }, + }, + }, + }, + }, + } as AzionConnectorV6; + }); + + return transformedPayload.connectors; + } +} + +export default ConnectorProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..3926554c --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts @@ -0,0 +1,160 @@ +import type { AzionConfigV6, AzionCustomPageV6 } from '../../types'; +import CustomPagesProcessConfigStrategy from './customPagesProcessConfigStrategy'; + +describe('CustomPagesProcessConfigStrategy (v6)', () => { + let strategy: CustomPagesProcessConfigStrategy; + + const connectors: AzionConfigV6['connectors'] = [ + { name: 'my-connector', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]; + const withPages = (customPages: AzionCustomPageV6[], extra: Partial = {}): AzionConfigV6 => ({ + version: 6, + connectors, + customPages, + ...extra, + }); + + beforeEach(() => { + strategy = new CustomPagesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no custom pages', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, customPages: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal page', () => { + expect( + strategy.transformToManifest( + withPages([ + { name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 'my-connector' } } }] }, + ]), + ), + ).toEqual([ + { + name: 'errors', + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 0, uri: null, custom_status_code: null }, + }, + }, + ], + }, + ]); + }); + + it('should map every field of the custom page to the manifest', () => { + expect( + strategy.transformToManifest( + withPages([ + { + name: 'errors', + pages: [ + { + code: 'default', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 300, uri: '/error.html', customStatusCode: 200 }, + }, + }, + { code: '500', page: { attributes: { connector: 'my-connector', uri: '/500.html' } } }, + ], + }, + ]), + ), + ).toEqual([ + { + name: 'errors', + pages: [ + { + code: 'default', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 300, uri: '/error.html', custom_status_code: 200 }, + }, + }, + { + code: '500', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 0, uri: '/500.html', custom_status_code: null }, + }, + }, + ], + }, + ]); + }); + + it('should keep a connector referenced by id as a string, without validating it', () => { + const [customPage] = strategy.transformToManifest({ + version: 6, + customPages: [{ name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 10 } } }] }], + }); + + expect(customPage.pages[0].page.attributes.connector).toBe('10'); + }); + + it('should throw when the connector of a page is not declared', () => { + const pages: AzionCustomPageV6[] = [ + { name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 'missing' } } }] }, + ]; + const message = 'Custom page "errors" with error code "404" references non-existent Connector "missing".'; + + expect(() => strategy.transformToManifest(withPages(pages))).toThrow(message); + expect(() => strategy.transformToManifest(withPages(pages, { connectors: undefined }))).toThrow(message); + }); + }); + + describe('transformToConfig', () => { + it('should not set custom pages when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ custom_pages: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.customPages).toBeUndefined(); + }); + + it('should map the custom_pages of the manifest back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + custom_pages: [ + { + name: 'errors', + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 10, ttl: 60, uri: '/404.html', custom_status_code: 404 }, + }, + }, + ], + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.customPages).toEqual([ + { + name: 'errors', + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 10, ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts new file mode 100644 index 00000000..39bfc3c2 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts @@ -0,0 +1,99 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionConnectorV6, AzionCustomPageV6 } from '../../types'; + +/** + * CustomPagesProcessConfigStrategy V6 + * @class CustomPagesProcessConfigStrategy + * @description Converts the v6 custom pages between the config (`customPages`) and the manifest (`custom_pages`). + * The connector of a page is kept in the manifest as the name (or the id as a string) the config has, which the Azion + * CLI resolves to the id of the API. + */ +class CustomPagesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate Connector references + */ + private validateConnectorReference( + connectors: AzionConnectorV6[] | undefined, + connectorNameOrId: string | number, + customPageName: string, + errorCode: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof connectorNameOrId === 'string') { + if (!Array.isArray(connectors) || !connectors.find((connector) => connector.name === connectorNameOrId)) { + throw new Error( + `Custom page "${customPageName}" with error code "${errorCode}" references non-existent Connector "${connectorNameOrId}".`, + ); + } + } + } + + /** + * Transform azion.config Custom Pages to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const customPages = config?.customPages; + if (!Array.isArray(customPages) || customPages.length === 0) { + return []; + } + + return customPages.map((customPage: AzionCustomPageV6) => { + // Validate connector references + customPage.pages.forEach((pageEntry) => { + this.validateConnectorReference( + config.connectors, + pageEntry.page.attributes.connector, + customPage.name, + pageEntry.code, + ); + }); + + return { + name: customPage.name, + pages: customPage.pages.map((pageEntry) => ({ + code: pageEntry.code, + page: { + type: pageEntry.page.type || 'page_connector', + attributes: { + connector: String(pageEntry.page.attributes.connector), + ttl: pageEntry.page.attributes.ttl ?? 0, + uri: pageEntry.page.attributes.uri || null, + custom_status_code: pageEntry.page.attributes.customStatusCode || null, + }, + }, + })), + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config Custom Pages + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { custom_pages?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.custom_pages) || payload.custom_pages.length === 0) { + return; + } + + transformedPayload.customPages = payload.custom_pages.map((customPage) => ({ + name: customPage.name, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + pages: customPage.pages.map((pageEntry: any) => ({ + code: pageEntry.code, + page: { + type: pageEntry.page.type, + attributes: { + connector: pageEntry.page.attributes.connector, // Keep as it comes from the API + ttl: pageEntry.page.attributes.ttl, + uri: pageEntry.page.attributes.uri, + customStatusCode: pageEntry.page.attributes.custom_status_code, + }, + }, + })), + })); + + return transformedPayload.customPages; + } +} + +export default CustomPagesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts new file mode 100644 index 00000000..a2f53993 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts @@ -0,0 +1,96 @@ +import type { AzionConfigV6 } from '../../types'; +import DeploymentProcessConfigStrategy from './deploymentProcessConfigStrategy'; + +describe('DeploymentProcessConfigStrategy (v6)', () => { + let strategy: DeploymentProcessConfigStrategy; + + beforeEach(() => { + strategy = new DeploymentProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no deployments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should write the binding policy and apply the defaults the API requires to the other fields', () => { + expect( + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + }), + ).toEqual([ + { + name: 'default-deployment', + description: null, + binding_policy: 'FLEXIBLE', + strategy_defaults: {}, + }, + ]); + }); + + it('should write the binding policy that the config declares', () => { + const policies = (['STRICT', 'FLEXIBLE'] as const).map( + (bindingPolicy) => + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy }], + })?.[0].binding_policy, + ); + + expect(policies).toEqual(['STRICT', 'FLEXIBLE']); + }); + + it('should map every field of the deployment to the manifest', () => { + const [deployment] = strategy.transformToManifest({ + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }); + + expect(deployment).toEqual({ + name: 'default-deployment', + description: 'Default', + binding_policy: 'STRICT', + strategy_defaults: { skew_protection: { enabled: true, default_ttl_seconds: 3600 } }, + deployment_policy: 'single_version', + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set deployments when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.deployments).toBeUndefined(); + }); + + it('should round trip a deployment through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ deployments: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.deployments).toEqual(config.deployments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts new file mode 100644 index 00000000..9670622c --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts @@ -0,0 +1,68 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionDeploymentV6 } from '../../types'; + +/** + * DeploymentProcessConfigStrategy + * @class DeploymentProcessConfigStrategy + * @description Converts the v6 deployments between the config and the manifest. + * The creation of a deployment requires `binding_policy`, which the config must declare. The replacement of a + * deployment also requires `description` and `strategy_defaults`, so the manifest defaults them to no description and + * no skew protection. + * The application a deployment serves is not part of it: the Azion CLI sets it when it creates a release. + */ +class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.deployments) || config.deployments.length === 0) { + return []; + } + + return config.deployments.map((deployment: AzionDeploymentV6) => { + const skewProtection = deployment.strategyDefaults?.skewProtection; + + return { + name: deployment.name, + description: deployment.description ?? null, + binding_policy: deployment.bindingPolicy, + strategy_defaults: skewProtection + ? { + skew_protection: { + enabled: skewProtection.enabled, + default_ttl_seconds: skewProtection.defaultTtlSeconds, + }, + } + : {}, + ...(deployment.deploymentPolicy && { deployment_policy: deployment.deploymentPolicy }), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { deployments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.deployments) || payload.deployments.length === 0) { + return; + } + + transformedPayload.deployments = payload.deployments.map((deployment) => { + const skewProtection = deployment.strategy_defaults?.skew_protection; + + return { + name: deployment.name, + description: deployment.description, + bindingPolicy: deployment.binding_policy, + deploymentPolicy: deployment.deployment_policy, + strategyDefaults: skewProtection + ? { + skewProtection: { + enabled: skewProtection.enabled, + defaultTtlSeconds: skewProtection.default_ttl_seconds, + }, + } + : undefined, + }; + }); + + return transformedPayload.deployments; + } +} + +export default DeploymentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts new file mode 100644 index 00000000..14a13f73 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts @@ -0,0 +1,118 @@ +import type { AzionConfigV6 } from '../../types'; +import EnvironmentProcessConfigStrategy from './environmentProcessConfigStrategy'; + +describe('EnvironmentProcessConfigStrategy (v6)', () => { + let strategy: EnvironmentProcessConfigStrategy; + + beforeEach(() => { + strategy = new EnvironmentProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no environments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should write the deployment policy and apply the defaults the API requires to the other fields', () => { + expect( + strategy.transformToManifest({ + version: 6, + environments: [{ name: 'production', deploymentPolicy: 'single_version' }], + }), + ).toEqual([ + { + name: 'production', + description: null, + log_verbosity: 'normal', + robots_policy: 'respect_origin', + protection: {}, + branch_tracking: null, + deployment_policy: 'single_version', + }, + ]); + }); + + it('should write the deployment policy that the config declares', () => { + const policies = (['single_version', 'versioned_urls'] as const).map( + (deploymentPolicy) => + strategy.transformToManifest({ version: 6, environments: [{ name: 'production', deploymentPolicy }] })?.[0] + .deployment_policy, + ); + + expect(policies).toEqual(['single_version', 'versioned_urls']); + }); + + it('should map every field of the environment to the manifest', () => { + const [environment] = strategy.transformToManifest({ + version: 6, + environments: [ + { + name: 'staging', + description: 'Staging', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: true, idpId: 'idp', allowedDomains: ['azion.com'] }, + }, + branchTracking: { enabled: true, mode: 'branch_is', branchMatch: 'main' }, + deploymentPolicy: 'versioned_urls', + }, + ], + }); + + expect(environment).toEqual({ + name: 'staging', + description: 'Staging', + log_verbosity: 'verbose', + robots_policy: 'noindex', + protection: { + azion_authentication: { enabled: true }, + password_protection: { enabled: true, secret_id: 'secret' }, + ip_allowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + sso_enforcement: { enabled: true, idp_id: 'idp', allowed_domains: ['azion.com'] }, + }, + branch_tracking: { enabled: true, mode: 'branch_is', branch_match: 'main' }, + deployment_policy: 'versioned_urls', + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set environments when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.environments).toBeUndefined(); + }); + + it('should round trip an environment through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + environments: [ + { + name: 'staging', + description: 'Staging', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: true, idpId: 'idp', allowedDomains: ['azion.com'] }, + }, + branchTracking: { enabled: true, mode: 'branch_is', branchMatch: 'main' }, + deploymentPolicy: 'versioned_urls', + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ environments: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.environments).toEqual(config.environments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts new file mode 100644 index 00000000..b584e3be --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts @@ -0,0 +1,99 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionEnvironmentV6 } from '../../types'; + +/** + * EnvironmentProcessConfigStrategy + * @class EnvironmentProcessConfigStrategy + * @description Converts the v6 environments between the config and the manifest. + * The creation of an environment requires `deployment_policy`, which the config must declare because the API does not + * accept changing it afterwards. The replacement of an environment also requires `log_verbosity`, `robots_policy`, + * `protection`, `branch_tracking` and `description`, so the manifest defaults them to the least intrusive values: + * normal logs, the robots policy of the origin, no protection, no branch tracking and no description. + */ +class EnvironmentProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.environments) || config.environments.length === 0) { + return []; + } + + return config.environments.map((environment: AzionEnvironmentV6) => { + const { protection, branchTracking } = environment; + + return { + name: environment.name, + description: environment.description ?? null, + log_verbosity: environment.logVerbosity ?? 'normal', + robots_policy: environment.robotsPolicy ?? 'respect_origin', + protection: { + ...(protection?.azionAuthentication && { azion_authentication: protection.azionAuthentication }), + ...(protection?.passwordProtection && { + password_protection: { + enabled: protection.passwordProtection.enabled, + secret_id: protection.passwordProtection.secretId, + }, + }), + ...(protection?.ipAllowlist && { ip_allowlist: protection.ipAllowlist }), + ...(protection?.ssoEnforcement && { + sso_enforcement: { + enabled: protection.ssoEnforcement.enabled, + idp_id: protection.ssoEnforcement.idpId, + allowed_domains: protection.ssoEnforcement.allowedDomains, + }, + }), + }, + branch_tracking: branchTracking + ? { + enabled: branchTracking.enabled, + mode: branchTracking.mode, + branch_match: branchTracking.branchMatch, + } + : null, + deployment_policy: environment.deploymentPolicy, + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { environments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.environments) || payload.environments.length === 0) { + return; + } + + transformedPayload.environments = payload.environments.map((environment) => { + const protection = environment.protection; + const branchTracking = environment.branch_tracking; + + return { + name: environment.name, + description: environment.description, + logVerbosity: environment.log_verbosity, + robotsPolicy: environment.robots_policy, + protection: protection && { + azionAuthentication: protection.azion_authentication, + passwordProtection: protection.password_protection && { + enabled: protection.password_protection.enabled, + secretId: protection.password_protection.secret_id, + }, + ipAllowlist: protection.ip_allowlist, + ssoEnforcement: protection.sso_enforcement && { + enabled: protection.sso_enforcement.enabled, + idpId: protection.sso_enforcement.idp_id, + allowedDomains: protection.sso_enforcement.allowed_domains, + }, + }, + branchTracking: branchTracking + ? { + enabled: branchTracking.enabled, + mode: branchTracking.mode, + branchMatch: branchTracking.branch_match, + } + : null, + deploymentPolicy: environment.deployment_policy, + }; + }); + + return transformedPayload.environments; + } +} + +export default EnvironmentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts new file mode 100644 index 00000000..16fa8dfb --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts @@ -0,0 +1,185 @@ +import type { AzionConfigV6 } from '../../types'; +import FunctionsProcessConfigStrategy from './functionsProcessConfigStrategy'; + +describe('FunctionsProcessConfigStrategy (v6)', () => { + let strategy: FunctionsProcessConfigStrategy; + + beforeEach(() => { + strategy = new FunctionsProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no functions', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, functions: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal function', () => { + const result = strategy.transformToManifest({ + version: 6, + functions: [{ name: 'my-function', path: './functions/index.js' }], + }); + + expect(result).toEqual([ + { + name: 'my-function', + runtime: 'azion_js', + default_args: {}, + execution_environment: 'application', + path: './functions/index.js', + }, + ]); + }); + + it('should map every field of the function to the manifest', () => { + const result = strategy.transformToManifest({ + version: 6, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + }, + ], + }); + + expect(result).toEqual([ + { + name: 'my-function', + runtime: 'azion_js', + default_args: { key: 'value' }, + execution_environment: 'firewall', + path: './functions/index.js', + }, + ]); + }); + }); + + describe('bindings', () => { + const withBinding = (bucket: string, storage?: AzionConfigV6['storage']): AzionConfigV6 => ({ + version: 6, + storage, + functions: [ + { name: 'my-function', path: './functions/index.js', bindings: { storage: { bucket, prefix: 'p' } } }, + ], + }); + + it('should write the bindings to the manifest', () => { + const [func] = strategy.transformToManifest( + withBinding('my-bucket', [{ name: 'my-bucket', dir: './dist', prefix: 'p' }]), + ); + + expect(func.bindings).toEqual({ storage: { bucket: 'my-bucket', prefix: 'p' } }); + }); + + it('should leave the bindings out of the manifest when the function has none', () => { + const [func] = strategy.transformToManifest({ version: 6, functions: [{ name: 'f', path: './f.js' }] }); + + expect(func.bindings).toBeUndefined(); + }); + + it('should throw when the storage bucket of a binding is not defined', () => { + const message = + 'Function "my-function" references storage bucket "my-bucket" which is not defined in the storage configuration.'; + + expect(() => strategy.transformToManifest(withBinding('my-bucket'))).toThrow(message); + expect(() => + strategy.transformToManifest(withBinding('my-bucket', [{ name: 'other-bucket', dir: './dist' }])), + ).toThrow(message); + }); + + it('should not validate a bucket referenced by id', () => { + expect(() => strategy.transformToManifest(withBinding(10 as unknown as string))).not.toThrow(); + }); + }); + + describe('transformToConfig', () => { + it('should not set functions when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.functions).toBeUndefined(); + }); + + it('should map the manifest functions back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + functions: [ + { + name: 'my-function', + runtime: 'azion_js', + default_args: { key: 'value' }, + execution_environment: 'firewall', + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.functions).toEqual([ + { + name: 'my-function', + path: './functions/my-function.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + }, + ]); + }); + }); + + describe('dependencies', () => { + const config = (dependencies: object[], extra: Partial = {}) => + ({ + version: 6, + connectors: [{ name: 'my-origin', type: 'live_ingest', attributes: { region: 'us-east-1' } }], + networkList: [{ name: 'my-list', type: 'countries', items: ['BR'] }], + functions: [{ name: 'fn', path: './fn.js', dependencies }], + ...extra, + }) as AzionConfigV6; + + it('should write the dependencies with the name or the ID of the resource', () => { + const [fn] = strategy.transformToManifest( + config([ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-list' }, + { type: 'connector', ref: 10 }, + ]), + ); + + expect(fn.dependencies).toEqual([ + { type: 'connector', id: 'my-origin' }, + { type: 'network_list', id: 'my-list' }, + { type: 'connector', id: 10 }, + ]); + }); + + it('should not write dependencies when the function has none', () => { + expect(strategy.transformToManifest(config([]))[0]).not.toHaveProperty('dependencies'); + }); + + it('should throw when the connector or network list is not declared', () => { + expect(() => strategy.transformToManifest(config([{ type: 'connector', ref: 'other' }]))).toThrow( + 'Function "fn" depends on non-existent Connector "other".', + ); + expect(() => strategy.transformToManifest(config([{ type: 'network_list', ref: 'my-origin' }]))).toThrow( + 'Function "fn" depends on non-existent Network List "my-origin".', + ); + }); + + it('should read the dependencies back from the manifest', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { functions: [{ name: 'fn', dependencies: [{ type: 'connector', id: 'my-origin' }] }] }, + transformedPayload, + ); + + expect(transformedPayload.functions?.[0].dependencies).toEqual([{ type: 'connector', ref: 'my-origin' }]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts new file mode 100644 index 00000000..91a9eeaf --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts @@ -0,0 +1,104 @@ +import type { FunctionExecutionEnvironment, FunctionRuntime } from '../../../../types'; +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionFunctionDependencyV6 } from '../../types'; + +/** + * FunctionsProcessConfigStrategy V6 + * @class FunctionsProcessConfigStrategy + * @description This class is implementation of the Functions Process Config Strategy for API V6. + */ +class FunctionsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate storage binding reference + */ + private validateStorageBinding(config: AzionConfigV6, bucketNameOrId: string | number, functionName: string) { + if (typeof bucketNameOrId === 'string') { + if (!Array.isArray(config?.storage) || !config.storage.find((storage) => storage.name === bucketNameOrId)) { + throw new Error( + `Function "${functionName}" references storage bucket "${bucketNameOrId}" which is not defined in the storage configuration.`, + ); + } + } + } + + /** + * Validate that the connector or network list of a dependency is declared. A number is an ID, which is not validated. + */ + private validateDependency(config: AzionConfigV6, dependency: AzionFunctionDependencyV6, functionName: string) { + if (typeof dependency.ref !== 'string') return; + + const declared = dependency.type === 'connector' ? config.connectors : config.networkList; + if (!declared?.some((resource) => resource.name === dependency.ref)) { + const label = dependency.type === 'connector' ? 'Connector' : 'Network List'; + throw new Error(`Function "${functionName}" depends on non-existent ${label} "${dependency.ref}".`); + } + } + + /** + * Transform azion.config Functions to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.functions) || config?.functions.length === 0) { + return []; + } + + return config.functions.map((func) => { + // Validate storage binding if exists + if (func.bindings?.storage?.bucket) { + this.validateStorageBinding(config, func.bindings.storage.bucket, func.name); + } + + return { + name: func.name, + runtime: func.runtime || 'azion_js', + default_args: func.defaultArgs || {}, + execution_environment: func.executionEnvironment || 'application', + path: func.path, + bindings: func.bindings, + ...(func.dependencies && + func.dependencies.length > 0 && { + dependencies: func.dependencies.map((dependency) => { + this.validateDependency(config, dependency, func.name); + return { type: dependency.type, id: dependency.ref }; + }), + }), + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config Functions + */ + transformToConfig( + payload: { + functions?: Array<{ + name: string; + runtime?: string; + default_args?: Record; + execution_environment?: string; + dependencies?: Array<{ type: string; id: string | number }>; + }>; + }, + transformedPayload: AzionConfigV6, + ) { + if (!Array.isArray(payload?.functions) || payload?.functions.length === 0) { + return; + } + + transformedPayload.functions = payload.functions.map((func) => ({ + name: func.name, + path: `./functions/${func.name}.js`, // Default path since it's not in the API + runtime: func.runtime as FunctionRuntime, + defaultArgs: func.default_args, + executionEnvironment: func.execution_environment as FunctionExecutionEnvironment, + ...(func.dependencies && { + dependencies: func.dependencies.map((dependency) => ({ + type: dependency.type as AzionFunctionDependencyV6['type'], + ref: dependency.id, + })), + }), + })); + } +} + +export default FunctionsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts new file mode 100644 index 00000000..97001041 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts @@ -0,0 +1,88 @@ +import type { AzionConfigV6 } from '../../types'; +import PurgeProcessConfigStrategy from './purgeProcessConfigStrategy'; + +describe('PurgeProcessConfigStrategy (v6)', () => { + let strategy: PurgeProcessConfigStrategy; + + beforeEach(() => { + strategy = new PurgeProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no purge', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, purge: [] })).toBeUndefined(); + }); + + it('should map a purge to the manifest and default the layer to cache', () => { + const config: AzionConfigV6 = { + version: 6, + purge: [ + { type: 'url', items: ['https://example.com/path'] }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'cache' }, + { type: 'cachekey', items: ['example.com/path'] }, + ], + }; + + expect(strategy.transformToManifest(config)).toEqual([ + { type: 'url', items: ['https://example.com/path'], layer: 'cache' }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'cache' }, + { type: 'cachekey', items: ['example.com/path'], layer: 'cache' }, + ]); + }); + + it('should throw when a url item has no protocol', () => { + expect(() => + strategy.transformToManifest({ version: 6, purge: [{ type: 'url', items: ['example.com/path'] }] }), + ).toThrow('The URL must contain the protocol (http:// or https://).'); + }); + + it('should throw when a wildcard item has no asterisk', () => { + expect(() => + strategy.transformToManifest({ + version: 6, + purge: [{ type: 'wildcard', items: ['https://example.com/path'] }], + }), + ).toThrow('The wildcard purge must contain the wildcard character (*).'); + }); + }); + + describe('transformToConfig', () => { + it('should return undefined when the manifest has no purge', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ purge: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.purge).toBeUndefined(); + }); + + it('should map the manifest back to the config and replace an existing purge', () => { + const transformedPayload: AzionConfigV6 = { + version: 6, + purge: [{ type: 'url', items: ['https://example.com/old'] }], + }; + + const result = strategy.transformToConfig( + { purge: [{ type: 'url', items: ['https://example.com/new'] }] }, + transformedPayload, + ); + + expect(result).toEqual([{ type: 'url', items: ['https://example.com/new'], layer: 'cache' }]); + expect(transformedPayload.purge).toEqual(result); + }); + + it('should apply the same item checks as the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(() => + strategy.transformToConfig({ purge: [{ type: 'url', items: ['example.com'] }] }, transformedPayload), + ).toThrow('The URL must contain the protocol (http:// or https://).'); + expect(() => + strategy.transformToConfig( + { purge: [{ type: 'wildcard', items: ['https://example.com'] }] }, + transformedPayload, + ), + ).toThrow('The wildcard purge must contain the wildcard character (*).'); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts new file mode 100644 index 00000000..56aedf76 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts @@ -0,0 +1,62 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionPurgeV6 } from '../../types'; + +/** + * Checks the items of a purge as the Azion CLI needs them: a `url` carries the protocol and a `wildcard` the asterisk. + */ +function validatePurgeItems(purge: Pick) { + purge.items.forEach((value) => { + if (purge.type === 'url' && !value.includes('http://') && !value.includes('https://')) { + throw new Error('The URL must contain the protocol (http:// or https://).'); + } + + if (purge.type === 'wildcard' && !value.includes('*')) { + throw new Error('The wildcard purge must contain the wildcard character (*).'); + } + }); +} + +/** + * PurgeProcessConfigStrategy V6 + * @class PurgeProcessConfigStrategy + * @description Converts the v6 purge between the config and the manifest. + */ +class PurgeProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.purge) || config.purge.length === 0) { + return; + } + + return config.purge.map((purge) => { + validatePurgeItems(purge); + + return { + type: purge.type, + items: purge.items, + layer: purge.layer ?? 'cache', + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const purgeConfig = payload.purge; + if (!Array.isArray(purgeConfig) || purgeConfig.length === 0) { + return; + } + + transformedPayload.purge = purgeConfig.map((purge: AzionPurgeV6) => { + validatePurgeItems(purge); + + return { + type: purge.type, + items: purge.items, + layer: purge.layer ?? 'cache', + }; + }); + + return transformedPayload.purge; + } +} + +export default PurgeProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts new file mode 100644 index 00000000..be3894e1 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts @@ -0,0 +1,373 @@ +import type { AzionConfigV6, AzionFirewallBehaviorV6, AzionFirewallV6 } from '../../../types'; +import FirewallProcessConfigStrategy from './firewallProcessConfigStrategy'; + +describe('FirewallProcessConfigStrategy (v6)', () => { + let strategy: FirewallProcessConfigStrategy; + + const withFirewall = (firewall: AzionFirewallV6, extra: Partial = {}): AzionConfigV6 => ({ + version: 6, + firewall: [firewall], + ...extra, + }); + const withBehaviors = (behaviors: AzionFirewallBehaviorV6[]) => + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors, + }, + ], + }); + + beforeEach(() => { + strategy = new FirewallProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no firewalls', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults to a firewall with only the name', () => { + expect(strategy.transformToManifest(withFirewall({ name: 'my-firewall' }))).toEqual([ + { + name: 'my-firewall', + modules: { + functions: { enabled: true }, + network_protection: { enabled: true }, + waf: { enabled: false }, + }, + debug: false, + }, + ]); + }); + + it('should write active and debugRules to the manifest (v4 ignored them)', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ name: 'my-firewall', debugRules: true, functions: false, waf: true }), + ); + + expect(firewall).toEqual( + expect.objectContaining({ + debug: true, + modules: { + functions: { enabled: false }, + network_protection: { enabled: true }, + waf: { enabled: true }, + }, + }), + ); + }); + + it('should wrap the variables of the criteria in ${} and keep them in one group', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + description: 'Block admin', + criteria: [ + { variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }, + { variable: '${host}', conditional: 'and', operator: 'exists' }, + ], + behaviors: [{ type: 'deny' }], + }, + ], + }), + ); + + expect(firewall.rules_engine).toEqual([ + { + name: 'rule', + description: 'Block admin', + behaviors: [{ type: 'deny' }], + criteria: [ + [ + { variable: '${request_uri}', conditional: 'if', operator: 'starts_with', argument: '/admin' }, + { variable: '${host}', conditional: 'and', operator: 'exists' }, + ], + ], + }, + ]); + }); + + it('should build a matches criterion from match and variable', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [{ name: 'rule', match: '^/api', variable: 'request_uri', behaviors: [{ type: 'drop' }] }], + }), + ); + + expect(firewall.rules_engine[0].criteria).toEqual([ + [{ variable: '${request_uri}', operator: 'matches', conditional: 'if', argument: '^/api' }], + ]); + }); + + it('should accept a bypass behavior (new in v6) and keep run_function as it is', () => { + const [firewall] = strategy.transformToManifest( + withFirewall( + { + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'host', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }, { type: 'bypass' }], + }, + ], + }, + { functions: [{ name: 'fn', path: './fn.js' }] }, + ), + ); + + expect(firewall.rules_engine[0].behaviors).toEqual([ + { type: 'run_function', attributes: { value: 'fn' } }, + { type: 'bypass' }, + ]); + }); + + it('should map set_waf, set_rate_limit and set_custom_response to the manifest', () => { + const [firewall] = strategy.transformToManifest( + withBehaviors([{ type: 'set_waf', attributes: { mode: 'logging', wafId: 'my-waf' } }]), + ); + expect(firewall.rules_engine[0].behaviors).toEqual([ + { type: 'set_waf', attributes: { mode: 'logging', waf_id: 'my-waf' } }, + ]); + + const [rateLimit] = strategy.transformToManifest( + withBehaviors([ + { + type: 'set_rate_limit', + attributes: { type: 'minute', limitBy: 'client_ip', averageRateLimit: 100, maximumBurstSize: 20 }, + }, + ]), + ); + expect(rateLimit.rules_engine[0].behaviors).toEqual([ + { + type: 'set_rate_limit', + attributes: { type: 'minute', limit_by: 'client_ip', average_rate_limit: 100, maximum_burst_size: 20 }, + }, + ]); + + const [custom] = strategy.transformToManifest( + withBehaviors([ + { + type: 'set_custom_response', + attributes: { statusCode: 403, contentType: 'text/plain', contentBody: 'Forbidden' }, + }, + ]), + ); + expect(custom.rules_engine[0].behaviors).toEqual([ + { + type: 'set_custom_response', + attributes: { status_code: 403, content_type: 'text/plain', content_body: 'Forbidden' }, + }, + ]); + }); + + it('should leave out the optional attributes of the rate limit and of the custom response', () => { + const [rateLimit] = strategy.transformToManifest( + withBehaviors([{ type: 'set_rate_limit', attributes: { limitBy: 'global', averageRateLimit: 5 } }]), + ); + expect(rateLimit.rules_engine[0].behaviors[0].attributes).toEqual({ limit_by: 'global', average_rate_limit: 5 }); + + const [custom] = strategy.transformToManifest( + withBehaviors([{ type: 'set_custom_response', attributes: { statusCode: 404 } }]), + ); + expect(custom.rules_engine[0].behaviors[0].attributes).toEqual({ status_code: 404 }); + }); + + it('should throw when a terminal behavior is combined with another one', () => { + const terminal = (type: 'deny' | 'drop') => + strategy.transformToManifest( + withBehaviors([{ type }, { type: 'set_rate_limit', attributes: { limitBy: 'global', averageRateLimit: 5 } }]), + ); + + expect(() => terminal('deny')).toThrow("The behavior 'deny' is a terminal behavior and must be used alone."); + expect(() => terminal('drop')).toThrow("The behavior 'drop' is a terminal behavior and must be used alone."); + expect(() => + strategy.transformToManifest( + withBehaviors([{ type: 'set_custom_response', attributes: { statusCode: 403 } }, { type: 'bypass' }]), + ), + ).toThrow("The behavior 'set_custom_response' is a terminal behavior"); + }); + + describe('network list references', () => { + const withList = ( + operator: 'is_in_list' | 'is_not_in_list', + argument: string | number, + extra: Partial = {}, + ) => + withFirewall( + { + name: 'my-firewall', + rules: [ + { + name: 'Block list', + criteria: [{ variable: 'network', conditional: 'if', operator, argument }], + behaviors: [{ type: 'deny' }], + }, + ], + }, + extra, + ); + + it('should accept a rule that references a declared network list', () => { + const networkList = [{ name: 'blocked-ips', type: 'ip_cidr' as const, items: ['10.0.0.0/8'] }]; + + expect(() => + strategy.transformToManifest(withList('is_in_list', 'blocked-ips', { networkList })), + ).not.toThrow(); + expect(() => + strategy.transformToManifest(withList('is_not_in_list', 'blocked-ips', { networkList })), + ).not.toThrow(); + }); + + it('should throw when the network list is not declared', () => { + const message = 'Firewall rule "Block list" references non-existent Network List "blocked-ips".'; + + expect(() => strategy.transformToManifest(withList('is_in_list', 'blocked-ips'))).toThrow(message); + expect(() => + strategy.transformToManifest( + withList('is_not_in_list', 'blocked-ips', { + networkList: [{ name: 'other', type: 'asn', items: ['1'] }], + }), + ), + ).toThrow(message); + }); + + it('should not validate a network list referenced by id', () => { + expect(() => strategy.transformToManifest(withList('is_in_list', 10))).not.toThrow(); + }); + + it('should not validate the argument of the other operators', () => { + expect(() => + strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'host', conditional: 'if', operator: 'is_equal', argument: 'blocked-ips' }], + behaviors: [{ type: 'deny' }], + }, + ], + }), + ), + ).not.toThrow(); + }); + }); + + it('should write the function instances, with active, and validate the function', () => { + const firewall: AzionFirewallV6 = { + name: 'my-firewall', + functionsInstances: [ + { name: 'instance', ref: 'fn', args: { a: 1 } }, + { name: 'off', ref: 10 }, + ], + }; + + expect( + strategy.transformToManifest(withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }))[0] + .functions_instances, + ).toEqual([ + { name: 'instance', args: { a: 1 }, function: 'fn' }, + { name: 'off', args: {}, function: 10 }, + ]); + expect(() => strategy.transformToManifest(withFirewall(firewall))).toThrow( + 'Function instance "instance" references non-existent Function "fn".', + ); + }); + }); + + describe('transformToConfig', () => { + it('should set an empty array when the manifest has no firewall', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toEqual([]); + expect(transformedPayload.firewall).toEqual([]); + }); + + it('should round trip a firewall through the manifest', () => { + const firewall: AzionFirewallV6 = { + name: 'my-firewall', + debugRules: true, + functions: true, + networkProtection: true, + waf: true, + rules: [ + { + name: 'rule', + description: 'Block admin', + criteria: [{ variable: '${request_uri}', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [ + { type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }, + { + type: 'set_rate_limit', + attributes: { type: 'second', limitBy: 'global', averageRateLimit: 10, maximumBurstSize: 2 }, + }, + ], + }, + { + name: 'deny', + criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'deny' }], + }, + ], + functionsInstances: [{ name: 'instance', ref: 'fn', args: { a: 1 } }], + }; + const config = withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }); + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ firewall: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.firewall).toEqual([firewall]); + }); + }); + + describe('modules the rules need', () => { + const rule = (variable: string, behaviors: AzionFirewallBehaviorV6[] = [{ type: 'deny' }]) => ({ + name: 'rule', + criteria: [{ variable, conditional: 'if' as const, operator: 'matches' as const, argument: 'x' }], + behaviors, + }); + const manifest = (firewall: Partial) => + strategy.transformToManifest(withFirewall({ name: 'my-firewall', ...firewall })); + + it('should accept the default modules (functions and network protection) for the variables they cover', () => { + expect(() => manifest({ rules: [rule('request_uri')] })).not.toThrow(); + expect(() => manifest({ rules: [rule('host', [{ type: 'drop' }])] })).not.toThrow(); + }); + + it('should throw when a variable needs the waf module and it is disabled', () => { + expect(() => manifest({ rules: [rule('header_user_agent')] })).toThrow( + 'Firewall "my-firewall" rule "rule" uses the variable "header_user_agent", which needs the waf (waf) module enabled.', + ); + expect(() => manifest({ waf: true, rules: [rule('${request_method}')] })).not.toThrow(); + }); + + it('should throw when the network variable needs the network protection module', () => { + expect(() => manifest({ networkProtection: false, rules: [rule('network')] })).toThrow( + 'which needs the network_protection (networkProtection) module enabled', + ); + }); + + it('should throw when no module is enabled for a behavior', () => { + expect(() => + manifest({ functions: false, networkProtection: false, waf: false, rules: [rule('request_uri')] }), + ).toThrow( + 'uses the behavior "deny", which needs one of the waf (waf), network_protection (networkProtection), functions (functions) modules enabled.', + ); + }); + + it('should throw when run_function needs the functions module', () => { + expect(() => + manifest({ functions: false, rules: [rule('network', [{ type: 'run_function', attributes: { value: 1 } }])] }), + ).toThrow('uses the behavior "run_function", which needs the functions (functions) module enabled.'); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts new file mode 100644 index 00000000..9edcbed6 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts @@ -0,0 +1,298 @@ +import type { AzionFunction } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import { FIREWALL_BEHAVIOR_MODULES, FIREWALL_VARIABLE_MODULES } from '../../../constants'; +import type { + AzionConfigV6, + AzionFirewallBehaviorV6, + AzionFirewallRuleV6, + AzionFirewallV6, + AzionNetworkListV6, +} from '../../../types'; + +/** + * FirewallProcessConfigStrategy V6 + * @class FirewallProcessConfigStrategy + * @description Converts the v6 firewalls between the config and the manifest. + * Unlike v4, the `debugRules` of the firewall is written to the manifest. + * The behaviors and criterion variables of the rules need the modules the API documents (`FirewallBehaviorRequest` and + * `FirewallCriterionFieldRequest`): at least one of the listed modules must be enabled. + */ +class FirewallProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that referenced Function exists + */ + private validateFunctionReference( + functions: AzionFunction[] | undefined, + functionNameOrId: string | number, + instanceName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof functionNameOrId === 'string') { + if (!Array.isArray(functions) || !functions.find((func) => func.name === functionNameOrId)) { + throw new Error(`Function instance "${instanceName}" references non-existent Function "${functionNameOrId}".`); + } + } + } + + /** + * Validate that the network list referenced by is_in_list and is_not_in_list exists + */ + private validateNetworkListReference( + networkLists: AzionNetworkListV6[] | undefined, + networkListNameOrId: string | number, + ruleName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof networkListNameOrId === 'string') { + if (!Array.isArray(networkLists) || !networkLists.find((list) => list.name === networkListNameOrId)) { + throw new Error(`Firewall rule "${ruleName}" references non-existent Network List "${networkListNameOrId}".`); + } + } + } + + /** + * Validate that the modules the rules need are enabled + */ + private validateModules(fw: AzionFirewallV6, modules: Record) { + const flags: Record = { + functions: 'functions', + network_protection: 'networkProtection', + waf: 'waf', + }; + const requireOneOf = (needed: readonly string[], ruleName: string, what: string) => { + if (!needed.some((module) => modules[module]?.enabled)) { + throw new Error( + `Firewall "${fw.name}" rule "${ruleName}" uses ${what}, which needs ${ + needed.length === 1 ? 'the' : 'one of the' + } ${needed.map((module) => `${module} (${flags[module]})`).join(', ')} module${ + needed.length === 1 ? '' : 's' + } enabled.`, + ); + } + }; + + fw.rules?.forEach((rule) => { + rule.behaviors.forEach((behavior) => { + const needed = FIREWALL_BEHAVIOR_MODULES[behavior.type]; + if (needed) requireOneOf(needed, rule.name, `the behavior "${behavior.type}"`); + }); + const variables = rule.criteria ? rule.criteria.map((criterion) => criterion.variable) : [rule.variable]; + variables.forEach((variable) => { + const name = String(variable).replace(/^\$\{|\}$/g, ''); + const needed = FIREWALL_VARIABLE_MODULES[name]; + if (needed) requireOneOf(needed, rule.name, `the variable "${name}"`); + }); + }); + } + + transformToManifest(config: AzionConfigV6) { + if (!config.firewall || !Array.isArray(config.firewall)) { + return []; + } + + return config.firewall.map((fw: AzionFirewallV6) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const payload: any = { + name: fw.name, + modules: { + functions: { + enabled: fw.functions ?? true, + }, + network_protection: { + enabled: fw.networkProtection ?? true, + }, + waf: { + enabled: fw.waf ?? false, + }, + }, + debug: fw.debugRules ?? false, + }; + + this.validateModules(fw, payload.modules); + + if (fw.rules && fw.rules.length > 0) { + fw.rules.forEach((rule: AzionFirewallRuleV6) => + rule.criteria?.forEach((criterion) => { + if ( + (criterion.operator === 'is_in_list' || criterion.operator === 'is_not_in_list') && + criterion.argument !== undefined && + criterion.argument !== null + ) { + this.validateNetworkListReference(config.networkList, criterion.argument, rule.name); + } + }), + ); + + payload.rules_engine = fw.rules.map((rule: AzionFirewallRuleV6) => ({ + name: rule.name, + description: rule.description || '', + behaviors: this.transformBehaviorsToManifest(rule.behaviors), + criteria: rule.criteria + ? [ + rule.criteria.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ] + : [ + [ + { + variable: rule.variable?.startsWith('${') ? rule.variable : `\${${rule.variable}}`, + operator: 'matches', + conditional: 'if', + argument: rule.match, + }, + ], + ], + })); + } + + if (fw.functionsInstances && fw.functionsInstances.length > 0) { + payload.functions_instances = fw.functionsInstances.map((instance) => { + this.validateFunctionReference(config.functions, instance.ref, instance.name); + return { + name: instance.name, + args: instance.args || {}, + function: instance.ref, + }; + }); + } + + return payload; + }); + } + + private transformBehaviorsToManifest(behaviorArray: AzionFirewallBehaviorV6[]) { + // Runtime validation: deny, drop, and set_custom_response are terminal behaviors + // and cannot be combined with other behaviors + if (behaviorArray.length > 1) { + const firstBehavior = behaviorArray[0]; + const hasTerminalBehavior = + firstBehavior.type === 'deny' || firstBehavior.type === 'drop' || firstBehavior.type === 'set_custom_response'; + + if (hasTerminalBehavior) { + throw new Error( + `The behavior '${firstBehavior.type}' is a terminal behavior and must be used alone. ` + + `It cannot be combined with other behaviors in the same rule.`, + ); + } + } + + return behaviorArray.map((behavior) => { + switch (behavior.type) { + case 'set_waf': + return { + type: 'set_waf', + attributes: { + mode: behavior.attributes.mode, + waf_id: behavior.attributes.wafId, + }, + }; + case 'set_rate_limit': + return { + type: 'set_rate_limit', + attributes: { + ...(behavior.attributes.type && { type: behavior.attributes.type }), + limit_by: behavior.attributes.limitBy, + average_rate_limit: behavior.attributes.averageRateLimit, + ...(behavior.attributes.maximumBurstSize !== undefined && { + maximum_burst_size: behavior.attributes.maximumBurstSize, + }), + }, + }; + case 'set_custom_response': + return { + type: 'set_custom_response', + attributes: { + status_code: behavior.attributes.statusCode, + ...(behavior.attributes.contentType !== undefined && { content_type: behavior.attributes.contentType }), + ...(behavior.attributes.contentBody !== undefined && { content_body: behavior.attributes.contentBody }), + }, + }; + default: + // run_function, deny, drop and bypass keep their shape + return behavior; + } + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + if (!payload.firewall || !Array.isArray(payload.firewall)) { + transformedPayload.firewall = []; + return transformedPayload.firewall; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.firewall = payload.firewall.map((fw: any) => { + const firewallConfig: AzionFirewallV6 = { + name: fw?.name, + functions: fw?.modules?.functions?.enabled ?? false, + networkProtection: fw?.modules?.network_protection?.enabled ?? false, + waf: fw?.modules?.waf?.enabled ?? false, + debugRules: fw?.debug ?? false, + }; + + if (fw.rules_engine && fw.rules_engine.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firewallConfig.rules = fw.rules_engine.map((rule: any) => ({ + name: rule.name, + description: rule.description || undefined, + behaviors: this.transformBehaviorsToConfig(rule.behaviors), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + criteria: rule.criteria?.[0]?.map((criterion: any) => ({ ...criterion })) || [], + })); + } + + if (fw.functions_instances && fw.functions_instances.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firewallConfig.functionsInstances = fw.functions_instances.map((instance: any) => ({ + name: instance.name, + args: instance.args || {}, + ref: instance.function, + })); + } + + return firewallConfig; + }); + return transformedPayload.firewall; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private transformBehaviorsToConfig(behaviors: any[]): AzionFirewallBehaviorV6[] { + return behaviors.map((b) => { + switch (b.type) { + case 'set_waf': + return { type: 'set_waf', attributes: { mode: b.attributes.mode, wafId: b.attributes.waf_id } }; + case 'set_rate_limit': + return { + type: 'set_rate_limit', + attributes: { + type: b.attributes.type, + limitBy: b.attributes.limit_by, + averageRateLimit: b.attributes.average_rate_limit, + maximumBurstSize: b.attributes.maximum_burst_size, + }, + }; + case 'set_custom_response': + return { + type: 'set_custom_response', + attributes: { + statusCode: b.attributes.status_code, + contentType: b.attributes.content_type, + contentBody: b.attributes.content_body, + }, + }; + case 'run_function': + return { type: 'run_function', attributes: b.attributes }; + default: + // deny, drop and bypass + return { type: b.type }; + } + }); + } +} + +export default FirewallProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts new file mode 100644 index 00000000..8c76f9a4 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts @@ -0,0 +1,56 @@ +import type { AzionConfigV6 } from '../../../types'; +import NetworkListProcessConfigStrategy from './networkListProcessConfigStrategy'; + +describe('NetworkListProcessConfigStrategy (v6)', () => { + let strategy: NetworkListProcessConfigStrategy; + + beforeEach(() => { + strategy = new NetworkListProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there are no network lists', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, networkList: [] })).toBeUndefined(); + }); + + it('should map a network list to the manifest and default active to true', () => { + expect( + strategy.transformToManifest({ + version: 6, + networkList: [ + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'] }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'] }, + { name: 'blocked-asns', type: 'asn', items: ['13335'] }, + ], + }), + ).toEqual([ + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'] }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'] }, + { name: 'blocked-asns', type: 'asn', items: ['13335'] }, + ]); + }); + }); + + describe('transformToConfig', () => { + it('should not set network lists when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ network_list: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.networkList).toBeUndefined(); + }); + + it('should read the network_list key of the manifest back into the config (v4 read the wrong key)', () => { + const config: AzionConfigV6 = { + version: 6, + networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ network_list: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.networkList).toEqual(config.networkList); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts new file mode 100644 index 00000000..400cb6cd --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts @@ -0,0 +1,47 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +/** + * NetworkListProcessConfigStrategy V6 + * @class NetworkListProcessConfigStrategy + * @description Converts the v6 network lists between the config (`networkList`) and the manifest (`network_list`). + */ +class NetworkListProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config Network List to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const networkList = config?.networkList; + if (!Array.isArray(networkList) || networkList.length === 0) { + return; + } + + return networkList.map((network) => ({ + name: network.name, + type: network.type, + items: network.items, + })); + } + + /** + * Transform V6 manifest format back to azion.config Network List + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const networkList = payload?.network_list; + if (!Array.isArray(networkList) || networkList.length === 0) { + return; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.networkList = networkList.map((network: any) => ({ + name: network.name, + type: network.type, + items: network.items, + })); + + return transformedPayload.networkList; + } +} + +export default NetworkListProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts new file mode 100644 index 00000000..924fb466 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts @@ -0,0 +1,102 @@ +import type { AzionConfigV6 } from '../../../types'; +import WafProcessConfigStrategy from './wafProcessConfigStrategy'; + +describe('WafProcessConfigStrategy (v6)', () => { + let strategy: WafProcessConfigStrategy; + + beforeEach(() => { + strategy = new WafProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no waf', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, waf: [] })).toBeUndefined(); + }); + + it('should apply the defaults of the API to a waf with only the name', () => { + expect(strategy.transformToManifest({ version: 6, waf: [{ name: 'my-waf' }] })).toEqual([ + { + name: 'my-waf', + engine_settings: { + engine_version: '2021-Q3', + type: 'score', + attributes: { rulesets: [1], thresholds: [] }, + }, + }, + ]); + }); + + it('should map every field of the waf to the manifest', () => { + expect( + strategy.transformToManifest({ + version: 6, + waf: [ + { + name: 'my-waf', + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'high' }, { threat: 'file_upload' }], + }, + }, + }, + ], + }), + ).toEqual([ + { + name: 'my-waf', + engine_settings: { + engine_version: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'high' }, { threat: 'file_upload' }], + }, + }, + }, + ]); + }); + + it('should not write product_version (it is not in the v6 request)', () => { + const [waf] = strategy.transformToManifest({ version: 6, waf: [{ name: 'my-waf' }] }) ?? []; + + expect(waf).not.toHaveProperty('product_version'); + }); + }); + + describe('transformToConfig', () => { + it('should not set waf when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.waf).toBeUndefined(); + }); + + it('should round trip a waf through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + waf: [ + { + name: 'my-waf', + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'cross_site_scripting', sensitivity: 'low' }], + }, + }, + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ waf: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.waf).toEqual(config.waf); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts new file mode 100644 index 00000000..a16f9927 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts @@ -0,0 +1,68 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +/** + * WafProcessConfigStrategy V6 + * @class WafProcessConfigStrategy + * @description Converts the v6 wafs between the config and the manifest. + * The engine settings are optional: the manifest defaults them to the ones of the API (engine 2021-Q3, type score, + * ruleset 1 and no thresholds). A threshold without sensitivity is left to the API. + */ +class WafProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config WAF to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const waf = config?.waf; + if (!Array.isArray(waf) || waf.length === 0) { + return; + } + + return waf.map((wafConfig) => ({ + name: wafConfig.name, + engine_settings: { + engine_version: wafConfig.engineSettings?.engineVersion ?? '2021-Q3', + type: wafConfig.engineSettings?.type ?? 'score', + attributes: { + rulesets: wafConfig.engineSettings?.attributes?.rulesets ?? [1], + thresholds: (wafConfig.engineSettings?.attributes?.thresholds ?? []).map((threshold) => ({ + threat: threshold.threat, + ...(threshold.sensitivity && { sensitivity: threshold.sensitivity }), + })), + }, + }, + })); + } + + /** + * Transform V6 manifest format back to azion.config WAF + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const waf = payload?.waf; + if (!Array.isArray(waf) || waf.length === 0) { + return; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.waf = waf.map((wafItem: any) => ({ + name: wafItem.name, + engineSettings: wafItem.engine_settings && { + engineVersion: wafItem.engine_settings.engine_version, + type: wafItem.engine_settings.type, + attributes: wafItem.engine_settings.attributes && { + rulesets: wafItem.engine_settings.attributes.rulesets, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + thresholds: wafItem.engine_settings.attributes.thresholds?.map((threshold: any) => ({ + threat: threshold.threat, + sensitivity: threshold.sensitivity, + })), + }, + }, + })); + + return transformedPayload.waf; + } +} + +export default WafProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts new file mode 100644 index 00000000..a912f14a --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts @@ -0,0 +1,54 @@ +import type { AzionConfigV6 } from '../../types'; +import StorageProcessConfigStrategy from './storageProcessConfigStrategy'; + +describe('StorageProcessConfigStrategy (v6)', () => { + let strategy: StorageProcessConfigStrategy; + + beforeEach(() => { + strategy = new StorageProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no storage', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, storage: [] })).toBeUndefined(); + }); + + it('should default workloads_access to read_only and leave the prefix out when it is not set', () => { + expect(strategy.transformToManifest({ version: 6, storage: [{ name: 'my-bucket', dir: './dist' }] })).toEqual([ + { name: 'my-bucket', workloads_access: 'read_only', dir: './dist' }, + ]); + }); + + it('should map every field of the storage to the manifest', () => { + expect( + strategy.transformToManifest({ + version: 6, + storage: [{ name: 'my-bucket', dir: './dist', workloadsAccess: 'restricted', prefix: 'assets' }], + }), + ).toEqual([{ name: 'my-bucket', workloads_access: 'restricted', dir: './dist', prefix: 'assets' }]); + }); + }); + + describe('transformToConfig', () => { + it('should not set storage when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.storage).toBeUndefined(); + }); + + it('should map the manifest storage back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { storage: [{ name: 'my-bucket', workloads_access: 'read_write', dir: './dist', prefix: 'p' }] }, + transformedPayload, + ); + + expect(transformedPayload.storage).toEqual([ + { name: 'my-bucket', workloadsAccess: 'read_write', dir: './dist', prefix: 'p' }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts new file mode 100644 index 00000000..4ba4ffb7 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts @@ -0,0 +1,41 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * StorageProcessConfigStrategy V6 + * @class StorageProcessConfigStrategy + * @description Converts the v6 storage between the config and the manifest. + */ +class StorageProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.storage) || config?.storage.length === 0) { + return; + } + + return config.storage.map((item) => ({ + name: item.name, + workloads_access: item.workloadsAccess || 'read_only', + dir: item.dir, + ...(item.prefix !== undefined && { prefix: item.prefix }), + })); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const storageConfig = payload.storage; + if (!Array.isArray(storageConfig) || storageConfig.length === 0) { + return; + } + + transformedPayload.storage = storageConfig.map((item) => ({ + name: item.name, + workloadsAccess: item.workloads_access || 'read_only', + dir: item.dir, + prefix: item.prefix, + })); + + return transformedPayload.storage; + } +} + +export default StorageProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..3955f144 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,36 @@ +import type { AzionConfigV6 } from '../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v6)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 6 })).toBe(6); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({ version: 6 }, transformedPayload); + + expect(result).toBe(6); + expect(transformedPayload.version).toBe(6); + }); + + it('should keep the version of the config when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBe(6); + expect(transformedPayload.version).toBe(6); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..deb100d3 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,24 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + return config?.version; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts new file mode 100644 index 00000000..4a164655 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts @@ -0,0 +1,223 @@ +import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; +import WorkloadProcessConfigStrategy from './workloadProcessConfigStrategy'; + +describe('WorkloadProcessConfigStrategy (v6)', () => { + let strategy: WorkloadProcessConfigStrategy; + + const declared: AzionConfigV6 = { + version: 6, + environments: [{ name: 'production', deploymentPolicy: 'single_version' }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + }; + + beforeEach(() => { + strategy = new WorkloadProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no workloads', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, workloads: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal workload', () => { + const result = strategy.transformToManifest({ version: 6, workloads: [{ name: 'my-workload' }] }); + + expect(result).toEqual([ + { + name: 'my-workload', + infrastructure: 1, + workload_domain_allow_access: true, + tls: { minimum_version: 'tls_1_3' }, + protocols: { + http: { + versions: ['http1', 'http2', 'http3'], + http_ports: [80], + https_ports: [443], + quic_ports: [443], + }, + }, + mtls: undefined, + bindings: [], + }, + ]); + }); + + it('should not send tls.ciphers when it is not set (the v6 API does not accept null)', () => { + const [withoutCiphers] = strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] }); + const [withCiphers] = strategy.transformToManifest({ + version: 6, + workloads: [{ name: 'w', tls: { ciphers: 3, minimumVersion: 'tls_1_2' } }], + }); + + expect(withoutCiphers.tls).not.toHaveProperty('ciphers'); + expect(withCiphers.tls).toEqual({ ciphers: 3, minimum_version: 'tls_1_2' }); + }); + + it('should map every field of the workload, the mtls and the bindings to the manifest', () => { + const [workload] = strategy.transformToManifest({ + ...declared, + workloads: [ + { + name: 'my-workload', + infrastructure: 2, + workloadDomainAllowAccess: false, + protocols: { http: { versions: ['http2'], httpPorts: [8080], httpsPorts: [8443], quicPorts: [8443] } }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1] } }, + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'example.com', certificate: 7 }, { domain: 'www.example.com' }], + }, + ], + }, + ], + }); + + expect(workload).toEqual( + expect.objectContaining({ + infrastructure: 2, + workload_domain_allow_access: false, + protocols: { http: { versions: ['http2'], http_ports: [8080], https_ports: [8443], quic_ports: [8443] } }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1] } }, + }), + ); + expect(workload.bindings).toEqual([ + { + environment_name: 'production', + deployment_name: 'default-deployment', + domains: [ + { domain: 'example.com', certificate: 7 }, + { domain: 'www.example.com', certificate: null }, + ], + }, + ]); + }); + + it('should name the environment and the deployment of a binding as names, not as ids (the CLI resolves the ids)', () => { + const [workload] = strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], + }); + + expect(Object.keys(workload.bindings[0])).toEqual(['environment_name', 'deployment_name', 'domains']); + }); + + it('should throw when a binding references an environment that is not declared', () => { + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }], + }), + ).toThrow('Workload "w" binding references non-existent Environment "staging".'); + }); + + it('should throw when a binding references a deployment that is not declared', () => { + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'other' }] }], + }), + ).toThrow('Workload "w" binding references non-existent Deployment "other".'); + expect(() => + strategy.transformToManifest({ + version: 6, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'd' }] }], + }), + ).toThrow('non-existent Environment "production"'); + }); + }); + + describe('transformToConfig', () => { + it('should not set workloads when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.workloads).toBeUndefined(); + }); + + it('should map the manifest workloads and bindings back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + workloads: [ + { + name: 'my-workload', + infrastructure: 1, + workload_domain_allow_access: true, + tls: { ciphers: 3, minimum_version: 'tls_1_2' }, + protocols: { http: { versions: ['http1'], http_ports: [80], https_ports: [443], quic_ports: null } }, + bindings: [ + { + environment_name: 'production', + deployment_name: 'default-deployment', + domains: [{ domain: 'a.com', certificate: 1 }], + }, + ], + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.workloads).toEqual([ + { + name: 'my-workload', + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, + protocols: { http: { versions: ['http1'], httpPorts: [80], httpsPorts: [443], quicPorts: null } }, + mtls: undefined, + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'a.com', certificate: 1 }], + }, + ], + }, + ]); + }); + }); + + describe('workload_domain_allow_access', () => { + const config = ( + policy: 'single_version' | 'versioned_urls', + workload: Partial = {}, + ): AzionConfigV6 => ({ + version: 6, + environments: [{ name: 'production', deploymentPolicy: policy }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + workloads: [ + { name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }], ...workload }, + ], + }); + + it('should be true by default, and false by default when the workload is bound to a versioned_urls environment', () => { + expect(strategy.transformToManifest(config('single_version'))[0].workload_domain_allow_access).toBe(true); + expect(strategy.transformToManifest(config('versioned_urls'))[0].workload_domain_allow_access).toBe(false); + expect( + strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] })[0].workload_domain_allow_access, + ).toBe(true); + }); + + it('should accept an explicit value for a single_version environment, and false for a versioned_urls one', () => { + expect( + strategy.transformToManifest(config('single_version', { workloadDomainAllowAccess: false }))[0] + .workload_domain_allow_access, + ).toBe(false); + expect( + strategy.transformToManifest(config('versioned_urls', { workloadDomainAllowAccess: false }))[0] + .workload_domain_allow_access, + ).toBe(false); + }); + + it('should throw when true is set for a workload bound to a versioned_urls environment', () => { + expect(() => strategy.transformToManifest(config('versioned_urls', { workloadDomainAllowAccess: true }))).toThrow( + 'Workload "w" cannot set workloadDomainAllowAccess to true: it is bound to an environment whose deploymentPolicy is versioned_urls.', + ); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts new file mode 100644 index 00000000..5c0f092a --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts @@ -0,0 +1,142 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; + +/** + * WorkloadProcessConfigStrategy V6 + * @class WorkloadProcessConfigStrategy + * @description Converts the v6 workloads between the config and the manifest. + * A binding references an environment and a deployment by the name it has in the config. The manifest keeps that name + * in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, so it is the + * one that knows their ids and sends them to the API. + */ +class WorkloadProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that the environment and the deployment of the bindings are declared + */ + private validateBindingReferences(config: AzionConfigV6, workload: AzionWorkloadV6) { + workload.bindings?.forEach((binding) => { + if (!config.environments?.some((environment) => environment.name === binding.environment)) { + throw new Error( + `Workload "${workload.name}" binding references non-existent Environment "${binding.environment}".`, + ); + } + if (!config.deployments?.some((deployment) => deployment.name === binding.deployment)) { + throw new Error( + `Workload "${workload.name}" binding references non-existent Deployment "${binding.deployment}".`, + ); + } + }); + } + + /** + * `workload_domain_allow_access` needs the workload bound to single-version environments only: it is true by default, + * and it is false by default when a binding uses a `versioned_urls` environment. + */ + private resolveWorkloadDomainAllowAccess(config: AzionConfigV6, workload: AzionWorkloadV6) { + const versionedUrls = workload.bindings?.some( + (binding) => + config.environments?.find((environment) => environment.name === binding.environment)?.deploymentPolicy === + 'versioned_urls', + ); + + if (workload.workloadDomainAllowAccess && versionedUrls) { + throw new Error( + `Workload "${workload.name}" cannot set workloadDomainAllowAccess to true: it is bound to an environment whose deploymentPolicy is versioned_urls.`, + ); + } + + return workload.workloadDomainAllowAccess ?? !versionedUrls; + } + + transformToManifest(config: AzionConfigV6) { + const workloads = config?.workloads; + if (!workloads || workloads.length === 0) return []; + + return workloads.map((workload: AzionWorkloadV6) => { + this.validateBindingReferences(config, workload); + + return { + name: workload.name, + infrastructure: workload.infrastructure || 1, + workload_domain_allow_access: this.resolveWorkloadDomainAllowAccess(config, workload), + tls: { + ...(workload.tls?.ciphers && { ciphers: workload.tls.ciphers }), + minimum_version: workload.tls?.minimumVersion || 'tls_1_3', + }, + protocols: { + http: { + versions: workload.protocols?.http?.versions || ['http1', 'http2', 'http3'], + http_ports: workload.protocols?.http?.httpPorts || [80], + https_ports: workload.protocols?.http?.httpsPorts || [443], + quic_ports: workload.protocols?.http?.quicPorts || [443], + }, + }, + mtls: workload.mtls + ? { + enabled: workload.mtls.enabled || false, + config: { + verification: workload.mtls.config.verification || 'enforce', + certificate: workload.mtls.config.certificate, + crl: workload.mtls.config.crl, + }, + } + : undefined, + bindings: (workload.bindings ?? []).map((binding) => ({ + environment_name: binding.environment, + deployment_name: binding.deployment, + domains: (binding.domains ?? []).map((item) => ({ + domain: item.domain, + certificate: item.certificate ?? null, + })), + })), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { workloads?: any[] }, transformedPayload: AzionConfigV6) { + if (!payload.workloads || payload.workloads.length === 0) { + return; + } + + transformedPayload.workloads = payload.workloads.map((workload) => ({ + name: workload.name, + infrastructure: workload.infrastructure, + workloadDomainAllowAccess: workload.workload_domain_allow_access, + tls: { + ciphers: workload.tls?.ciphers, + minimumVersion: workload.tls?.minimum_version, + }, + protocols: { + http: { + versions: workload.protocols?.http?.versions, + httpPorts: workload.protocols?.http?.http_ports, + httpsPorts: workload.protocols?.http?.https_ports, + quicPorts: workload.protocols?.http?.quic_ports, + }, + }, + mtls: workload.mtls + ? { + enabled: workload.mtls.enabled || false, + config: { + verification: workload.mtls.config.verification || 'enforce', + certificate: workload.mtls.config.certificate, + crl: workload.mtls.config.crl, + }, + } + : undefined, + bindings: workload.bindings?.map( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (binding: any) => ({ + environment: binding.environment_name, + deployment: binding.deployment_name, + domains: binding.domains, + }), + ), + })); + + return transformedPayload.workloads; + } +} + +export default WorkloadProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts new file mode 100644 index 00000000..895580dc --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -0,0 +1,37 @@ +import ProcessConfigContext from '../../shared/processStrategy/processConfigContext'; +import type { AzionConfigV6 } from '../types'; +import ApplicationProcessConfigStrategy from './implementations/application/applicationProcessConfigStrategy'; +import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; +import ConnectorProcessConfigStrategy from './implementations/connectorProcessConfigStrategy'; +import CustomPagesProcessConfigStrategy from './implementations/customPagesProcessConfigStrategy'; +import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; +import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; +import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; +import PurgeProcessConfigStrategy from './implementations/purgeProcessConfigStrategy'; +import FirewallProcessConfigStrategy from './implementations/secure/firewallProcessConfigStrategy'; +import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; +import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; +import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; +import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; + +function factoryProcessContext() { + const processConfigContext = new ProcessConfigContext(); + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); + processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); + processConfigContext.setStrategy('functions', new FunctionsProcessConfigStrategy()); + processConfigContext.setStrategy('network_list', new NetworkListProcessConfigStrategy()); + processConfigContext.setStrategy('waf', new WafProcessConfigStrategy()); + processConfigContext.setStrategy('storage', new StorageProcessConfigStrategy()); + processConfigContext.setStrategy('firewall', new FirewallProcessConfigStrategy()); + processConfigContext.setStrategy('connectors', new ConnectorProcessConfigStrategy()); + processConfigContext.setStrategy('custom_pages', new CustomPagesProcessConfigStrategy()); + processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); + processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); + processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); + processConfigContext.setStrategy('workloads', new WorkloadProcessConfigStrategy()); + processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); + return processConfigContext; +} + +export { factoryProcessContext }; diff --git a/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts b/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts new file mode 100644 index 00000000..35de7141 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts @@ -0,0 +1,217 @@ +import { + COOKIE_BEHAVIORS, + HEADER_BEHAVIORS, + ID_BEHAVIORS, + NO_ARGS_BEHAVIORS, + STRING_BEHAVIORS, +} from '../../../constants'; + +const noArgsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: NO_ARGS_BEHAVIORS, + errorMessage: "The 'type' field must be a valid no-args behavior type.", + }, + }, + required: ['type'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in no-args behaviors.', + required: "The 'type' field is required in no-args behaviors.", + }, +}; + +const stringBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: STRING_BEHAVIORS, + errorMessage: "The 'type' field must be a valid string behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in string behavior attributes.', + required: "The 'value' field is required in string behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +// Schema para behaviors com ID value (run_function, set_cache_policy, etc.) +const idBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ID_BEHAVIORS, + errorMessage: "The 'type' field must be a valid ID behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + oneOf: [ + { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + }, + { + type: 'number', + minimum: 1, + }, + ], + errorMessage: "The 'value' field must be a string or positive number.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in ID behavior attributes.', + required: "The 'value' field is required in ID behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const headerBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: HEADER_BEHAVIORS, + errorMessage: "The 'type' field must be a valid header behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a non-empty string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in header behavior attributes.', + required: "The 'value' field is required in header behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const cookieBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: COOKIE_BEHAVIORS, + errorMessage: "The 'type' field must be a valid cookie behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a non-empty string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in cookie behavior attributes.', + required: "The 'value' field is required in cookie behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const captureGroupsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['capture_match_groups'], + errorMessage: "The 'type' field must be 'capture_match_groups'.", + }, + attributes: { + type: 'object', + properties: { + regex: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'regex' field must be a string between 1 and 255 characters.", + }, + subject: { + type: 'string', + minLength: 4, + maxLength: 50, + pattern: '.*', + errorMessage: "The 'subject' field must be a string between 4 and 50 characters.", + }, + captured_array: { + type: 'string', + minLength: 1, + maxLength: 10, + pattern: '.*', + errorMessage: "The 'captured_array' field must be a string between 1 and 10 characters.", + }, + }, + required: ['regex', 'subject', 'captured_array'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in capture groups behavior attributes.', + required: + "All fields ('regex', 'subject', 'captured_array') are required in capture groups behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const applicationRuleBehaviorSchema = { + oneOf: [ + noArgsBehaviorSchema, + stringBehaviorSchema, + idBehaviorSchema, + headerBehaviorSchema, + cookieBehaviorSchema, + captureGroupsBehaviorSchema, + ], + errorMessage: 'Each behavior must match one of the valid behavior formats.', +}; + +export default applicationRuleBehaviorSchema; diff --git a/packages/config/src/versions/v6/schemas/applications/index.ts b/packages/config/src/versions/v6/schemas/applications/index.ts new file mode 100644 index 00000000..a9e72790 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/applications/index.ts @@ -0,0 +1,463 @@ +import { + ALL_REQUEST_VARIABLES, + ALL_RESPONSE_VARIABLES, + RULE_CONDITIONALS, + RULE_OPERATORS_WITH_VALUE, + RULE_OPERATORS_WITHOUT_VALUE, + SPECIAL_VARIABLES, +} from '../../constants'; +import applicationRuleBehaviorSchema from './behaviors'; + +const createVariableValidation = (isRequestPhase = false) => ({ + type: 'string', + anyOf: [ + { + type: 'string', + pattern: + '^\\$\\{(' + [...new Set(isRequestPhase ? ALL_REQUEST_VARIABLES : ALL_RESPONSE_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + pattern: isRequestPhase + ? '^\\$\\{(arg_|cookie_|http_)[a-zA-Z0-9_]+\\}$' + : '^\\$\\{(arg_|cookie_|http_|sent_http_|upstream_cookie_|upstream_http_)[a-zA-Z0-9_]+\\}$', + }, + { + // special variables with arguments + type: 'string', + pattern: `^\\$\\{(${SPECIAL_VARIABLES.join('|')})\\([^)]+\\)\\}$`, + }, + ], + errorMessage: isRequestPhase + ? "The 'variable' field must be a valid request phase variable wrapped in ${}, follow the patterns arg_*, cookie_*, http_*, or be a special function variable cookie_time_offset(), encode_base64()" + : "The 'variable' field must be a valid response phase variable wrapped in ${}, follow the patterns arg_*, cookie_*, http_*, sent_http_*, upstream_cookie_*, upstream_http_*, or be a special function variable cookie_time_offset(), encode_base64()", +}); + +const createCriteriaBaseSchema = (isRequestPhase = false) => ({ + type: 'object', + properties: { + variable: createVariableValidation(isRequestPhase).anyOf + ? { + type: 'string', + anyOf: createVariableValidation(isRequestPhase).anyOf, + errorMessage: createVariableValidation(isRequestPhase).errorMessage, + } + : createVariableValidation(isRequestPhase), + conditional: { + type: 'string', + enum: RULE_CONDITIONALS, + errorMessage: `The 'conditional' field must be one of: ${RULE_CONDITIONALS.join(', ')}`, + }, + operator: { + type: 'string', + enum: [...RULE_OPERATORS_WITH_VALUE, ...RULE_OPERATORS_WITHOUT_VALUE], + errorMessage: `The 'operator' field must be one of: ${[...RULE_OPERATORS_WITH_VALUE, ...RULE_OPERATORS_WITHOUT_VALUE].join(', ')}`, + }, + argument: { + type: 'string', + errorMessage: "The 'argument' field must be a string", + }, + }, + required: ['variable', 'conditional', 'operator'], + allOf: [ + { + if: { + properties: { + operator: { enum: RULE_OPERATORS_WITH_VALUE }, + }, + }, + then: { + required: ['argument'], + }, + }, + { + if: { + properties: { + operator: { enum: RULE_OPERATORS_WITHOUT_VALUE }, + }, + }, + then: { + not: { + required: ['argument'], + }, + }, + }, + ], + additionalProperties: false, +}); + +const createRuleSchema = (isRequestPhase = false) => ({ + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters.", + }, + description: { + type: 'string', + maxLength: 1000, + errorMessage: "The 'description' field must be a string with maximum 1000 characters.", + }, + criteria: { + type: 'array', + items: { + type: 'array', + items: createCriteriaBaseSchema(isRequestPhase), + minItems: 1, + maxItems: 10, + errorMessage: 'Each criteria group must have between 1 and 10 criteria items.', + }, + minItems: 1, + maxItems: 5, + errorMessage: 'The criteria must be an array of arrays with 1-5 groups.', + }, + behaviors: { + type: 'array', + items: applicationRuleBehaviorSchema, + minItems: 1, + maxItems: 10, + errorMessage: 'The behaviors must be an array with 1-10 items.', + }, + }, + required: ['name', 'criteria', 'behaviors'], + additionalProperties: false, +}); + +/** + * Schema of the v6 applications. + * Based on v4, checked against the requests of the v6 API: `name` has at most 100 characters in an application + * (`ApplicationRequest`) and in a rule (`RequestPhaseRuleRequest`, `ResponsePhaseRuleRequest`). + * Cache: `maxAgeSeconds` is between 0 and 31536000 (1 year) and `tieredCache.topology` is not nullable, as in `CacheSettingRequest`. + * Device groups: same constraints as v4 (`DeviceGroupRequest`). + */ +const applicationsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: "The 'name' field must be a string with 1 to 100 characters", + }, + debug: { + type: 'boolean', + default: false, + errorMessage: "The 'debug' field must be a boolean", + }, + edgeCacheEnabled: { + type: 'boolean', + enum: [true], + default: true, + errorMessage: "The 'edgeCacheEnabled' field can only be true: the cache module cannot be disabled", + }, + functionsEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'functionsEnabled' field must be a boolean", + }, + applicationAcceleratorEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'applicationAcceleratorEnabled' field must be a boolean", + }, + imageProcessorEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'imageProcessorEnabled' field must be a boolean", + }, + cache: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The 'name' field must be a string with 1 to 250 characters", + }, + stale: { + type: 'boolean', + errorMessage: "The 'stale' field must be a boolean.", + }, + queryStringSort: { + type: 'boolean', + errorMessage: "The 'queryStringSort' field must be a boolean.", + }, + tieredCache: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean.", + }, + topology: { + type: 'string', + enum: ['nearest-region', 'us-east-1', 'br-east-1'], + default: 'nearest-region', + errorMessage: "The 'topology' field must be one of 'nearest-region', 'br-east-1' or 'us-east-1'.", + }, + }, + required: ['enabled'], + if: { + properties: { enabled: { const: true } }, + }, + then: { + required: ['enabled', 'topology'], + errorMessage: { + required: "When 'enabled' is true, 'topology' is required in the 'tiered_cache' object.", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'tiered_cache' object.", + }, + }, + methods: { + type: 'object', + properties: { + post: { + type: 'boolean', + errorMessage: "The 'post' field must be a boolean.", + }, + options: { + type: 'boolean', + errorMessage: "The 'options' field must be a boolean.", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'methods' object.", + }, + }, + browser: { + type: 'object', + properties: { + maxAgeSeconds: { + oneOf: [ + { + type: 'number', + minimum: 0, + maximum: 31536000, + errorMessage: + "The 'maxAgeSeconds' field must be a number between 0 and 31536000 or a valid mathematical expression.", + }, + { + type: 'string', + pattern: '^[0-9+*/.() -]+$', + errorMessage: "The 'maxAgeSeconds' field must be a valid mathematical expression.", + }, + ], + }, + }, + required: ['maxAgeSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'browser' object.", + required: "The 'maxAgeSeconds' field is required in the 'browser' object.", + }, + }, + edge: { + type: 'object', + properties: { + maxAgeSeconds: { + oneOf: [ + { + type: 'number', + minimum: 0, + maximum: 31536000, + errorMessage: + "The 'maxAgeSeconds' field must be a number between 0 and 31536000 or a valid mathematical expression.", + }, + { + type: 'string', + pattern: '^[0-9+*/.() -]+$', + errorMessage: "The 'maxAgeSeconds' field must be a valid mathematical expression.", + }, + ], + }, + }, + required: ['maxAgeSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'edge' object.", + required: "The 'maxAgeSeconds' field is required in the 'edge' object.", + }, + }, + cacheByCookie: { + type: 'object', + properties: { + option: { + type: 'string', + enum: ['ignore', 'all', 'allowlist', 'denylist'], + errorMessage: "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + }, + list: { + type: 'array', + items: { + type: 'string', + errorMessage: "Each item in 'list' must be a string.", + }, + errorMessage: { + type: "The 'list' field must be an array of strings.", + }, + }, + }, + required: ['option'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'cacheByCookie' object.", + required: "The 'option' field is required in the 'cacheByCookie' object.", + }, + if: { + properties: { + option: { enum: ['allowlist', 'denylist'] }, + }, + }, + then: { + required: ['list'], + errorMessage: { + required: "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + }, + }, + }, + cacheByQueryString: { + type: 'object', + properties: { + option: { + type: 'string', + enum: ['ignore', 'all', 'allowlist', 'denylist'], + errorMessage: "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + }, + list: { + type: 'array', + items: { + type: 'string', + errorMessage: "Each item in 'list' must be a string.", + }, + errorMessage: { + type: "The 'list' field must be an array of strings.", + }, + }, + }, + required: ['option'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'cacheByQueryString' object.", + required: "The 'option' field is required in the 'cacheByQueryString' object.", + }, + if: { + properties: { + option: { enum: ['allowlist', 'denylist'] }, + }, + }, + then: { + required: ['list'], + errorMessage: { + required: "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + }, + }, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in cache item objects.', + required: "The 'name' field is required in each cache item.", + }, + }, + errorMessage: "The 'cache' field must be an array of cache setting items.", + }, + rules: { + type: 'object', + properties: { + request: { + type: 'array', + items: createRuleSchema(true), + }, + response: { + type: 'array', + items: createRuleSchema(false), + }, + }, + additionalProperties: false, + }, + deviceGroups: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '^[a-zA-Z0-9]+$', + errorMessage: "The 'name' field must be a string of 1 to 250 letters and numbers", + }, + userAgent: { + type: 'string', + minLength: 1, + maxLength: 512, + pattern: '.*', + errorMessage: "The 'userAgent' field must be a valid regex pattern between 1 and 512 characters", + }, + }, + required: ['name', 'userAgent'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in device group objects', + required: "The 'name' and 'userAgent' fields are required in each device group", + }, + }, + errorMessage: "The 'deviceGroups' field must be an array of device group objects", + }, + functionsInstances: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters", + }, + ref: { + type: ['string', 'number'], + errorMessage: "The 'ref' field must be a string or number referencing an existing Function name or ID", + }, + args: { + type: 'object', + default: {}, + errorMessage: "The 'args' field must be an object", + }, + }, + required: ['name', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in function instance objects', + required: "The 'name' and 'ref' fields are required in each function instance", + }, + }, + errorMessage: "The 'functionsInstances' field must be an array of function instance objects", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in an application', + required: { name: "The 'name' field is required in an application" }, + }, + }, + errorMessage: "The 'applications' field must be an array of application items.", +}; + +export default applicationsSchema; diff --git a/packages/config/src/versions/v6/schemas/build/index.ts b/packages/config/src/versions/v6/schemas/build/index.ts new file mode 100644 index 00000000..51b2fca5 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/build/index.ts @@ -0,0 +1,3 @@ +import buildSchema from '../../../shared/schemas/build'; + +export default buildSchema; diff --git a/packages/config/src/versions/v6/schemas/connectors/index.ts b/packages/config/src/versions/v6/schemas/connectors/index.ts new file mode 100644 index 00000000..8bda230e --- /dev/null +++ b/packages/config/src/versions/v6/schemas/connectors/index.ts @@ -0,0 +1,380 @@ +import { + CONNECTOR_DNS_RESOLUTION, + CONNECTOR_HMAC_TYPE, + CONNECTOR_HTTP_VERSION_POLICY, + CONNECTOR_LIVE_INGEST_REGIONS, + CONNECTOR_LOAD_BALANCE_METHOD, + CONNECTOR_SERVER_ROLES, + CONNECTOR_TRANSPORT_POLICY, + CONNECTOR_TYPES, +} from '../../constants'; + +const storageAttributesSchema = { + type: 'object', + properties: { + bucket: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'bucket' field must be a string between 1 and 255 characters", + }, + prefix: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'prefix' field must be a string between 1 and 255 characters", + }, + }, + required: ['bucket'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in storage attributes', + required: "The 'bucket' field is required in storage attributes", + }, +}; + +const liveIngestAttributesSchema = { + type: 'object', + properties: { + region: { + type: 'string', + enum: CONNECTOR_LIVE_INGEST_REGIONS, + errorMessage: `The 'region' field must be one of: ${CONNECTOR_LIVE_INGEST_REGIONS.join(', ')}`, + }, + }, + required: ['region'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in live ingest attributes', + required: "The 'region' field is required in live ingest attributes", + }, +}; + +const httpAttributesSchema = { + type: 'object', + properties: { + addresses: { + type: 'array', + minItems: 1, + items: { + type: 'object', + properties: { + address: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'address' field must be a string between 1 and 255 characters", + }, + httpPort: { + type: 'integer', + minimum: 1, + maximum: 65535, + default: 80, + errorMessage: "The 'httpPort' must be between 1 and 65535", + }, + httpsPort: { + type: 'integer', + minimum: 1, + maximum: 65535, + default: 443, + errorMessage: "The 'httpsPort' must be between 1 and 65535", + }, + modules: { + type: 'object', + properties: { + loadBalancer: { + type: 'object', + properties: { + serverRole: { + type: 'string', + enum: CONNECTOR_SERVER_ROLES, + errorMessage: `The 'serverRole' must be one of: ${CONNECTOR_SERVER_ROLES.join(', ')}`, + }, + weight: { + type: 'integer', + minimum: 1, + maximum: 100, + default: 1, + errorMessage: "The 'weight' must be between 1 and 100", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: "The 'modules' field of an address must be an object", + }, + }, + required: ['address'], + additionalProperties: false, + }, + errorMessage: "The 'addresses' field must be an array of at least one address object", + }, + connectionOptions: { + type: 'object', + properties: { + dnsResolution: { + type: 'string', + enum: CONNECTOR_DNS_RESOLUTION, + default: 'both', + errorMessage: `The 'dnsResolution' must be one of: ${CONNECTOR_DNS_RESOLUTION.join(', ')}`, + }, + transportPolicy: { + type: 'string', + enum: CONNECTOR_TRANSPORT_POLICY, + default: 'preserve', + errorMessage: `The 'transportPolicy' must be one of: ${CONNECTOR_TRANSPORT_POLICY.join(', ')}`, + }, + httpVersionPolicy: { + type: 'string', + enum: CONNECTOR_HTTP_VERSION_POLICY, + default: 'http1_1', + errorMessage: "The 'httpVersionPolicy' must be http1_1", + }, + host: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + default: '${host}', + errorMessage: "The 'host' field must be a string between 1 and 255 characters", + }, + pathPrefix: { + type: 'string', + minLength: 0, + maxLength: 255, + pattern: '.*', + default: '', + errorMessage: "The 'pathPrefix' field must be a string between 0 and 255 characters", + }, + followingRedirect: { + type: 'boolean', + default: false, + errorMessage: "The 'followingRedirect' field must be a boolean", + }, + realIpHeader: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + default: 'X-Real-IP', + errorMessage: "The 'realIpHeader' field must be a string between 1 and 100 characters", + }, + realPortHeader: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + default: 'X-Real-PORT', + errorMessage: "The 'realPortHeader' field must be a string between 1 and 100 characters", + }, + }, + additionalProperties: false, + errorMessage: "The 'connectionOptions' field must be an object with valid connection options", + }, + modules: { + type: 'object', + properties: { + loadBalancer: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + method: { + type: 'string', + enum: CONNECTOR_LOAD_BALANCE_METHOD, + default: 'round_robin', + errorMessage: `The 'method' must be one of: ${CONNECTOR_LOAD_BALANCE_METHOD.join(', ')}`, + }, + maxRetries: { + type: 'integer', + minimum: 0, + maximum: 20, + default: 0, + errorMessage: "The 'maxRetries' must be between 0 and 20", + }, + connectionTimeout: { + type: 'integer', + minimum: 1, + maximum: 300, + default: 60, + errorMessage: "The 'connectionTimeout' must be between 1 and 300", + }, + readWriteTimeout: { + type: 'integer', + minimum: 1, + maximum: 600, + default: 120, + errorMessage: "The 'readWriteTimeout' must be between 1 and 600", + }, + }, + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + originShield: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + originIpAcl: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + }, + additionalProperties: false, + }, + hmac: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + type: { + type: 'string', + enum: CONNECTOR_HMAC_TYPE, + errorMessage: "The 'type' must be one of: aws4_hmac_sha256", + }, + attributes: { + type: 'object', + properties: { + region: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'region' field must be a string between 1 and 255 characters", + }, + service: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + default: 's3', + errorMessage: "The 'service' field must be a string between 1 and 255 characters", + }, + accessKey: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'accessKey' field must be a string between 1 and 255 characters", + }, + secretKey: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'secretKey' field must be a string between 1 and 255 characters", + }, + }, + required: ['region', 'accessKey', 'secretKey'], + additionalProperties: false, + }, + }, + required: ['attributes'], + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + }, + required: ['addresses'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in HTTP attributes', + required: "The 'addresses' field is required in HTTP attributes", + }, +}; + +/** + * Schema of the v6 connectors, from `ConnectorHTTPRequest`, `ConnectorStorageRequest` and `ConnectorLiveIngestRequest` + * of the v6 API. The attributes must match the type of the connector. + * Based on v4, checked against the v6 API: the storage prefix is optional, the HTTP attributes only require the + * addresses, an address can have load balancer modules, force_ipv6 is a DNS resolution, live ingest has a region + * and the module configs are not nullable. + */ +const connectorsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 255 characters", + }, + type: { + type: 'string', + enum: CONNECTOR_TYPES, + errorMessage: `The 'type' field must be one of: ${CONNECTOR_TYPES.join(', ')}`, + }, + attributes: { + type: 'object', + errorMessage: "The 'attributes' field must be an object", + }, + }, + required: ['name', 'type', 'attributes'], + additionalProperties: false, + allOf: [ + { + if: { properties: { type: { const: 'storage' } }, required: ['type'] }, + then: { properties: { attributes: storageAttributesSchema } }, + }, + { + if: { properties: { type: { const: 'http' } }, required: ['type'] }, + then: { properties: { attributes: httpAttributesSchema } }, + }, + { + if: { properties: { type: { const: 'live_ingest' } }, required: ['type'] }, + then: { properties: { attributes: liveIngestAttributesSchema } }, + }, + ], + errorMessage: { + additionalProperties: 'No additional properties are allowed in connector objects', + required: "The 'name', 'type' and 'attributes' fields are required in each connector", + }, + }, + errorMessage: "The 'connectors' field must be an array of connector objects", +}; + +export default connectorsSchema; diff --git a/packages/config/src/versions/v6/schemas/customPages/index.ts b/packages/config/src/versions/v6/schemas/customPages/index.ts new file mode 100644 index 00000000..a445cee9 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/customPages/index.ts @@ -0,0 +1,106 @@ +import { CUSTOM_PAGE_ERROR_CODES, CUSTOM_PAGE_TYPES } from '../../constants'; + +/** + * Schema of the v6 custom pages, based on v4 and checked against `CustomPageRequest` of the v6 API: at most 23 pages + * (one for each error code), the connector id is between 1 and 2147483647 and the `uri` has no pattern. + */ +const customPagesSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 255 characters", + }, + pages: { + type: 'array', + minItems: 1, + maxItems: 23, + items: { + type: 'object', + properties: { + code: { + type: 'string', + enum: CUSTOM_PAGE_ERROR_CODES, + errorMessage: "The 'code' field must be a valid error code", + }, + page: { + type: 'object', + properties: { + type: { + type: 'string', + enum: CUSTOM_PAGE_TYPES, + default: 'page_connector', + errorMessage: "The 'type' field must be a valid page type", + }, + attributes: { + type: 'object', + properties: { + connector: { + type: ['string', 'number'], + minimum: 1, + maximum: 2147483647, + errorMessage: + "The 'connector' field must be a string or a number between 1 and 2147483647 referencing a connector name or ID", + }, + ttl: { + type: 'integer', + minimum: 0, + maximum: 31536000, + default: 0, + errorMessage: "The 'ttl' field must be an integer between 0 and 31536000", + }, + uri: { + type: ['string', 'null'], + minLength: 1, + maxLength: 250, + errorMessage: "The 'uri' field must be a string between 1 and 250 characters or null", + }, + customStatusCode: { + type: ['integer', 'null'], + minimum: 100, + maximum: 599, + errorMessage: "The 'customStatusCode' field must be an integer between 100 and 599 or null", + }, + }, + required: ['connector'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page attributes', + required: "The 'connector' field is required in page attributes", + }, + }, + }, + required: ['attributes'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page configuration', + required: "The 'attributes' field is required in page configuration", + }, + }, + }, + required: ['code', 'page'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page entry', + required: "The 'code' and 'page' fields are required in each page entry", + }, + }, + errorMessage: "The 'pages' field must be an array of 1 to 23 page configurations", + }, + }, + required: ['name', 'pages'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in custom page objects', + required: "The 'name' and 'pages' fields are required in each custom page", + }, + }, + errorMessage: "The 'customPages' field must be an array of custom page objects", +}; + +export default customPagesSchema; diff --git a/packages/config/src/versions/v6/schemas/deployments/index.ts b/packages/config/src/versions/v6/schemas/deployments/index.ts new file mode 100644 index 00000000..555530f0 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/deployments/index.ts @@ -0,0 +1,68 @@ +import { DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES } from '../../constants'; + +/** + * Schema of the v6 deployments, from `DeploymentCreateRequest` and `DeploymentRequest` of the v6 API. + * `bindingPolicy` is required, as in the creation of a deployment. + */ +const deploymentsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 3, + maxLength: 255, + errorMessage: "The 'name' field must be a string between 3 and 255 characters", + }, + description: { + type: ['string', 'null'], + errorMessage: "The 'description' field must be a string or null", + }, + bindingPolicy: { + type: 'string', + enum: DEPLOYMENT_BINDING_POLICIES, + errorMessage: `The 'bindingPolicy' field must be one of: ${DEPLOYMENT_BINDING_POLICIES.join(', ')}`, + }, + deploymentPolicy: { + type: 'string', + enum: DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, + }, + strategyDefaults: { + type: 'object', + properties: { + skewProtection: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + defaultTtlSeconds: { type: 'integer', minimum: 1, maximum: 2147483647 }, + }, + required: ['enabled', 'defaultTtlSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in skewProtection', + required: "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + }, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in strategyDefaults', + }, + }, + }, + required: ['name', 'bindingPolicy'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in deployment objects', + required: { + name: "The 'name' field is required in each deployment", + bindingPolicy: "The 'bindingPolicy' field is required in each deployment", + }, + }, + }, + errorMessage: "The 'deployments' field must be an array of deployment objects", +}; + +export default deploymentsSchema; diff --git a/packages/config/src/versions/v6/schemas/environments/index.ts b/packages/config/src/versions/v6/schemas/environments/index.ts new file mode 100644 index 00000000..68225144 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/environments/index.ts @@ -0,0 +1,117 @@ +import { + ENVIRONMENT_DEPLOYMENT_POLICIES, + ENVIRONMENT_BRANCH_TRACKING_MODES, + ENVIRONMENT_LOG_VERBOSITY, + ENVIRONMENT_ROBOTS_POLICIES, +} from '../../constants'; + +/** + * Schema of the v6 environments, from `EnvironmentCreateRequest` and `EnvironmentRequest` of the v6 API. + * `deploymentPolicy` is required, as in the creation of an environment, and the API does not accept changing it later. + */ +const environmentsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 3, + maxLength: 255, + errorMessage: "The 'name' field must be a string between 3 and 255 characters", + }, + description: { + type: ['string', 'null'], + errorMessage: "The 'description' field must be a string or null", + }, + logVerbosity: { + type: 'string', + enum: ENVIRONMENT_LOG_VERBOSITY, + errorMessage: `The 'logVerbosity' field must be one of: ${ENVIRONMENT_LOG_VERBOSITY.join(', ')}`, + }, + robotsPolicy: { + type: 'string', + enum: ENVIRONMENT_ROBOTS_POLICIES, + errorMessage: `The 'robotsPolicy' field must be one of: ${ENVIRONMENT_ROBOTS_POLICIES.join(', ')}`, + }, + protection: { + type: 'object', + properties: { + azionAuthentication: { + type: 'object', + properties: { enabled: { type: 'boolean' } }, + required: ['enabled'], + additionalProperties: false, + }, + passwordProtection: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + secretId: { type: ['string', 'null'], minLength: 1 }, + }, + required: ['enabled', 'secretId'], + additionalProperties: false, + }, + ipAllowlist: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + cidrs: { type: 'array', items: { type: 'string', minLength: 2, maxLength: 49 } }, + }, + required: ['enabled', 'cidrs'], + additionalProperties: false, + }, + ssoEnforcement: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + idpId: { type: ['string', 'null'], minLength: 1 }, + allowedDomains: { type: 'array', items: { type: 'string', minLength: 1 } }, + }, + required: ['enabled', 'idpId', 'allowedDomains'], + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the environment protection', + }, + }, + branchTracking: { + type: ['object', 'null'], + properties: { + enabled: { type: 'boolean' }, + mode: { + type: 'string', + enum: ENVIRONMENT_BRANCH_TRACKING_MODES, + errorMessage: `The 'mode' field must be one of: ${ENVIRONMENT_BRANCH_TRACKING_MODES.join(', ')}`, + }, + branchMatch: { type: 'string', minLength: 1, maxLength: 255 }, + }, + required: ['enabled', 'mode', 'branchMatch'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in branchTracking', + required: "The 'enabled', 'mode' and 'branchMatch' fields are required in branchTracking", + }, + }, + deploymentPolicy: { + type: 'string', + enum: ENVIRONMENT_DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${ENVIRONMENT_DEPLOYMENT_POLICIES.join(', ')}`, + }, + }, + required: ['name', 'deploymentPolicy'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in environment objects', + required: { + name: "The 'name' field is required in each environment", + deploymentPolicy: "The 'deploymentPolicy' field is required in each environment", + }, + }, + }, + errorMessage: "The 'environments' field must be an array of environment objects", +}; + +export default environmentsSchema; diff --git a/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts b/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts new file mode 100644 index 00000000..eba35989 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts @@ -0,0 +1,208 @@ +import { + FIREWALL_NO_ARGS_BEHAVIORS, + FIREWALL_RATE_LIMIT_BY, + FIREWALL_RATE_LIMIT_TYPES, + FIREWALL_WAF_MODES, +} from '../../../constants'; + +const setRateLimitBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_rate_limit'], + errorMessage: "The 'type' field must be a valid set_rate_limit behavior type.", + }, + attributes: { + type: 'object', + properties: { + type: { + type: 'string', + enum: FIREWALL_RATE_LIMIT_TYPES, + default: 'second', + errorMessage: `The rate limit type must be one of: ${FIREWALL_RATE_LIMIT_TYPES.join(', ')}`, + }, + limitBy: { + type: 'string', + enum: FIREWALL_RATE_LIMIT_BY, + errorMessage: `The rate limit must be applied by one of: ${FIREWALL_RATE_LIMIT_BY.join(', ')}`, + }, + averageRateLimit: { + type: 'integer', + minimum: 1, + maximum: 2147483647, + errorMessage: 'The averageRateLimit must be an integer between 1 and 2147483647', + }, + maximumBurstSize: { + type: ['integer', 'null'], + minimum: 1, + maximum: 2147483647, + errorMessage: 'The maximumBurstSize must be an integer between 1 and 2147483647 or null', + }, + }, + required: ['limitBy', 'averageRateLimit'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in set_rate_limit behavior attributes.', + required: "The 'limitBy' and 'averageRateLimit' fields are required in set_rate_limit behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const setWafRuleSetBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_waf'], + errorMessage: "The 'type' field must be a valid set_waf behavior type.", + }, + attributes: { + type: 'object', + properties: { + mode: { + type: 'string', + enum: FIREWALL_WAF_MODES, + errorMessage: `The mode must be one of: ${FIREWALL_WAF_MODES.join(', ')}`, + }, + wafId: { + type: ['string', 'number'], + errorMessage: 'The wafId must be a string or number', + }, + }, + required: ['mode', 'wafId'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the set_waf object', + required: "Both 'mode' and 'wafId' fields are required in set_waf attributes", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const setCustomResponseBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_custom_response'], + errorMessage: "The 'type' field must be a valid set_custom_response behavior type.", + }, + attributes: { + type: 'object', + properties: { + statusCode: { + type: 'integer', + minimum: 200, + maximum: 499, + errorMessage: 'The statusCode must be an integer between 200 and 499', + }, + contentType: { + type: 'string', + maxLength: 255, + errorMessage: 'The contentType must be a string of at most 255 characters', + }, + contentBody: { + type: 'string', + maxLength: 500, + errorMessage: 'The contentBody must be a string of at most 500 characters', + }, + }, + required: ['statusCode'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the setCustomResponse object', + required: "The 'statusCode' field is required in setCustomResponse", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const noArgsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: FIREWALL_NO_ARGS_BEHAVIORS, + errorMessage: "The 'type' field must be a valid firewall no-args behavior type.", + }, + }, + required: ['type'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in firewall no-args behaviors.', + required: "The 'type' field is required in firewall no-args behaviors.", + }, +}; + +const runFunctionBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['run_function'], + errorMessage: "The 'type' field must be 'run_function' for this behavior.", + }, + attributes: { + type: 'object', + properties: { + value: { + oneOf: [ + { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a string between 1 and 255 characters.", + }, + { + type: 'number', + minimum: 1, + errorMessage: "The 'value' field must be a positive number.", + }, + ], + errorMessage: "The 'value' field must be a string or positive number.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in run_function behavior attributes.', + required: "The 'value' field is required in run_function behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +/** + * Behaviors of a firewall rule, from `FirewallBehaviorRequest` of the v6 API: `bypass` is a behavior without + * arguments, the mode of `set_waf` is logging or blocking, and the rate limit and the status code are integers. + */ +const firewallBehaviorSchema = { + if: { type: 'object', properties: { type: { const: 'run_function' } }, required: ['type'] }, + then: runFunctionBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_waf' } }, required: ['type'] }, + then: setWafRuleSetBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_rate_limit' } }, required: ['type'] }, + then: setRateLimitBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_custom_response' } }, required: ['type'] }, + then: setCustomResponseBehaviorSchema, + else: noArgsBehaviorSchema, + }, + }, + }, +}; + +export default firewallBehaviorSchema; diff --git a/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts new file mode 100644 index 00000000..ba817d4e --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts @@ -0,0 +1,30 @@ +/** + * Schema of the function instances of a v6 firewall, from `FirewallFunctionInstanceRequest` of the v6 API. + */ +const firewallFunctionsInstances = { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: 'The name must be a string between 1 and 100 characters long', + }, + args: { + type: 'object', + default: {}, + errorMessage: "The 'args' field must be an object", + }, + ref: { + type: ['string', 'number'], + errorMessage: "The 'ref' field must be a string or number referencing an existing Function name or ID", + }, + }, + required: ['name', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the firewallFunctionsInstance object', + }, +}; + +export default firewallFunctionsInstances; diff --git a/packages/config/src/versions/v6/schemas/firewall/index.ts b/packages/config/src/versions/v6/schemas/firewall/index.ts new file mode 100644 index 00000000..2ae95f90 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/index.ts @@ -0,0 +1,175 @@ +import { FIREWALL_RULE_CONDITIONAL, FIREWALL_RULE_OPERATORS, FIREWALL_VARIABLES } from '../../constants'; +import firewallBehaviorSchema from './behaviors'; +import firewallFunctionsInstances from './functionsInstances'; + +/** + * Schema of the v6 firewalls, based on v4 and checked against `FirewallRequest` and `FirewallRuleRequest` of the v6 API. + */ +const firewall = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The firewall configuration must have a 'name' field of type string (1-250 characters)", + }, + debugRules: { + type: 'boolean', + errorMessage: "The firewall's 'debugRules' field must be a boolean", + }, + functions: { + type: 'boolean', + errorMessage: "The firewall's 'functions' field must be a boolean", + }, + networkProtection: { + type: 'boolean', + errorMessage: "The firewall's 'networkProtection' field must be a boolean", + }, + waf: { + type: 'boolean', + errorMessage: "The firewall's 'waf' field must be a boolean", + }, + rules: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: "Each firewall rule must have a 'name' field of type string (1-100 characters)", + }, + description: { + type: 'string', + maxLength: 1000, + errorMessage: "The rule's 'description' field must be a string of at most 1000 characters", + }, + match: { + type: 'string', + errorMessage: "The rule's 'match' field must be a string containing a valid regex pattern", + }, + variable: { + anyOf: [ + { + type: 'string', + pattern: '^\\$\\{(' + [...new Set(FIREWALL_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + enum: [...FIREWALL_VARIABLES], + errorMessage: "The 'variable' field must be a valid firewall variable", + }, + ], + errorMessage: "The 'variable' field must be a valid variable (with or without ${})", + }, + behaviors: { + type: 'array', + items: firewallBehaviorSchema, + minItems: 1, + maxItems: 10, + errorMessage: 'The behaviors must be an array with 1-10 items.', + }, + criteria: { + type: 'array', + minItems: 1, + maxItems: 10, + items: { + type: 'object', + properties: { + conditional: { + type: 'string', + enum: FIREWALL_RULE_CONDITIONAL, + errorMessage: `The 'conditional' field must be one of: ${FIREWALL_RULE_CONDITIONAL.join(', ')}`, + }, + variable: { + anyOf: [ + { + type: 'string', + pattern: '^\\$\\{(' + [...new Set(FIREWALL_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + enum: [...FIREWALL_VARIABLES], + errorMessage: "The 'variable' field must be a valid firewall variable", + }, + ], + errorMessage: "The 'variable' field must be a valid variable (with or without ${})", + }, + operator: { + type: 'string', + enum: FIREWALL_RULE_OPERATORS, + errorMessage: `The 'operator' field must be one of: ${FIREWALL_RULE_OPERATORS.join(', ')}`, + }, + argument: { + type: ['string', 'number', 'null'], + errorMessage: 'The argument must be a string, a number or null', + }, + }, + required: ['conditional', 'variable', 'operator'], + additionalProperties: false, + // only `exists` and `does_not_exist` do not compare with a value + if: { properties: { operator: { enum: ['exists', 'does_not_exist'] } }, required: ['operator'] }, + else: { + required: ['argument'], + properties: { argument: { type: ['string', 'number'] } }, + errorMessage: { + required: "The 'argument' field is required unless the operator is 'exists' or 'does_not_exist'", + properties: { argument: 'The argument must be a string or a number for this operator' }, + }, + }, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the criteria object', + required: "The 'variable', 'operator' and 'conditional' fields are required in each criteria object", + }, + }, + errorMessage: { + type: 'The criteria field must be an array with at least one criteria item', + }, + }, + }, + required: ['name', 'behaviors'], + oneOf: [ + { + required: ['match', 'variable'], + not: { required: ['criteria'] }, + errorMessage: + "When using 'match' or 'variable', both fields are required and cannot be used with 'criteria'.", + }, + { + required: ['criteria'], + not: { + anyOf: [{ required: ['match'] }, { required: ['variable'] }], + }, + errorMessage: "Cannot use 'criteria' together with 'match' or 'variable'.", + }, + ], + errorMessage: { + oneOf: "You must use either 'match' AND 'variable' together OR 'criteria', but not both at the same time", + }, + }, + }, + functionsInstances: { + type: 'array', + items: firewallFunctionsInstances, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + type: 'Each firewall item must be an object', + additionalProperties: 'No additional properties are allowed in the firewall object', + required: "The 'name' field is required in each firewall object", + }, + }, + errorMessage: { + type: "The 'firewall' field must be an array of firewall objects", + }, +}; + +export default firewall; diff --git a/packages/config/src/versions/v6/schemas/functions/index.ts b/packages/config/src/versions/v6/schemas/functions/index.ts new file mode 100644 index 00000000..61b0fe28 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/functions/index.ts @@ -0,0 +1,104 @@ +import { FUNCTION_DEPENDENCY_TYPES } from '../../constants'; + +const functionsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 250 characters", + }, + path: { + type: 'string', + errorMessage: "The 'path' field must be a string", + }, + runtime: { + type: 'string', + enum: ['azion_js'], + default: 'azion_js', + errorMessage: "The 'runtime' field must be 'azion_js'", + }, + defaultArgs: { + type: 'object', + default: {}, + errorMessage: "The 'defaultArgs' field must be an object", + }, + executionEnvironment: { + type: 'string', + enum: ['application', 'firewall'], + default: 'application', + errorMessage: "The 'executionEnvironment' field must be 'application' or 'firewall'", + }, + dependencies: { + type: 'array', + maxItems: 20, + items: { + type: 'object', + properties: { + type: { + type: 'string', + enum: FUNCTION_DEPENDENCY_TYPES, + errorMessage: `The 'type' field must be one of: ${FUNCTION_DEPENDENCY_TYPES.join(', ')}`, + }, + ref: { + type: ['string', 'integer'], + minimum: 1, + minLength: 1, + errorMessage: + "The 'ref' field must be the name of a connector or network list declared in the config, or its ID", + }, + }, + required: ['type', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in function dependencies', + required: "The 'type' and 'ref' fields are required in each function dependency", + }, + }, + errorMessage: { + maxItems: "The 'dependencies' field can have at most 20 items", + type: "The 'dependencies' field must be an array of dependency objects", + }, + }, + bindings: { + type: 'object', + properties: { + storage: { + type: 'object', + properties: { + bucket: { + type: ['string', 'number'], + errorMessage: "The 'bucket' field must be a string or number", + }, + prefix: { + type: 'string', + errorMessage: "The 'prefix' field must be a string", + }, + }, + required: ['bucket', 'prefix'], + additionalProperties: false, + errorMessage: { + type: "The 'storage' field must be an object", + additionalProperties: 'No additional properties are allowed in the storage object binding.', + required: "The 'bucket' and 'prefix' fields are required in the storage object binding.", + }, + }, + }, + additionalProperties: false, + errorMessage: { + type: "The 'bindings' field must be an object", + additionalProperties: 'No additional properties are allowed in the bindings object', + }, + }, + }, + required: ['name', 'path'], + additionalProperties: false, + }, + errorMessage: "The 'functions' field must be an array of function objects with at least one item", +}; + +export default functionsSchema; diff --git a/packages/config/src/versions/v6/schemas/networkList/index.ts b/packages/config/src/versions/v6/schemas/networkList/index.ts new file mode 100644 index 00000000..ea75088c --- /dev/null +++ b/packages/config/src/versions/v6/schemas/networkList/index.ts @@ -0,0 +1,82 @@ +import { NETWORK_LIST_TYPES } from '../../constants'; + +/** + * Schema of the v6 network lists, from `NetworkListRequest` of the v6 API: each item has 1 to 250 characters. + * The items follow the formats the API documents for the types `asn` (digits only) and `countries` (two uppercase + * alphanumeric characters, ISO 3166-1 alpha-2). The items of `ip_cidr` can be an IP with or without CIDR and with or + * without an expiration date, so they are not checked. + */ +const networkListSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 250 characters.", + }, + type: { + type: 'string', + enum: NETWORK_LIST_TYPES, + errorMessage: "The 'type' field must be a string. Accepted values are 'ip_cidr', 'asn' or 'countries'.", + }, + items: { + type: 'array', + minItems: 1, + maxItems: 20000, + items: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "Each item in 'items' must be a string between 1 and 250 characters.", + }, + errorMessage: "The 'items' field must be an array of strings with 1-20000 items.", + }, + }, + required: ['name', 'type', 'items'], + additionalProperties: false, + allOf: [ + { + if: { properties: { type: { const: 'asn' } }, required: ['type'] }, + then: { + properties: { + items: { + type: 'array', + items: { + type: 'string', + pattern: '^[0-9]+$', + errorMessage: 'Each ASN item must be a number composed of digits only.', + }, + }, + }, + }, + }, + { + if: { properties: { type: { const: 'countries' } }, required: ['type'] }, + then: { + properties: { + items: { + type: 'array', + items: { + type: 'string', + pattern: '^[A-Z0-9]{2}$', + errorMessage: + 'Each country item must be a two-character uppercase alphanumeric code (ISO 3166-1 alpha-2).', + }, + }, + }, + }, + }, + ], + errorMessage: { + additionalProperties: 'No additional properties are allowed in network list items.', + required: "The 'name', 'type' and 'items' fields are required in each network list item.", + }, + }, +}; + +export default networkListSchema; diff --git a/packages/config/src/versions/v6/schemas/purge/index.ts b/packages/config/src/versions/v6/schemas/purge/index.ts new file mode 100644 index 00000000..889777ee --- /dev/null +++ b/packages/config/src/versions/v6/schemas/purge/index.ts @@ -0,0 +1,49 @@ +/** + * Schema of the v6 purge. + * Based on v4, checked against `PurgeRequest` (`POST /workspace/purge/{purge_type}`): each item has at least 1 character + * and `layer` is `cache`. The `uri` format of the items is not enforced here: a `cachekey` item is not a URI, + * and the strategy already checks the protocol of a `url` and the asterisk of a `wildcard`. + */ +const purgeSchema = { + type: 'array', + items: { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['url', 'cachekey', 'wildcard'], + errorMessage: "The 'type' field must be either 'url', 'cachekey' or 'wildcard'.", + }, + items: { + type: 'array', + minItems: 1, + items: { + type: 'string', + minLength: 1, + errorMessage: { + type: "Each item in 'items' must be a string.", + minLength: "Each item in 'items' must have at least 1 character.", + }, + }, + errorMessage: { + type: "The 'items' field must be an array of strings.", + minItems: 'The purge items array cannot be empty. At least one item must be specified.', + }, + }, + layer: { + type: 'string', + enum: ['cache'], + errorMessage: "The 'layer' field must be 'cache'.", + }, + }, + required: ['type', 'items'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in purge items.', + required: "The 'type and items' fields are required in each purge item.", + }, + }, + errorMessage: "The 'purge' field must be an array of purge items.", +}; + +export default purgeSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts new file mode 100644 index 00000000..3138a26f --- /dev/null +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -0,0 +1,50 @@ +import applicationsSchema from './applications'; +import buildSchema from './build'; +import connectorsSchema from './connectors'; +import customPagesSchema from './customPages'; +import deploymentsSchema from './deployments'; +import environmentsSchema from './environments'; +import firewallSchema from './firewall'; +import functionsSchema from './functions'; +import networkListSchema from './networkList'; +import purgeSchema from './purge'; +import storageSchema from './storage'; +import wafSchema from './waf'; +import workloadsSchema from './workloads'; + +/** + * JSON Schema of the v6 config. + */ +const azionConfigSchema = { + $id: 'azionConfig', + definitions: { + mainConfig: { + type: 'object', + properties: { + version: { type: 'number', enum: [6] }, + build: buildSchema, + functions: functionsSchema, + storage: storageSchema, + connectors: connectorsSchema, + customPages: customPagesSchema, + networkList: networkListSchema, + waf: wafSchema, + firewall: firewallSchema, + applications: applicationsSchema, + workloads: workloadsSchema, + environments: environmentsSchema, + deployments: deploymentsSchema, + purge: purgeSchema, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', + type: 'Configuration must be an object', + }, + }, + }, + $ref: '#/definitions/mainConfig', +}; + +export default azionConfigSchema; diff --git a/packages/config/src/versions/v6/schemas/schemaManifest.ts b/packages/config/src/versions/v6/schemas/schemaManifest.ts new file mode 100644 index 00000000..97f13c4b --- /dev/null +++ b/packages/config/src/versions/v6/schemas/schemaManifest.ts @@ -0,0 +1,10 @@ +/** + * JSON Schema of the v6 manifest. + * TODO: placeholder. Accepts any object until the v6 manifest is defined. + */ +const schemaManifest = { + $id: 'azionManifest', + type: 'object', +}; + +export { schemaManifest }; diff --git a/packages/config/src/versions/v6/schemas/storage/index.ts b/packages/config/src/versions/v6/schemas/storage/index.ts new file mode 100644 index 00000000..8baa308c --- /dev/null +++ b/packages/config/src/versions/v6/schemas/storage/index.ts @@ -0,0 +1,45 @@ +import { WORKLOADS_ACCESS_TYPES } from '../../constants'; + +/** + * Schema of the v6 storage, from `BucketCreateRequest` of the v6 API: the name has 6 to 63 lowercase letters, digits + * and hyphens, and does not start nor end with a hyphen. A `$PLACEHOLDER` is also accepted, as the presets use them + * and the Azion CLI replaces them. + */ +const storageSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 6, + maxLength: 63, + pattern: '^(\\$[A-Z][A-Z0-9_]*|[a-z0-9][a-z0-9-]*[a-z0-9])$', + errorMessage: + "The 'name' field must be a string between 6 and 63 characters, with lowercase letters, digits and hyphens, and must not start or end with a hyphen.", + }, + dir: { + type: 'string', + errorMessage: "The 'dir' field must be a string.", + }, + workloadsAccess: { + type: 'string', + enum: WORKLOADS_ACCESS_TYPES, + errorMessage: "The 'workloadsAccess' field must be one of: read_only, read_write, restricted.", + }, + prefix: { + type: 'string', + errorMessage: "The 'prefix' field must be a string.", + }, + }, + required: ['name', 'dir'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in storage items.', + required: "The 'name' and 'dir' fields are required.", + }, + }, + errorMessage: "The 'storage' field must be an array of storage items.", +}; + +export default storageSchema; diff --git a/packages/config/src/versions/v6/schemas/waf/index.ts b/packages/config/src/versions/v6/schemas/waf/index.ts new file mode 100644 index 00000000..4d91da9e --- /dev/null +++ b/packages/config/src/versions/v6/schemas/waf/index.ts @@ -0,0 +1,105 @@ +import { + WAF_ENGINE_TYPES, + WAF_ENGINE_VERSIONS, + WAF_RULESETS, + WAF_SENSITIVITY, + WAF_THREAT_TYPES, +} from '../../constants'; + +/** + * Schema of the v6 wafs, from `WAFRequest` of the v6 API. The request has no `id` nor `productVersion`, only the name + * is required, and a threshold only requires the threat. + */ +const wafSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The WAF configuration must have a 'name' field of type string (1-250 characters)", + }, + engineSettings: { + type: 'object', + properties: { + engineVersion: { + type: 'string', + enum: WAF_ENGINE_VERSIONS, + default: '2021-Q3', + errorMessage: "The 'engineVersion' field must be '2021-Q3'", + }, + type: { + type: 'string', + enum: WAF_ENGINE_TYPES, + default: 'score', + errorMessage: "The 'type' field must be 'score'", + }, + attributes: { + type: 'object', + properties: { + rulesets: { + type: 'array', + items: { + type: 'integer', + enum: WAF_RULESETS, + errorMessage: "The 'rulesets' field must be an array containing [1]", + }, + default: [1], + errorMessage: "The 'rulesets' field must be an array containing [1]", + }, + thresholds: { + type: 'array', + items: { + type: 'object', + properties: { + threat: { + type: 'string', + enum: WAF_THREAT_TYPES, + errorMessage: `The 'threat' field must be one of: ${WAF_THREAT_TYPES.join(', ')}`, + }, + sensitivity: { + type: 'string', + enum: WAF_SENSITIVITY, + errorMessage: `The 'sensitivity' field must be one of: ${WAF_SENSITIVITY.join(', ')}`, + }, + }, + required: ['threat'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in a threshold', + required: "The 'threat' field is required in each threshold", + }, + }, + maxItems: 8, + errorMessage: "The 'thresholds' field must be an array of threat configurations (max 8 items)", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the attributes object', + }, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the engineSettings object', + }, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + type: "The 'waf' field must be an object", + additionalProperties: 'No additional properties are allowed in the WAF object', + required: "The 'name' field is required in the WAF object", + }, + }, + errorMessage: { + type: "The 'waf' field must be an array", + }, +}; + +export default wafSchema; diff --git a/packages/config/src/versions/v6/schemas/workloads/index.ts b/packages/config/src/versions/v6/schemas/workloads/index.ts new file mode 100644 index 00000000..39d3ca4d --- /dev/null +++ b/packages/config/src/versions/v6/schemas/workloads/index.ts @@ -0,0 +1,204 @@ +import { + WORKLOAD_HTTP_VERSIONS, + WORKLOAD_INFRASTRUCTURE, + WORKLOAD_MTLS_VERIFICATION, + WORKLOAD_TLS_CIPHERS, + WORKLOAD_TLS_VERSIONS, +} from '../../constants'; + +/** + * Schema of the v6 workloads. + * Based on v4, checked against `WorkloadRequest` of the v6 API: the domains and the certificate moved to the + * `bindings`, `tls.ciphers` is not nullable and the ports and versions of the http protocol have limits. + */ +const workloadsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters", + }, + infrastructure: { + type: 'integer', + enum: WORKLOAD_INFRASTRUCTURE, + default: 1, + errorMessage: "The 'infrastructure' must be either 1 or 2", + }, + workloadDomainAllowAccess: { + type: 'boolean', + default: true, + errorMessage: "The 'workloadDomainAllowAccess' field must be a boolean", + }, + tls: { + type: 'object', + properties: { + ciphers: { + type: 'integer', + enum: WORKLOAD_TLS_CIPHERS, + errorMessage: "The 'ciphers' must be an integer between 1-8", + }, + minimumVersion: { + type: ['string', 'null'], + enum: [...WORKLOAD_TLS_VERSIONS, null], + default: 'tls_1_3', + errorMessage: "The 'minimumVersion' must be a valid TLS version or null", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: + 'No additional properties are allowed in tls. The certificate is set per domain in the bindings', + }, + }, + protocols: { + type: 'object', + properties: { + http: { + type: 'object', + properties: { + versions: { + type: 'array', + items: { + type: 'string', + enum: WORKLOAD_HTTP_VERSIONS, + }, + maxItems: 3, + // the API requires http1 and http2 + allOf: [{ contains: { const: 'http1' } }, { contains: { const: 'http2' } }], + default: ['http1', 'http2', 'http3'], + errorMessage: { + allOf: "The 'versions' field must include http1 and http2", + }, + }, + httpPorts: { + type: 'array', + items: { type: 'integer' }, + minItems: 1, + maxItems: 4, + default: [80], + }, + httpsPorts: { + type: 'array', + items: { type: 'integer' }, + minItems: 1, + maxItems: 12, + default: [443], + }, + quicPorts: { + type: ['array', 'null'], + items: { type: 'integer' }, + maxItems: 12, + }, + }, + required: ['versions', 'httpPorts', 'httpsPorts'], + additionalProperties: false, + }, + }, + default: { + http: { + versions: ['http1', 'http2', 'http3'], + httpPorts: [80], + httpsPorts: [443], + quicPorts: [443], + }, + }, + additionalProperties: false, + }, + mtls: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + }, + config: { + type: 'object', + properties: { + verification: { + type: 'string', + enum: WORKLOAD_MTLS_VERIFICATION, + default: 'enforce', + }, + certificate: { + type: ['integer', 'null'], + minimum: 1, + }, + crl: { + type: ['array', 'null'], + items: { type: 'integer' }, + maxItems: 100, + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + bindings: { + type: 'array', + items: { + type: 'object', + properties: { + environment: { + type: 'string', + minLength: 1, + errorMessage: "The 'environment' field must be the name of an environment declared in 'environments'", + }, + deployment: { + type: 'string', + minLength: 1, + errorMessage: "The 'deployment' field must be the name of a deployment declared in 'deployments'", + }, + domains: { + type: 'array', + items: { + type: 'object', + properties: { + domain: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The 'domain' field must be a string between 1 and 250 characters", + }, + certificate: { + type: ['integer', 'null'], + minimum: 1, + errorMessage: "The 'certificate' must be an integer >= 1 or null", + }, + }, + required: ['domain'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in binding domains', + required: { domain: "The 'domain' field is required in each binding domain" }, + }, + }, + errorMessage: "The 'domains' field must be an array of domain objects", + }, + }, + required: ['environment', 'deployment'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in binding objects', + required: "The 'environment' and 'deployment' fields are required in each binding", + }, + }, + errorMessage: "The 'bindings' field must be an array of binding objects", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in workload items', + required: { name: "The 'name' field is required in workloads" }, + }, + }, + errorMessage: "The 'workloads' field must be an array of workload items.", +}; + +export default workloadsSchema; diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts new file mode 100644 index 00000000..3ed84741 --- /dev/null +++ b/packages/config/src/versions/v6/types.ts @@ -0,0 +1,460 @@ +import type { + AzionBuild, + AzionCache, + AzionFunction, + AzionFunctionInstance, + AzionRule, + AzionWorkloadMTLS, + AzionWorkloadProtocols, + WorkloadInfrastructure, + WorkloadTLSCipher, + WorkloadTLSVersion, +} from '../../types'; +import type { + CONNECTOR_DNS_RESOLUTION, + CONNECTOR_HMAC_TYPE, + CONNECTOR_HTTP_VERSION_POLICY, + CONNECTOR_LIVE_INGEST_REGIONS, + CONNECTOR_LOAD_BALANCE_METHOD, + CONNECTOR_SERVER_ROLES, + CONNECTOR_TRANSPORT_POLICY, + CUSTOM_PAGE_ERROR_CODES, + CUSTOM_PAGE_TYPES, + DEPLOYMENT_BINDING_POLICIES, + DEPLOYMENT_POLICIES, + ENVIRONMENT_DEPLOYMENT_POLICIES, + ENVIRONMENT_BRANCH_TRACKING_MODES, + ENVIRONMENT_LOG_VERBOSITY, + ENVIRONMENT_ROBOTS_POLICIES, + FIREWALL_NO_ARGS_BEHAVIORS, + FIREWALL_RATE_LIMIT_BY, + FIREWALL_RATE_LIMIT_TYPES, + FIREWALL_RULE_CONDITIONAL, + FIREWALL_RULE_OPERATORS, + FIREWALL_WAF_MODES, + FUNCTION_DEPENDENCY_TYPES, + NETWORK_LIST_TYPES, + WAF_ENGINE_TYPES, + WAF_ENGINE_VERSIONS, + WAF_RULESETS, + WAF_SENSITIVITY, + WAF_THREAT_TYPES, + WORKLOADS_ACCESS_TYPES, +} from './constants'; + +/** + * Resource a function uses at runtime, which a release includes with the function. + */ +export type AzionFunctionDependencyV6 = { + type: (typeof FUNCTION_DEPENDENCY_TYPES)[number]; + /** Name of a connector or network list declared in the config, or its ID */ + ref: string | number; +}; + +/** + * Function of the Azion API v6 (it has no `active`). + */ +export type AzionFunctionV6 = Omit & { + /** Connectors and network lists the function uses at runtime (at most 20) */ + dependencies?: AzionFunctionDependencyV6[]; +}; + +/** + * Function instance of the Azion API v6 (it has no `active`). + */ +export type AzionFunctionInstanceV6 = Omit; + +/** + * Rule of the Azion API v6 (it has no `active`). + */ +export type AzionRuleV6 = Omit; + +/** + * Rules of an application of the Azion API v6. + */ +export type AzionRulesV6 = { + /** Request rules */ + request?: AzionRuleV6[]; + /** Response rules */ + response?: AzionRuleV6[]; +}; + +/** + * Device group of an application of the Azion API v6. + */ +export type AzionDeviceGroupV6 = { + /** Device group name */ + name: string; + /** User agent regex pattern */ + userAgent: string; +}; + +/** + * Application of the Azion API v6. + */ +export type AzionApplicationV6 = { + /** Application name */ + name: string; + /** Enable edge cache */ + /** The cache module cannot be disabled, so it can only be true */ + edgeCacheEnabled?: true; + /** Enable functions */ + functionsEnabled?: boolean; + /** Enable application accelerator */ + applicationAcceleratorEnabled?: boolean; + /** Enable image processor */ + imageProcessorEnabled?: boolean; + /** Enable debug mode */ + debug?: boolean; + /** Cache settings */ + cache?: AzionCache[]; + /** Rules configuration */ + rules?: AzionRulesV6; + /** Function instances */ + functionsInstances?: AzionFunctionInstanceV6[]; + /** Device groups */ + deviceGroups?: AzionDeviceGroupV6[]; +}; + +/** + * TLS of a workload of the Azion API v6. The certificate is set per domain, in the bindings. + */ +export type AzionWorkloadTLSV6 = { + ciphers?: WorkloadTLSCipher; + minimumVersion?: WorkloadTLSVersion | null; +}; + +/** + * Domain served by a workload binding. + */ +export type AzionWorkloadBindingDomainV6 = { + /** Domain name */ + domain: string; + /** Digital certificate ID */ + certificate?: number | null; +}; + +/** + * Binding of a workload to an environment and a deployment. + */ +export type AzionWorkloadBindingV6 = { + /** Name of an environment declared in `environments` */ + environment: string; + /** Name of a deployment declared in `deployments` */ + deployment: string; + /** Domains served by the binding */ + domains?: AzionWorkloadBindingDomainV6[]; +}; + +/** + * Workload of the Azion API v6. + */ +export type AzionWorkloadV6 = { + name: string; + infrastructure?: WorkloadInfrastructure; + tls?: AzionWorkloadTLSV6; + protocols?: AzionWorkloadProtocols; + mtls?: AzionWorkloadMTLS; + workloadDomainAllowAccess?: boolean; + /** Environments and deployments the workload is bound to, with the domains of each binding */ + bindings?: AzionWorkloadBindingV6[]; +}; + +/** + * Environment of the Azion API v6. + */ +export type AzionEnvironmentV6 = { + /** Environment name */ + name: string; + description?: string | null; + logVerbosity?: (typeof ENVIRONMENT_LOG_VERBOSITY)[number]; + robotsPolicy?: (typeof ENVIRONMENT_ROBOTS_POLICIES)[number]; + protection?: { + azionAuthentication?: { enabled: boolean }; + passwordProtection?: { enabled: boolean; secretId: string | null }; + ipAllowlist?: { enabled: boolean; cidrs: string[] }; + ssoEnforcement?: { enabled: boolean; idpId: string | null; allowedDomains: string[] }; + }; + branchTracking?: { + enabled: boolean; + mode: (typeof ENVIRONMENT_BRANCH_TRACKING_MODES)[number]; + branchMatch: string; + } | null; + /** How the releases of the environment are served. Required by the API, and it cannot be changed afterwards */ + deploymentPolicy: (typeof ENVIRONMENT_DEPLOYMENT_POLICIES)[number]; +}; + +/** + * Deployment of the Azion API v6. + */ +export type AzionDeploymentV6 = { + /** Deployment name */ + name: string; + description?: string | null; + /** Whether a release can swap the resources of the deployment. Required by the API */ + bindingPolicy: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; + deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; + strategyDefaults?: { + skewProtection?: { enabled: boolean; defaultTtlSeconds: number }; + }; +}; + +/** + * Storage (bucket) of the Azion API v6. + */ +export type AzionStorageV6 = { + /** Storage name */ + name: string; + /** Access of the workloads to the storage */ + workloadsAccess?: (typeof WORKLOADS_ACCESS_TYPES)[number]; + /** Local directory whose files are uploaded to the storage */ + dir: string; + /** Prefix the files are uploaded under, which the storage connectors read from */ + prefix?: string; +}; + +/** + * Address of an HTTP connector. + */ +export type AzionConnectorAddressV6 = { + /** IPv4/IPv6 address or CNAME */ + address: string; + httpPort?: number; + httpsPort?: number; + /** Address modules */ + modules?: { + loadBalancer?: { + serverRole?: (typeof CONNECTOR_SERVER_ROLES)[number]; + weight?: number; + }; + }; +}; + +/** + * Attributes of an HTTP connector. + */ +export type AzionConnectorHttpAttributesV6 = { + addresses: AzionConnectorAddressV6[]; + connectionOptions?: { + dnsResolution?: (typeof CONNECTOR_DNS_RESOLUTION)[number]; + transportPolicy?: (typeof CONNECTOR_TRANSPORT_POLICY)[number]; + httpVersionPolicy?: (typeof CONNECTOR_HTTP_VERSION_POLICY)[number]; + host?: string; + pathPrefix?: string; + followingRedirect?: boolean; + realIpHeader?: string; + realPortHeader?: string; + }; + modules?: { + loadBalancer?: { + enabled: boolean; + config?: { + method?: (typeof CONNECTOR_LOAD_BALANCE_METHOD)[number]; + maxRetries?: number; + connectionTimeout?: number; + readWriteTimeout?: number; + }; + }; + originShield?: { + enabled: boolean; + config?: { + originIpAcl?: { enabled?: boolean }; + hmac?: { + enabled: boolean; + config?: { + type?: (typeof CONNECTOR_HMAC_TYPE)[number]; + attributes: { + region: string; + service?: string; + accessKey: string; + secretKey: string; + }; + }; + }; + }; + }; + }; +}; + +type AzionConnectorBaseV6 = { + /** Connector name */ + name: string; +}; + +/** + * Connector of the Azion API v6. + */ +export type AzionConnectorV6 = + | (AzionConnectorBaseV6 & { type: 'http'; attributes: AzionConnectorHttpAttributesV6 }) + | (AzionConnectorBaseV6 & { type: 'storage'; attributes: { bucket: string; prefix?: string } }) + | (AzionConnectorBaseV6 & { + type: 'live_ingest'; + attributes: { region: (typeof CONNECTOR_LIVE_INGEST_REGIONS)[number] }; + }); + +/** + * Page of a custom page, served for an error code. + */ +export type AzionCustomPageEntryV6 = { + /** Error code the page is served for (or `default`) */ + code: (typeof CUSTOM_PAGE_ERROR_CODES)[number]; + page: { + type?: (typeof CUSTOM_PAGE_TYPES)[number]; + attributes: { + /** Name of a connector declared in `connectors`, or its id */ + connector: string | number; + /** Time to live in seconds */ + ttl?: number; + /** Path the connector is requested with */ + uri?: string | null; + customStatusCode?: number | null; + }; + }; +}; + +/** + * Custom pages of the Azion API v6. + */ +export type AzionCustomPageV6 = { + /** Custom page name */ + name: string; + /** Pages, one for each error code */ + pages: AzionCustomPageEntryV6[]; +}; + +/** + * Network list of the Azion API v6. + */ +export type AzionNetworkListV6 = { + /** Network list name */ + name: string; + /** Type of the items: IP addresses (with or without CIDR), ASNs or country codes */ + type: (typeof NETWORK_LIST_TYPES)[number]; + /** Items of the list */ + items: string[]; +}; + +/** + * Criterion of a firewall rule. The argument is optional (the operators `exists` and `does_not_exist` do not take one). + */ +export type AzionFirewallCriterionV6 = { + /** Variable, with or without `${}` */ + variable: string; + conditional: (typeof FIREWALL_RULE_CONDITIONAL)[number]; + operator: (typeof FIREWALL_RULE_OPERATORS)[number]; + argument?: string | number | null; +}; + +/** + * Behavior of a firewall rule. `run_function` and `set_waf` reference a function and a waf by name or by id. + */ +export type AzionFirewallBehaviorV6 = + | { type: 'run_function'; attributes: { value: string | number } } + | { type: 'set_waf'; attributes: { mode: (typeof FIREWALL_WAF_MODES)[number]; wafId: string | number } } + | { + type: 'set_rate_limit'; + attributes: { + type?: (typeof FIREWALL_RATE_LIMIT_TYPES)[number]; + limitBy: (typeof FIREWALL_RATE_LIMIT_BY)[number]; + averageRateLimit: number; + maximumBurstSize?: number | null; + }; + } + | { type: (typeof FIREWALL_NO_ARGS_BEHAVIORS)[number] } + | { + type: 'set_custom_response'; + attributes: { statusCode: number; contentType?: string; contentBody?: string }; + }; + +/** + * Rule of a firewall: either `criteria`, or `match` and `variable` together (a `matches` criterion). + */ +export type AzionFirewallRuleV6 = { + name: string; + description?: string; + /** Regex the variable must match */ + match?: string; + variable?: string; + criteria?: AzionFirewallCriterionV6[]; + behaviors: AzionFirewallBehaviorV6[]; +}; + +/** + * Firewall of the Azion API v6. + */ +export type AzionFirewallV6 = { + name: string; + debugRules?: boolean; + /** Enable the functions module */ + functions?: boolean; + /** Enable the network protection module */ + networkProtection?: boolean; + /** Enable the waf module */ + waf?: boolean; + rules?: AzionFirewallRuleV6[]; + functionsInstances?: AzionFunctionInstanceV6[]; +}; + +/** + * WAF of the Azion API v6. + */ +export type AzionWafV6 = { + name: string; + engineSettings?: { + engineVersion?: (typeof WAF_ENGINE_VERSIONS)[number]; + type?: (typeof WAF_ENGINE_TYPES)[number]; + attributes?: { + rulesets?: (typeof WAF_RULESETS)[number][]; + thresholds?: { + threat: (typeof WAF_THREAT_TYPES)[number]; + sensitivity?: (typeof WAF_SENSITIVITY)[number]; + }[]; + }; + }; +}; + +/** + * Purge of the Azion API v6. + */ +export type AzionPurgeV6 = { + /** Items to be purged */ + items: string[]; + /** Cache layer to be purged */ + layer?: 'cache'; + /** Purge type */ + type: 'url' | 'cachekey' | 'wildcard'; +}; + +/** + * Config of the Azion API v6. + */ +export type AzionConfigV6 = { + /** Azion API version this config targets. */ + version: 6; + /** Build configuration (shared by every API version). */ + build?: AzionBuild; + /** Functions */ + functions?: AzionFunctionV6[]; + /** Storage buckets */ + storage?: AzionStorageV6[]; + /** Custom pages */ + customPages?: AzionCustomPageV6[]; + /** Network lists */ + networkList?: AzionNetworkListV6[]; + /** WAFs */ + waf?: AzionWafV6[]; + /** Firewalls */ + firewall?: AzionFirewallV6[]; + /** Connectors */ + connectors?: AzionConnectorV6[]; + /** Applications */ + applications?: AzionApplicationV6[]; + /** Workloads */ + workloads?: AzionWorkloadV6[]; + /** Environments */ + environments?: AzionEnvironmentV6[]; + /** Deployments */ + deployments?: AzionDeploymentV6[]; + /** Purge configurations */ + purge?: AzionPurgeV6[]; +}; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts new file mode 100644 index 00000000..2ee2831e --- /dev/null +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -0,0 +1,1464 @@ +import { validateConfig } from '.'; + +describe('validateConfig (v6)', () => { + describe('build', () => { + it('accepts a complete build config', () => { + expect(() => + validateConfig({ + version: 6, + build: { + bundler: 'esbuild', + entry: { main: './src/index.js' }, + preset: 'next', + polyfills: true, + worker: false, + memoryFS: { injectionDirs: ['./src/injected'], removePathPrefix: './src' }, + }, + }), + ).not.toThrow(); + }); + + it('accepts a preset declared as an object', () => { + expect(() => + validateConfig({ + version: 6, + build: { + preset: { metadata: { name: 'custom' }, config: { version: 6, build: { bundler: 'esbuild' } } }, + }, + }), + ).not.toThrow(); + }); + + it('rejects an invalid bundler', () => { + expect(() => validateConfig({ version: 6, build: { bundler: 'rollup' } })).toThrow( + "The 'build.bundler' must be either 'webpack' or 'esbuild'", + ); + }); + + it('rejects unknown properties in build', () => { + expect(() => validateConfig({ version: 6, build: { unknown: true } })).toThrow( + "No additional properties are allowed in the 'build' object", + ); + }); + + it('rejects an invalid entry', () => { + expect(() => validateConfig({ version: 6, build: { entry: 1 } })).toThrow( + "The 'build.entry' must be a string, array of strings, or object with string values", + ); + }); + }); + + describe('applications', () => { + it('accepts a complete application', () => { + expect(() => + validateConfig({ + version: 6, + applications: [ + { + name: 'my-app', + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: false, + }, + ], + }), + ).not.toThrow(); + }); + + it('requires the name', () => { + expect(() => validateConfig({ version: 6, applications: [{}] })).toThrow( + "The 'name' field is required in an application", + ); + }); + + it('accepts a name of 100 characters and rejects a longer one (v6 API limit)', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a'.repeat(100) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, applications: [{ name: 'a'.repeat(101) }] })).toThrow( + "The 'name' field must be a string with 1 to 100 characters", + ); + }); + + it('rejects an empty name', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: '' }] })).toThrow( + "The 'name' field must be a string with 1 to 100 characters", + ); + }); + + it('rejects a flag that is not a boolean', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', functionsEnabled: 'yes' }] })).toThrow( + "The 'functionsEnabled' field must be a boolean", + ); + }); + + it('rejects unknown properties in an application', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', unknown: true }] })).toThrow( + 'No additional properties are allowed in an application', + ); + }); + + it('rejects applications that are not an array', () => { + expect(() => validateConfig({ version: 6, applications: {} })).toThrow( + "The 'applications' field must be an array of application items.", + ); + }); + }); + + it('rejects properties the v6 schema does not know yet', () => { + expect(() => validateConfig({ version: 6, kv: [] })).toThrow( + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', + ); + }); + + it('rejects another version', () => { + expect(() => validateConfig({ version: 4, build: {} })).toThrow(); + }); +}); + +describe('validateConfig (v6) functions', () => { + it('accepts a complete function', () => { + expect(() => + validateConfig({ + version: 6, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + }, + ], + }), + ).not.toThrow(); + }); + + it('requires name and path', () => { + expect(() => validateConfig({ version: 6, functions: [{ path: './a.js' }] })).toThrow(); + expect(() => validateConfig({ version: 6, functions: [{ name: 'a' }] })).toThrow(); + }); + + it('rejects an unknown runtime and execution environment', () => { + expect(() => validateConfig({ version: 6, functions: [{ name: 'a', path: './a.js', runtime: 'node' }] })).toThrow( + "The 'runtime' field must be 'azion_js'", + ); + expect(() => + validateConfig({ version: 6, functions: [{ name: 'a', path: './a.js', executionEnvironment: 'edge' }] }), + ).toThrow("The 'executionEnvironment' field must be 'application' or 'firewall'"); + }); + + describe('bindings', () => { + const binding = (bindings: unknown) => ({ + version: 6, + functions: [{ name: 'my-function', path: './functions/index.js', bindings }], + }); + + it('accepts a storage binding with the bucket as a name or an id', () => { + expect(() => validateConfig(binding({ storage: { bucket: 'my-bucket', prefix: 'assets' } }))).not.toThrow(); + expect(() => validateConfig(binding({ storage: { bucket: 10, prefix: '' } }))).not.toThrow(); + expect(() => validateConfig(binding({}))).not.toThrow(); + }); + + it('requires the bucket and the prefix of a storage binding', () => { + expect(() => validateConfig(binding({ storage: { bucket: 'my-bucket' } }))).toThrow( + "The 'bucket' and 'prefix' fields are required in the storage object binding.", + ); + expect(() => validateConfig(binding({ storage: { prefix: 'assets' } }))).toThrow(); + }); + + it('rejects unknown properties in the bindings and in the storage binding', () => { + expect(() => validateConfig(binding({ kv: {} }))).toThrow( + 'No additional properties are allowed in the bindings object', + ); + expect(() => + validateConfig(binding({ storage: { bucket: 'my-bucket', prefix: 'assets', unknown: true } })), + ).toThrow('No additional properties are allowed in the storage object binding.'); + }); + }); +}); + +describe('validateConfig (v6) application functionsInstances and rules', () => { + const app = (extra: Record) => ({ version: 6, applications: [{ name: 'my-app', ...extra }] }); + const requestRule = (extra: Record = {}) => ({ + name: 'rule', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'deliver' }], + ...extra, + }); + + describe('functionsInstances', () => { + it('accepts an instance and requires name and ref', () => { + expect(() => + validateConfig(app({ functionsInstances: [{ name: 'i', ref: 'fn', args: { a: 1 } }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'i', ref: 10 }] }))).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'i' }] }))).toThrow( + "The 'name' and 'ref' fields are required in each function instance", + ); + }); + + it('limits the name to 100 characters', () => { + expect(() => validateConfig(app({ functionsInstances: [{ name: 'a'.repeat(100), ref: 'fn' }] }))).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'a'.repeat(101), ref: 'fn' }] }))).toThrow( + "The 'name' field must be a string between 1 and 100 characters", + ); + }); + }); + + describe('rules', () => { + it('accepts request and response rules', () => { + expect(() => + validateConfig( + app({ + rules: { + request: [requestRule({ description: 'd' })], + response: [requestRule({ behaviors: [{ type: 'add_response_header', attributes: { value: 'x: y' } }] })], + }, + }), + ), + ).not.toThrow(); + }); + + it('limits the rule name to 100 characters (v6 API limit, 250 in v4)', () => { + const rules = (name: string) => ({ rules: { request: [requestRule({ name })] } }); + expect(() => validateConfig(app(rules('a'.repeat(100))))).not.toThrow(); + expect(() => validateConfig(app(rules('a'.repeat(101))))).toThrow( + "The 'name' field must be a string between 1 and 100 characters.", + ); + }); + + it('validates the variables of each phase as the v6 API documents them', () => { + const criteria = (variable: string) => [[{ variable, conditional: 'if', operator: 'exists' }]]; + const request = (variable: string) => + app({ rules: { request: [requestRule({ criteria: criteria(variable) })] } }); + const response = (variable: string) => + app({ rules: { response: [requestRule({ criteria: criteria(variable) })] } }); + + // available in both phases in v6 (a single phase in v4) + expect(() => validateConfig(request('${tcpinfo_rtt}'))).not.toThrow(); + expect(() => validateConfig(response('${server_addr}'))).not.toThrow(); + expect(() => validateConfig(response('${ssl_client_verify}'))).not.toThrow(); + // response only + expect(() => validateConfig(response('${status}'))).not.toThrow(); + expect(() => validateConfig(request('${status}'))).toThrow(); + expect(() => validateConfig(request('${sent_http_x_header}'))).toThrow(); + expect(() => validateConfig(response('${sent_http_x_header}'))).not.toThrow(); + // v4 only + expect(() => validateConfig(response('${sent_http_name}'))).not.toThrow(); // matches sent_http_ + }); + + it('requires the argument only for the operators with value', () => { + const rule = (criterion: Record) => + app({ rules: { request: [requestRule({ criteria: [[criterion]] })] } }); + expect(() => validateConfig(rule({ variable: '${uri}', conditional: 'if', operator: 'matches' }))).toThrow(); + expect(() => + validateConfig(rule({ variable: '${uri}', conditional: 'if', operator: 'exists', argument: 'x' })), + ).toThrow(); + }); + + it('does not accept the firewall operators in an application rule', () => { + expect(() => + validateConfig( + app({ + rules: { + request: [ + requestRule({ + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'is_in_list', argument: '1' }]], + }), + ], + }, + }), + ), + ).toThrow(); + }); + + it('rejects a behavior that is not valid', () => { + expect(() => + validateConfig(app({ rules: { request: [requestRule({ behaviors: [{ type: 'unknown' }] })] } })), + ).toThrow(); + }); + }); + + describe('deviceGroups', () => { + it('accepts a device group and requires name and userAgent', () => { + expect(() => + validateConfig(app({ deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'mobile' }] }))).toThrow( + "The 'name' and 'userAgent' fields are required in each device group", + ); + }); + + it('limits the name to 250 characters and the user agent to 512 (DeviceGroupRequest)', () => { + expect(() => + validateConfig(app({ deviceGroups: [{ name: 'a'.repeat(250), userAgent: 'u'.repeat(512) }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a'.repeat(251), userAgent: 'u' }] }))).toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a', userAgent: 'u'.repeat(513) }] }))).toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: '', userAgent: 'u' }] }))).toThrow(); + }); + + it('rejects unknown properties in a device group', () => { + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a', userAgent: 'u', id: 1 }] }))).toThrow( + 'No additional properties are allowed in device group objects', + ); + }); + }); +}); + +describe('validateConfig (v6) workloads, environments and deployments', () => { + const workload = (extra: Record = {}) => ({ + version: 6, + workloads: [{ name: 'my-workload', ...extra }], + }); + const environment = (extra: Record = {}) => ({ + version: 6, + environments: [{ name: 'production', deploymentPolicy: 'single_version', ...extra }], + }); + const deployment = (extra: Record = {}) => ({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE', ...extra }], + }); + + describe('workloads', () => { + it('accepts a complete workload', () => { + expect(() => + validateConfig( + workload({ + infrastructure: 2, + workloadDomainAllowAccess: false, + tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, + protocols: { + http: { versions: ['http1', 'http2'], httpPorts: [80, 8080], httpsPorts: [443], quicPorts: null }, + }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1, 2] } }, + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'example.com', certificate: 7 }, { domain: 'www.example.com' }], + }, + ], + }), + ), + ).not.toThrow(); + }); + + it('requires only the name', () => { + expect(() => validateConfig({ version: 6, workloads: [{}] })).toThrow( + "The 'name' field is required in workloads", + ); + expect(() => validateConfig(workload())).not.toThrow(); + }); + + it('limits the name to 100 characters', () => { + expect(() => validateConfig({ version: 6, workloads: [{ name: 'a'.repeat(100) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, workloads: [{ name: 'a'.repeat(101) }] })).toThrow( + "The 'name' field must be a string between 1 and 100 characters", + ); + }); + + it('moved the domains and the certificate to the bindings', () => { + expect(() => validateConfig(workload({ domains: ['example.com'] }))).toThrow( + 'No additional properties are allowed in workload items', + ); + expect(() => validateConfig(workload({ tls: { certificate: 1 } }))).toThrow( + 'The certificate is set per domain in the bindings', + ); + }); + + it('does not accept a null tls.ciphers nor one out of range', () => { + expect(() => validateConfig(workload({ tls: { ciphers: null } }))).toThrow( + "The 'ciphers' must be an integer between 1-8", + ); + expect(() => validateConfig(workload({ tls: { ciphers: 9 } }))).toThrow(); + }); + + it('applies the limits of the http protocol of the v6 API', () => { + const http = (extra: Record) => + workload({ + protocols: { http: { versions: ['http1', 'http2'], httpPorts: [80], httpsPorts: [443], ...extra } }, + }); + + expect(() => validateConfig(http({}))).not.toThrow(); + // the API requires http1 and http2 + expect(() => validateConfig(http({ versions: ['http3'] }))).toThrow(); + expect(() => validateConfig(http({ versions: ['http1', 'http3'] }))).toThrow(); + expect(() => validateConfig(http({ httpPorts: [] }))).toThrow(); + expect(() => validateConfig(http({ httpPorts: [80, 81, 82, 83, 84] }))).toThrow(); + expect(() => validateConfig(http({ httpsPorts: Array.from({ length: 13 }, (_, i) => 443 + i) }))).toThrow(); + expect(() => validateConfig(http({ quicPorts: Array.from({ length: 13 }, (_, i) => 443 + i) }))).toThrow(); + expect(() => validateConfig(http({ versions: ['http1', 'http2', 'http3', 'http1'] }))).toThrow(); + }); + + it('requires environment and deployment in a binding', () => { + expect(() => validateConfig(workload({ bindings: [{ environment: 'production' }] }))).toThrow( + "The 'environment' and 'deployment' fields are required in each binding", + ); + expect(() => validateConfig(workload({ bindings: [{ deployment: 'default-deployment' }] }))).toThrow(); + }); + + it('requires the domain in a binding domain and rejects unknown properties', () => { + const binding = (domains: unknown[]) => + workload({ bindings: [{ environment: 'production', deployment: 'default-deployment', domains }] }); + + expect(() => validateConfig(binding([{ certificate: 1 }]))).toThrow( + "The 'domain' field is required in each binding domain", + ); + expect(() => validateConfig(binding([{ domain: 'a.com', unknown: true }]))).toThrow( + 'No additional properties are allowed in binding domains', + ); + }); + }); + + describe('environments', () => { + it('accepts a complete environment', () => { + expect(() => + validateConfig( + environment({ + description: 'Production', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: false, idpId: null, allowedDomains: [] }, + }, + branchTracking: { enabled: true, mode: 'branch_starts_with', branchMatch: 'release/' }, + deploymentPolicy: 'versioned_urls', + }), + ), + ).not.toThrow(); + expect(() => validateConfig(environment({ description: null, branchTracking: null }))).not.toThrow(); + }); + + it('limits the name to 3-255 characters and requires it', () => { + expect(() => + validateConfig({ version: 6, environments: [{ description: 'x', deploymentPolicy: 'single_version' }] }), + ).toThrow("The 'name' field is required in each environment"); + expect(() => + validateConfig({ version: 6, environments: [{ name: 'ab', deploymentPolicy: 'single_version' }] }), + ).toThrow("The 'name' field must be a string between 3 and 255 characters"); + expect(() => + validateConfig({ version: 6, environments: [{ name: 'a'.repeat(256), deploymentPolicy: 'single_version' }] }), + ).toThrow(); + }); + + it('requires the deploymentPolicy (the API requires it and does not accept changing it later)', () => { + expect(() => validateConfig({ version: 6, environments: [{ name: 'production' }] })).toThrow( + "The 'deploymentPolicy' field is required in each environment", + ); + expect(() => validateConfig(environment({ deploymentPolicy: 'single_version' }))).not.toThrow(); + expect(() => validateConfig(environment({ deploymentPolicy: 'versioned_urls' }))).not.toThrow(); + }); + + it('rejects values out of the enums', () => { + expect(() => validateConfig(environment({ logVerbosity: 'debug' }))).toThrow( + "The 'logVerbosity' field must be one of: normal, verbose", + ); + expect(() => validateConfig(environment({ robotsPolicy: 'all' }))).toThrow( + "The 'robotsPolicy' field must be one of: index, noindex, respect_origin", + ); + expect(() => validateConfig(environment({ deploymentPolicy: 'multiple' }))).toThrow( + "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", + ); + expect(() => + validateConfig(environment({ branchTracking: { enabled: true, mode: 'branch_matches', branchMatch: 'a' } })), + ).toThrow("The 'mode' field must be one of: branch_is, branch_starts_with, branch_ends_with"); + }); + + it('requires the fields of branchTracking and of the protections', () => { + expect(() => validateConfig(environment({ branchTracking: { enabled: true } }))).toThrow( + "The 'enabled', 'mode' and 'branchMatch' fields are required in branchTracking", + ); + expect(() => validateConfig(environment({ protection: { ipAllowlist: { enabled: true } } }))).toThrow(); + expect(() => validateConfig(environment({ protection: { unknown: {} } }))).toThrow( + 'No additional properties are allowed in the environment protection', + ); + }); + }); + + describe('deployments', () => { + it('accepts a complete deployment', () => { + expect(() => + validateConfig( + deployment({ + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }), + ), + ).not.toThrow(); + }); + + it('limits the name to 3-255 characters and requires it', () => { + expect(() => validateConfig({ version: 6, deployments: [{ bindingPolicy: 'STRICT' }] })).toThrow( + "The 'name' field is required in each deployment", + ); + expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab', bindingPolicy: 'FLEXIBLE' }] })).toThrow( + "The 'name' field must be a string between 3 and 255 characters", + ); + }); + + it('requires the bindingPolicy (the creation of a deployment requires it)', () => { + expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( + "The 'bindingPolicy' field is required in each deployment", + ); + expect(() => validateConfig(deployment({ bindingPolicy: 'STRICT' }))).not.toThrow(); + expect(() => validateConfig(deployment({ bindingPolicy: 'FLEXIBLE' }))).not.toThrow(); + }); + + it('rejects values out of the enums and invalid skew protection', () => { + expect(() => validateConfig(deployment({ bindingPolicy: 'strict' }))).toThrow( + "The 'bindingPolicy' field must be one of: STRICT, FLEXIBLE", + ); + expect(() => validateConfig(deployment({ deploymentPolicy: 'rolling' }))).toThrow( + "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", + ); + expect(() => validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true } } }))).toThrow( + "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + ); + expect(() => + validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 0 } } })), + ).toThrow(); + }); + }); +}); + +describe('validateConfig (v6) storage and connectors', () => { + const storage = (extra: Record = {}) => ({ + version: 6, + storage: [{ name: 'my-bucket', dir: './dist', ...extra }], + }); + const connector = (extra: Record) => ({ + version: 6, + connectors: [{ name: 'my-connector', ...extra }], + }); + const http = (attributes: Record = {}) => + connector({ type: 'http', attributes: { addresses: [{ address: 'origin.example.com' }], ...attributes } }); + + describe('storage', () => { + it('accepts a complete storage', () => { + expect(() => validateConfig(storage({ workloadsAccess: 'read_write', prefix: 'assets' }))).not.toThrow(); + }); + + it('requires only name and dir (the prefix is optional in v6)', () => { + expect(() => validateConfig(storage())).not.toThrow(); + expect(() => validateConfig({ version: 6, storage: [{ dir: './dist' }] })).toThrow( + "The 'name' and 'dir' fields are required.", + ); + expect(() => validateConfig({ version: 6, storage: [{ name: 'my-bucket' }] })).toThrow(); + }); + + it('applies the name rules of the v6 API (lowercase letters, digits, hyphens, 6 to 63 characters)', () => { + const name = (value: string) => validateConfig({ version: 6, storage: [{ name: value, dir: './dist' }] }); + + expect(() => name('my-bucket-01')).not.toThrow(); + expect(() => name('a'.repeat(63))).not.toThrow(); + expect(() => name('short')).toThrow(); + expect(() => name('a'.repeat(64))).toThrow(); + expect(() => name('My-Bucket')).toThrow(); + expect(() => name('my_bucket')).toThrow(); + expect(() => name('-my-bucket')).toThrow(); + expect(() => name('my-bucket-')).toThrow(); + }); + + it('accepts a $PLACEHOLDER as the name, as the presets use them', () => { + expect(() => validateConfig({ version: 6, storage: [{ name: '$BUCKET_NAME', dir: './dist' }] })).not.toThrow(); + }); + + it('rejects an unknown workloadsAccess and unknown properties', () => { + expect(() => validateConfig(storage({ workloadsAccess: 'write_only' }))).toThrow( + "The 'workloadsAccess' field must be one of: read_only, read_write, restricted.", + ); + expect(() => validateConfig(storage({ unknown: true }))).toThrow( + 'No additional properties are allowed in storage items.', + ); + }); + }); + + describe('connectors', () => { + it('accepts a storage connector with and without prefix', () => { + expect(() => + validateConfig(connector({ type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } })), + ).not.toThrow(); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'my-bucket' } }))).not.toThrow(); + }); + + it('requires the bucket and does not accept an empty prefix in a storage connector', () => { + expect(() => validateConfig(connector({ type: 'storage', attributes: {} }))).toThrow( + "The 'bucket' field is required in storage attributes", + ); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'b', prefix: '' } }))).toThrow( + "The 'prefix' field must be a string between 1 and 255 characters", + ); + }); + + it('accepts a live ingest connector and validates its region', () => { + expect(() => + validateConfig(connector({ type: 'live_ingest', attributes: { region: 'br-east-1' } })), + ).not.toThrow(); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: { region: 'eu-west-1' } }))).toThrow( + "The 'region' field must be one of: us-east-1, us-east-2, br-east-1, br-east-2, br-east-3", + ); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: {} }))).toThrow( + "The 'region' field is required in live ingest attributes", + ); + }); + + it('accepts an http connector with only the addresses', () => { + expect(() => validateConfig(http())).not.toThrow(); + }); + + it('accepts a complete http connector', () => { + expect(() => + validateConfig( + http({ + addresses: [ + { + address: 'origin.example.com', + httpPort: 8080, + httpsPort: 8443, + modules: { loadBalancer: { serverRole: 'backup', weight: 50 } }, + }, + ], + connectionOptions: { + dnsResolution: 'force_ipv6', + transportPolicy: 'force_https', + httpVersionPolicy: 'http1_1', + host: '${host}', + pathPrefix: '/api', + followingRedirect: true, + realIpHeader: 'X-Real-IP', + realPortHeader: 'X-Real-PORT', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'least_conn', maxRetries: 3, connectionTimeout: 30, readWriteTimeout: 60 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }), + ), + ).not.toThrow(); + }); + + it('requires at least one address with an address', () => { + expect(() => validateConfig(connector({ type: 'http', attributes: {} }))).toThrow( + "The 'addresses' field is required in HTTP attributes", + ); + expect(() => validateConfig(http({ addresses: [] }))).toThrow( + "The 'addresses' field must be an array of at least one address object", + ); + expect(() => validateConfig(http({ addresses: [{ httpPort: 80 }] }))).toThrow(); + }); + + it('accepts force_ipv6 (new in v6) and rejects the other values of dnsResolution', () => { + expect(() => validateConfig(http({ connectionOptions: { dnsResolution: 'force_ipv6' } }))).not.toThrow(); + expect(() => validateConfig(http({ connectionOptions: { dnsResolution: 'ipv6' } }))).toThrow( + "The 'dnsResolution' must be one of: both, force_ipv4, force_ipv6", + ); + }); + + it('validates the load balancer of an address (serverRole and weight)', () => { + const address = (loadBalancer: Record) => + http({ addresses: [{ address: 'o.example.com', modules: { loadBalancer } }] }); + + expect(() => validateConfig(address({ serverRole: 'primary', weight: 1 }))).not.toThrow(); + expect(() => validateConfig(address({ serverRole: 'secondary' }))).toThrow( + "The 'serverRole' must be one of: primary, backup", + ); + expect(() => validateConfig(address({ weight: 101 }))).toThrow("The 'weight' must be between 1 and 100"); + expect(() => validateConfig(address({ weight: 0 }))).toThrow(); + }); + + it('does not accept null in the module configs and requires enabled and the hmac attributes', () => { + expect(() => validateConfig(http({ modules: { loadBalancer: { enabled: true, config: null } } }))).toThrow(); + expect(() => validateConfig(http({ modules: { loadBalancer: {} } }))).toThrow(); + expect(() => + validateConfig( + http({ modules: { originShield: { enabled: true, config: { hmac: { enabled: true, config: {} } } } } }), + ), + ).toThrow(); + expect(() => + validateConfig(http({ modules: { originShield: { enabled: true, config: { hmac: { config: {} } } } } })), + ).toThrow(); + }); + + it('validates the limits of the load balancer config', () => { + const config = (value: Record) => + http({ modules: { loadBalancer: { enabled: true, config: value } } }); + + expect(() => validateConfig(config({ maxRetries: 21 }))).toThrow("The 'maxRetries' must be between 0 and 20"); + expect(() => validateConfig(config({ connectionTimeout: 301 }))).toThrow(); + expect(() => validateConfig(config({ readWriteTimeout: 601 }))).toThrow(); + expect(() => validateConfig(config({ method: 'random' }))).toThrow(); + }); + + it('ties the attributes to the type of the connector', () => { + expect(() => + validateConfig(connector({ type: 'storage', attributes: { addresses: [{ address: 'a.com' }] } })), + ).toThrow(); + expect(() => validateConfig(connector({ type: 'http', attributes: { bucket: 'my-bucket' } }))).toThrow(); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: { bucket: 'my-bucket' } }))).toThrow(); + }); + + it('requires name, type and attributes and rejects an unknown type and unknown properties', () => { + expect(() => + validateConfig({ version: 6, connectors: [{ type: 'storage', attributes: { bucket: 'b' } }] }), + ).toThrow("The 'name', 'type' and 'attributes' fields are required in each connector"); + expect(() => validateConfig(connector({ type: 'ftp', attributes: {} }))).toThrow( + "The 'type' field must be one of: http, storage, live_ingest", + ); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'b' }, unknown: true }))).toThrow( + 'No additional properties are allowed in connector objects', + ); + }); + }); +}); + +describe('validateConfig (v6) application cache', () => { + const cache = (value: Record) => ({ + version: 6, + applications: [{ name: 'my-app', cache: [{ name: 'my-cache', ...value }] }], + }); + + it('accepts a complete cache setting', () => { + expect(() => + validateConfig( + cache({ + stale: true, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'us-east-1' }, + methods: { post: true, options: false }, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: '60 * 60 * 24' }, + cacheByCookie: { option: 'allowlist', list: ['session'] }, + cacheByQueryString: { option: 'denylist', list: ['utm'] }, + }), + ), + ).not.toThrow(); + expect(() => validateConfig(cache({}))).not.toThrow(); + }); + + it('requires the name and limits it to 250 characters', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', cache: [{ stale: true }] }] })).toThrow( + "The 'name' field is required in each cache item.", + ); + expect(() => validateConfig(cache({ name: 'a'.repeat(250) }))).not.toThrow(); + expect(() => validateConfig(cache({ name: 'a'.repeat(251) }))).toThrow( + "The 'name' field must be a string with 1 to 250 characters", + ); + }); + + it('limits a numeric max age to 0..31536000 (the v6 API limit) and accepts an expression', () => { + expect(() => + validateConfig(cache({ browser: { maxAgeSeconds: 0 }, edge: { maxAgeSeconds: 31536000 } })), + ).not.toThrow(); + expect(() => validateConfig(cache({ browser: { maxAgeSeconds: 31536001 } }))).toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: -1 } }))).toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: '60 * 60' } }))).not.toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: 'abc' } }))).toThrow( + "The 'maxAgeSeconds' field must be a valid mathematical expression.", + ); + }); + + it('requires the topology when the tiered cache is enabled and does not accept null', () => { + expect(() => validateConfig(cache({ tieredCache: { enabled: true } }))).toThrow( + "When 'enabled' is true, 'topology' is required in the 'tiered_cache' object.", + ); + expect(() => validateConfig(cache({ tieredCache: { enabled: false } }))).not.toThrow(); + expect(() => validateConfig(cache({ tieredCache: { enabled: false, topology: null } }))).toThrow( + "The 'topology' field must be one of 'nearest-region', 'br-east-1' or 'us-east-1'.", + ); + expect(() => validateConfig(cache({ tieredCache: { enabled: true, topology: 'eu-west-1' } }))).toThrow(); + }); + + it('validates the cache by cookie and by query string', () => { + expect(() => validateConfig(cache({ cacheByCookie: { option: 'sometimes' } }))).toThrow( + "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + ); + expect(() => validateConfig(cache({ cacheByQueryString: { list: ['q'] } }))).toThrow( + "The 'option' field is required in the 'cacheByQueryString' object.", + ); + expect(() => validateConfig(cache({ cacheByQueryString: { option: 'allowlist' } }))).toThrow( + "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + ); + }); + + it('rejects unknown properties in a cache setting', () => { + expect(() => validateConfig(cache({ unknown: true }))).toThrow( + 'No additional properties are allowed in cache item objects.', + ); + expect(() => validateConfig(cache({ methods: { get: true } }))).toThrow( + "No additional properties are allowed in the 'methods' object.", + ); + }); +}); + +describe('validateConfig (v6) waf and firewall', () => { + const waf = (extra: Record = {}) => ({ version: 6, waf: [{ name: 'my-waf', ...extra }] }); + const firewall = (extra: Record = {}) => ({ + version: 6, + firewall: [{ name: 'my-firewall', ...extra }], + }); + const rule = (extra: Record = {}) => + firewall({ + rules: [ + { + name: 'rule', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'deny' }], + ...extra, + }, + ], + }); + const behavior = (value: Record) => rule({ behaviors: [value] }); + + describe('waf', () => { + it('accepts a waf with only the name, and a complete one', () => { + expect(() => validateConfig(waf())).not.toThrow(); + expect(() => + validateConfig( + waf({ + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'highest' }, { threat: 'file_upload' }], + }, + }, + }), + ), + ).not.toThrow(); + }); + + it('requires the name and limits it to 250 characters', () => { + expect(() => validateConfig({ version: 6, waf: [{}] })).toThrow("The 'name' field is required in the WAF object"); + expect(() => validateConfig({ version: 6, waf: [{ name: 'a'.repeat(251) }] })).toThrow(); + }); + + it('does not accept id nor productVersion (they are not in the v6 request)', () => { + expect(() => validateConfig(waf({ id: 1 }))).toThrow('No additional properties are allowed in the WAF object'); + expect(() => validateConfig(waf({ productVersion: '1.0' }))).toThrow( + 'No additional properties are allowed in the WAF object', + ); + }); + + it('validates the engine settings and the thresholds', () => { + const engine = (attributes: Record) => waf({ engineSettings: { attributes } }); + + expect(() => validateConfig(waf({ engineSettings: { engineVersion: '2022-Q1' } }))).toThrow( + "The 'engineVersion' field must be '2021-Q3'", + ); + expect(() => validateConfig(waf({ engineSettings: { type: 'rules' } }))).toThrow( + "The 'type' field must be 'score'", + ); + expect(() => validateConfig(engine({ rulesets: [2] }))).toThrow( + "The 'rulesets' field must be an array containing [1]", + ); + expect(() => validateConfig(engine({ thresholds: [{ sensitivity: 'low' }] }))).toThrow( + "The 'threat' field is required in each threshold", + ); + expect(() => validateConfig(engine({ thresholds: [{ threat: 'xss' }] }))).toThrow( + "The 'threat' field must be one of:", + ); + expect(() => validateConfig(engine({ thresholds: [{ threat: 'file_upload', sensitivity: 'max' }] }))).toThrow( + "The 'sensitivity' field must be one of: highest, high, medium, low, lowest", + ); + expect(() => + validateConfig(engine({ thresholds: Array.from({ length: 9 }, () => ({ threat: 'file_upload' })) })), + ).toThrow("The 'thresholds' field must be an array of threat configurations (max 8 items)"); + }); + }); + + describe('firewall', () => { + it('accepts a firewall with only the name, and a complete one', () => { + expect(() => validateConfig(firewall())).not.toThrow(); + expect(() => + validateConfig( + firewall({ + debugRules: false, + functions: true, + networkProtection: true, + waf: true, + rules: [ + { + name: 'rule', + description: 'Block admin', + criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'bypass' }], + }, + ], + functionsInstances: [{ name: 'instance', ref: 'fn', args: {} }], + }), + ), + ).not.toThrow(); + }); + + it('limits the firewall name to 250 characters and the rule name to 100 (v6 API limits)', () => { + expect(() => validateConfig({ version: 6, firewall: [{ name: 'a'.repeat(250) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, firewall: [{ name: 'a'.repeat(251) }] })).toThrow( + "The firewall configuration must have a 'name' field of type string (1-250 characters)", + ); + expect(() => validateConfig(rule({ name: 'a'.repeat(100) }))).not.toThrow(); + expect(() => validateConfig(rule({ name: 'a'.repeat(101) }))).toThrow( + "Each firewall rule must have a 'name' field of type string (1-100 characters)", + ); + expect(() => validateConfig(rule({ description: 'a'.repeat(1001) }))).toThrow( + "The rule's 'description' field must be a string of at most 1000 characters", + ); + }); + + it('requires the argument unless the operator is exists or does_not_exist', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', ...value }] }); + const message = "The 'argument' field is required unless the operator is 'exists' or 'does_not_exist'"; + + expect(() => validateConfig(criterion({ operator: 'is_equal', argument: 'example.com' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'exists' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'does_not_exist' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'is_equal' }))).toThrow(message); + expect(() => validateConfig(criterion({ operator: 'is_in_list' }))).toThrow(message); + expect(() => validateConfig(criterion({ operator: 'matches', argument: null }))).toThrow(); + }); + + it('does not require the argument of a criterion and accepts null', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', operator: 'exists', ...value }] }); + + expect(() => validateConfig(criterion({}))).not.toThrow(); + expect(() => validateConfig(criterion({ argument: null }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'is_in_list', argument: 12 }))).not.toThrow(); + expect(() => validateConfig(criterion({ argument: true }))).toThrow( + 'The argument must be a string, a number or null', + ); + }); + + it('allows up to 10 criteria in a rule (the group limit of the v6 API)', () => { + const criteria = (n: number) => + rule({ + criteria: Array.from({ length: n }, () => ({ variable: 'host', conditional: 'and', operator: 'exists' })), + }); + + expect(() => validateConfig(criteria(10))).not.toThrow(); + expect(() => validateConfig(criteria(11))).toThrow(); + }); + + it('requires either criteria or match and variable together', () => { + expect(() => + validateConfig( + firewall({ rules: [{ name: 'rule', match: '^/', variable: 'request_uri', behaviors: [{ type: 'drop' }] }] }), + ), + ).not.toThrow(); + expect(() => + validateConfig(firewall({ rules: [{ name: 'rule', match: '^/', behaviors: [{ type: 'drop' }] }] })), + ).toThrow(); + expect(() => validateConfig(rule({ match: '^/', variable: 'request_uri' }))).toThrow(); + }); + + it('accepts only the variables, operators and conditionals of the firewall', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', operator: 'exists', ...value }] }); + + expect(() => validateConfig(criterion({ variable: '${uri}' }))).toThrow(); + expect(() => validateConfig(criterion({ operator: 'contains' }))).toThrow("The 'operator' field must be one of:"); + expect(() => validateConfig(criterion({ conditional: 'not' }))).toThrow( + "The 'conditional' field must be one of: if, and, or", + ); + }); + + describe('behaviors', () => { + it('accepts deny, drop and bypass (new in v6)', () => { + ['deny', 'drop', 'bypass'].forEach((type) => expect(() => validateConfig(behavior({ type }))).not.toThrow()); + expect(() => validateConfig(behavior({ type: 'allow' }))).toThrow(); + }); + + it('validates set_waf: the mode is logging or blocking in v6 (learning in v4)', () => { + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'logging', wafId: 'my-waf' } })), + ).not.toThrow(); + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'blocking', wafId: 1 } })), + ).not.toThrow(); + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'learning', wafId: 'my-waf' } })), + ).toThrow('The mode must be one of: logging, blocking'); + expect(() => validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'logging' } }))).toThrow( + "Both 'mode' and 'wafId' fields are required in set_waf attributes", + ); + }); + + it('validates set_rate_limit: integers, and only limitBy and averageRateLimit are required', () => { + const rateLimit = (attributes: Record) => behavior({ type: 'set_rate_limit', attributes }); + + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 10 }))).not.toThrow(); + expect(() => + validateConfig( + rateLimit({ type: 'minute', limitBy: 'client_ip', averageRateLimit: 10, maximumBurstSize: null }), + ), + ).not.toThrow(); + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: '10' }))).toThrow( + 'The averageRateLimit must be an integer between 1 and 2147483647', + ); + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 0 }))).toThrow(); + expect(() => + validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 5, maximumBurstSize: '1' })), + ).toThrow('The maximumBurstSize must be an integer between 1 and 2147483647 or null'); + expect(() => validateConfig(rateLimit({ limitBy: 'global' }))).toThrow( + "The 'limitBy' and 'averageRateLimit' fields are required in set_rate_limit behavior attributes.", + ); + expect(() => validateConfig(rateLimit({ type: 'hour', limitBy: 'global', averageRateLimit: 5 }))).toThrow( + 'The rate limit type must be one of: second, minute', + ); + }); + + it('validates set_custom_response: an integer status code and the limits of the content', () => { + const custom = (attributes: Record) => behavior({ type: 'set_custom_response', attributes }); + + expect(() => validateConfig(custom({ statusCode: 403 }))).not.toThrow(); + expect(() => + validateConfig(custom({ statusCode: 200, contentType: 'text/plain', contentBody: 'a'.repeat(500) })), + ).not.toThrow(); + expect(() => validateConfig(custom({ statusCode: '403' }))).toThrow( + 'The statusCode must be an integer between 200 and 499', + ); + expect(() => validateConfig(custom({ statusCode: 500 }))).toThrow(); + expect(() => validateConfig(custom({ statusCode: 403, contentBody: 'a'.repeat(501) }))).toThrow( + 'The contentBody must be a string of at most 500 characters', + ); + expect(() => validateConfig(custom({ statusCode: 403, contentType: 'a'.repeat(256) }))).toThrow( + 'The contentType must be a string of at most 255 characters', + ); + expect(() => validateConfig(custom({}))).toThrow("The 'statusCode' field is required in setCustomResponse"); + }); + + it('validates run_function', () => { + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 'fn' } }))).not.toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 7 } }))).not.toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 0 } }))).toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: {} }))).toThrow( + "The 'value' field is required in run_function behavior attributes.", + ); + }); + + it('requires between 1 and 10 behaviors', () => { + expect(() => validateConfig(rule({ behaviors: [] }))).toThrow( + 'The behaviors must be an array with 1-10 items.', + ); + expect(() => + validateConfig(rule({ behaviors: Array.from({ length: 11 }, () => ({ type: 'bypass' })) })), + ).toThrow('The behaviors must be an array with 1-10 items.'); + }); + }); + + describe('functionsInstances', () => { + const instance = (value: Record) => firewall({ functionsInstances: [value] }); + + it('accepts active (the v6 request has it) and limits the name to 100 characters', () => { + expect(() => validateConfig(instance({ name: 'i', ref: 'fn' }))).not.toThrow(); + expect(() => validateConfig(instance({ name: 'a'.repeat(100), ref: 10 }))).not.toThrow(); + expect(() => validateConfig(instance({ name: 'a'.repeat(101), ref: 'fn' }))).toThrow( + 'The name must be a string between 1 and 100 characters long', + ); + }); + + it('requires name and ref and rejects unknown properties', () => { + expect(() => validateConfig(instance({ name: 'i' }))).toThrow(); + expect(() => validateConfig(instance({ name: 'i', ref: 'fn', unknown: true }))).toThrow( + 'No additional properties are allowed in the firewallFunctionsInstance object', + ); + }); + }); + }); +}); + +describe('validateConfig (v6) networkList', () => { + const list = (extra: Record = {}) => ({ + version: 6, + networkList: [{ name: 'my-list', type: 'ip_cidr', items: ['10.0.0.0/8'], ...extra }], + }); + + it('accepts every type of list, with and without active', () => { + expect(() => validateConfig(list())).not.toThrow(); + expect(() => validateConfig(list({ type: 'asn', items: ['13335'] }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['BR', 'US'] }))).not.toThrow(); + }); + + it('requires name, type and items', () => { + const message = "The 'name', 'type' and 'items' fields are required in each network list item."; + + expect(() => validateConfig({ version: 6, networkList: [{ type: 'asn', items: ['1'] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, networkList: [{ name: 'my-list', items: ['1'] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, networkList: [{ name: 'my-list', type: 'asn' }] })).toThrow(message); + }); + + it('rejects an unknown type and limits the name to 250 characters', () => { + expect(() => validateConfig(list({ type: 'domain' }))).toThrow( + "The 'type' field must be a string. Accepted values are 'ip_cidr', 'asn' or 'countries'.", + ); + expect(() => validateConfig(list({ name: 'a'.repeat(250) }))).not.toThrow(); + expect(() => validateConfig(list({ name: 'a'.repeat(251) }))).toThrow( + "The 'name' field must be a string between 1 and 250 characters.", + ); + }); + + it('requires 1 to 20000 items of 1 to 250 characters each (v6 API)', () => { + expect(() => validateConfig(list({ items: [] }))).toThrow( + "The 'items' field must be an array of strings with 1-20000 items.", + ); + expect(() => validateConfig(list({ items: Array.from({ length: 20000 }, (_, i) => `10.0.${i}.1`) }))).not.toThrow(); + expect(() => validateConfig(list({ items: Array.from({ length: 20001 }, (_, i) => `10.0.${i}.1`) }))).toThrow(); + expect(() => validateConfig(list({ items: [''] }))).toThrow( + "Each item in 'items' must be a string between 1 and 250 characters.", + ); + expect(() => validateConfig(list({ items: ['a'.repeat(251)] }))).toThrow(); + expect(() => validateConfig(list({ items: [13335] }))).toThrow(); + }); + + it('requires the ASN items to be digits only', () => { + expect(() => validateConfig(list({ type: 'asn', items: ['13335', '1'] }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'asn', items: ['AS13335'] }))).toThrow( + 'Each ASN item must be a number composed of digits only.', + ); + expect(() => validateConfig(list({ type: 'asn', items: ['13335', '12.5'] }))).toThrow(); + }); + + it('requires the country items to be two uppercase alphanumeric characters', () => { + expect(() => validateConfig(list({ type: 'countries', items: ['BR', 'US', 'D3'] }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['br'] }))).toThrow( + 'Each country item must be a two-character uppercase alphanumeric code (ISO 3166-1 alpha-2).', + ); + expect(() => validateConfig(list({ type: 'countries', items: ['BRA'] }))).toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['B'] }))).toThrow(); + }); + + it('does not check the format of the ip_cidr items (IPs, CIDRs and expiration dates)', () => { + expect(() => + validateConfig( + list({ + items: ['192.168.0.1', '192.168.0.1/24', '2001:db8::/32', '192.168.0.1 --LT2025-05-29T12:25:23Z'], + }), + ), + ).not.toThrow(); + }); + + it('rejects unknown properties', () => { + expect(() => validateConfig(list({ unknown: true }))).toThrow( + 'No additional properties are allowed in network list items.', + ); + }); +}); + +describe('validateConfig (v6) customPages', () => { + const entry = (extra: Record = {}, attributes: Record = {}) => ({ + code: '404', + page: { attributes: { connector: 'my-connector', ...attributes }, ...extra }, + }); + const customPages = (pages: unknown[], extra: Record = {}) => ({ + version: 6, + customPages: [{ name: 'errors', pages, ...extra }], + }); + + it('accepts a minimal and a complete custom page', () => { + expect(() => validateConfig(customPages([entry()]))).not.toThrow(); + expect(() => + validateConfig( + customPages( + [ + entry({ type: 'page_connector' }, { connector: 10, ttl: 300, uri: '/error.html', customStatusCode: 200 }), + { code: 'default', page: { attributes: { connector: 'my-connector', uri: null, customStatusCode: null } } }, + ], + {}, + ), + ), + ).not.toThrow(); + }); + + it('requires name and pages, and at least one page', () => { + const message = "The 'name' and 'pages' fields are required in each custom page"; + + expect(() => validateConfig({ version: 6, customPages: [{ pages: [entry()] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, customPages: [{ name: 'errors' }] })).toThrow(message); + expect(() => validateConfig(customPages([]))).toThrow( + "The 'pages' field must be an array of 1 to 23 page configurations", + ); + }); + + it('allows up to 23 pages, one for each error code (v6 API limit)', () => { + const codes = [ + 'default', + '400', + '401', + '403', + '404', + '405', + '406', + '408', + '409', + '410', + '411', + '414', + '415', + '416', + '426', + '429', + '431', + '500', + '501', + '502', + '503', + '504', + '505', + ]; + const pages = codes.map((code) => ({ ...entry(), code })); + + expect(() => validateConfig(customPages(pages))).not.toThrow(); + expect(() => validateConfig(customPages([...pages, entry()]))).toThrow( + "The 'pages' field must be an array of 1 to 23 page configurations", + ); + }); + + it('accepts only the error codes of the API', () => { + expect(() => validateConfig(customPages([{ ...entry(), code: '418' }]))).toThrow( + "The 'code' field must be a valid error code", + ); + expect(() => validateConfig(customPages([{ ...entry(), code: 404 }]))).toThrow(); + }); + + it('requires the connector, as a name or an id between 1 and 2147483647', () => { + expect(() => validateConfig(customPages([entry({}, { connector: 1 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 2147483647 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 0 })]))).toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 2147483648 })]))).toThrow(); + expect(() => validateConfig(customPages([{ code: '404', page: { attributes: { ttl: 1 } } }]))).toThrow( + "The 'connector' field is required in page attributes", + ); + }); + + it('validates the ttl and the custom status code', () => { + expect(() => validateConfig(customPages([entry({}, { ttl: 31536000 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { ttl: 31536001 })]))).toThrow( + "The 'ttl' field must be an integer between 0 and 31536000", + ); + expect(() => validateConfig(customPages([entry({}, { ttl: -1 })]))).toThrow(); + expect(() => validateConfig(customPages([entry({}, { customStatusCode: 600 })]))).toThrow( + "The 'customStatusCode' field must be an integer between 100 and 599 or null", + ); + expect(() => validateConfig(customPages([entry({}, { customStatusCode: 99 })]))).toThrow(); + }); + + it('validates the uri: 1 to 250 characters or null, with no pattern (v6 API)', () => { + expect(() => validateConfig(customPages([entry({}, { uri: '/errors/404.html' })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'errors/404 page.html' })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'a'.repeat(250) })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'a'.repeat(251) })]))).toThrow( + "The 'uri' field must be a string between 1 and 250 characters or null", + ); + expect(() => validateConfig(customPages([entry({}, { uri: '' })]))).toThrow(); + }); + + it('accepts only the page_connector type', () => { + expect(() => validateConfig(customPages([entry({ type: 'page_static' })]))).toThrow( + "The 'type' field must be a valid page type", + ); + }); + + it('limits the name to 255 characters and rejects unknown properties', () => { + expect(() => + validateConfig({ version: 6, customPages: [{ name: 'a'.repeat(255), pages: [entry()] }] }), + ).not.toThrow(); + expect(() => validateConfig({ version: 6, customPages: [{ name: 'a'.repeat(256), pages: [entry()] }] })).toThrow( + "The 'name' field must be a string between 1 and 255 characters", + ); + expect(() => validateConfig(customPages([entry()], { unknown: true }))).toThrow( + 'No additional properties are allowed in custom page objects', + ); + expect(() => validateConfig(customPages([{ ...entry(), unknown: true }]))).toThrow( + 'No additional properties are allowed in page entry', + ); + }); +}); + +describe('validateConfig (v6) purge', () => { + describe('purge', () => { + it('accepts the three purge types and both layers', () => { + expect(() => + validateConfig({ + version: 6, + purge: [ + { type: 'url', items: ['https://example.com/a'], layer: 'cache' }, + { type: 'cachekey', items: ['example.com/a'], layer: 'cache' }, + { type: 'wildcard', items: ['https://example.com/*'] }, + ], + }), + ).not.toThrow(); + }); + + it('requires type and items', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url' }] })).toThrow( + "The 'type and items' fields are required in each purge item.", + ); + expect(() => validateConfig({ version: 6, purge: [{ items: ['a'] }] })).toThrow( + "The 'type and items' fields are required in each purge item.", + ); + }); + + it('rejects an unknown type or layer', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'tag', items: ['a'] }] })).toThrow( + "The 'type' field must be either 'url', 'cachekey' or 'wildcard'.", + ); + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: ['a'], layer: 'edge' }] })).toThrow( + "The 'layer' field must be 'cache'.", + ); + }); + + it('requires at least one item and rejects empty items (PurgeRequest)', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: [] }] })).toThrow( + 'The purge items array cannot be empty. At least one item must be specified.', + ); + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: [''] }] })).toThrow( + "Each item in 'items' must have at least 1 character.", + ); + }); + + it('rejects unknown properties in a purge item', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: ['a'], name: 'x' }] })).toThrow( + 'No additional properties are allowed in purge items.', + ); + }); + + it('rejects a purge that is not an array', () => { + expect(() => validateConfig({ version: 6, purge: {} })).toThrow( + "The 'purge' field must be an array of purge items.", + ); + }); + }); +}); + +describe('validateConfig (v6) changes of the current openapi-v6-prod', () => { + describe('active was removed from the requests', () => { + const rejected: Array<[string, Record]> = [ + ['application', { applications: [{ name: 'a', active: true }] }], + [ + 'application rule', + { + applications: [ + { + name: 'a', + rules: { + request: [ + { + name: 'r', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'deliver' }], + }, + ], + }, + }, + ], + }, + ], + [ + 'function instance', + { applications: [{ name: 'a', functionsInstances: [{ name: 'i', ref: 1, active: true }] }] }, + ], + ['function', { functions: [{ name: 'f', path: './f.js', active: true }] }], + [ + 'connector', + { connectors: [{ name: 'c', type: 'live_ingest', active: true, attributes: { region: 'us-east-1' } }] }, + ], + [ + 'connector address', + { connectors: [{ name: 'c', type: 'http', attributes: { addresses: [{ address: 'a.com', active: true }] } }] }, + ], + ['firewall', { firewall: [{ name: 'f', active: true }] }], + [ + 'firewall rule', + { + firewall: [{ name: 'f', rules: [{ name: 'r', active: true, criteria: [], behaviors: [{ type: 'deny' }] }] }], + }, + ], + ['waf', { waf: [{ name: 'w', active: true }] }], + ['network list', { networkList: [{ name: 'n', type: 'countries', items: ['BR'], active: true }] }], + ['custom page', { customPages: [{ name: 'p', active: true, pages: [] }] }], + ['workload', { workloads: [{ name: 'w', active: true }] }], + ]; + + it.each(rejected)('rejects active in a %s', (_name, extra) => { + expect(() => validateConfig({ version: 6, ...extra })).toThrow(); + }); + }); + + it('accepts only true for edgeCacheEnabled (the cache module cannot be disabled)', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', edgeCacheEnabled: true }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', edgeCacheEnabled: false }] })).toThrow(); + }); + + it('limits the name of a device group to letters and numbers', () => { + const group = (name: string) => ({ + version: 6, + applications: [{ name: 'a', deviceGroups: [{ name, userAgent: 'x' }] }], + }); + + expect(() => validateConfig(group('mobile1'))).not.toThrow(); + expect(() => validateConfig(group('my mobile'))).toThrow(); + expect(() => validateConfig(group('my-mobile'))).toThrow(); + }); + + describe('function dependencies', () => { + const fn = (dependencies: unknown) => ({ version: 6, functions: [{ name: 'f', path: './f.js', dependencies }] }); + + it('accepts connectors and network lists by name or ID', () => { + expect(() => + validateConfig( + fn([ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 5 }, + ]), + ), + ).not.toThrow(); + }); + + it('requires type and ref, and rejects another type, an empty ref and more than 20 items', () => { + expect(() => validateConfig(fn([{ type: 'connector' }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'waf', ref: 'x' }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'connector', ref: 0 }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'connector', ref: 1, id: 1 }]))).toThrow(); + expect(() => + validateConfig(fn(Array.from({ length: 21 }, (_, i) => ({ type: 'connector', ref: i + 1 })))), + ).toThrow(); + expect(() => + validateConfig(fn(Array.from({ length: 20 }, (_, i) => ({ type: 'connector', ref: i + 1 })))), + ).not.toThrow(); + }); + }); + + it('accepts the latest deployment policy only in a deployment, not in an environment', () => { + expect(() => + validateConfig({ + version: 6, + deployments: [{ name: 'abc', bindingPolicy: 'FLEXIBLE', deploymentPolicy: 'latest' }], + }), + ).not.toThrow(); + expect(() => validateConfig({ version: 6, environments: [{ name: 'abc', deploymentPolicy: 'latest' }] })).toThrow(); + }); +}); diff --git a/packages/config/src/versions/v6/validateConfig/index.ts b/packages/config/src/versions/v6/validateConfig/index.ts new file mode 100644 index 00000000..aa8d1727 --- /dev/null +++ b/packages/config/src/versions/v6/validateConfig/index.ts @@ -0,0 +1,14 @@ +import { createConfigValidator } from '../../shared/validateConfig'; +import azionConfigSchema from '../schemas/schema'; +import type { AzionConfigV6 } from '../types'; + +/** + * Validates the provided configuration against the v6 JSON Schema. + * If the configuration is not valid, an exception is thrown with the first validation issues encountered. + * @param {AzionConfigV6 | Record} config - The configuration to be validated. + * @param {object} schema - The JSON Schema to be used for validation. Default is the v6 configuration schema. + * @throws {Error} Throws an error if the configuration fails validation. + */ +const validateConfig = createConfigValidator(azionConfigSchema); + +export { validateConfig }; diff --git a/packages/config/src/versions/v6/validateManifest/index.ts b/packages/config/src/versions/v6/validateManifest/index.ts new file mode 100644 index 00000000..92bfa44f --- /dev/null +++ b/packages/config/src/versions/v6/validateManifest/index.ts @@ -0,0 +1,12 @@ +import { createManifestValidator } from '../../shared/validateManifest'; +import { schemaManifest as azionManifestSchema } from '../schemas/schemaManifest'; + +/** + * Validates the provided manifest against the Azion Manifest Schema (API v6). + * @param {Record} manifest - The manifest to be validated. + * @param {object} schema - Optional JSON Schema overriding the default manifest schema. + * @throws {Error} Throws an error if the manifest fails validation. + */ +const validateManifest = createManifestValidator(azionManifestSchema); + +export { validateManifest }; diff --git a/packages/presets/src/presets/angular/config.v6.ts b/packages/presets/src/presets/angular/config.v6.ts new file mode 100644 index 00000000..0fb45cbc --- /dev/null +++ b/packages/presets/src/presets/angular/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/angular/index.ts b/packages/presets/src/presets/angular/index.ts index eb551e1f..c3cdefa3 100644 --- a/packages/presets/src/presets/angular/index.ts +++ b/packages/presets/src/presets/angular/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const angular: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const angular: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/astro/config.v6.ts b/packages/presets/src/presets/astro/config.v6.ts new file mode 100644 index 00000000..6817e2f2 --- /dev/null +++ b/packages/presets/src/presets/astro/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/astro/index.ts b/packages/presets/src/presets/astro/index.ts index 03336589..009cd330 100644 --- a/packages/presets/src/presets/astro/index.ts +++ b/packages/presets/src/presets/astro/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const astro: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const astro: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index e8e1a0b6..7694514b 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -18,6 +18,12 @@ const goldenPresets = readdirSync(goldenDir) .filter((file) => file.endsWith('.input.json')) .map((file) => file.replace('.input.json', '')); +// the v6 API has no `active` in any resource, while the v4 manifest still writes it +const withoutActive = (value: unknown) => + value === undefined + ? undefined + : JSON.parse(JSON.stringify(value, (key, item) => (key === 'active' ? undefined : item))); + const byName = (name: string) => presets.find((preset) => preset.metadata.name === name) as AzionBuildPreset; describe('preset configs by API version', () => { @@ -29,14 +35,156 @@ describe('preset configs by API version', () => { }, ); - it('keeps nitro v4 only, as it did not exist on v3', () => { - expect(getPresetApiVersions(byName('nitro'))).toEqual([4]); + it('keeps nitro without a v3 config, as it did not exist on v3', () => { + expect(getPresetApiVersions(byName('nitro'))).toEqual([4, 6]); expect(() => resolvePresetConfig(byName('nitro'), 3)).toThrow('does not support config version 3'); }); it('has a v3 config for every preset that existed on v3', () => { expect(goldenPresets.length).toBe(24); - goldenPresets.forEach((name) => expect(getPresetApiVersions(byName(name))).toEqual([3, 4])); + goldenPresets.forEach((name) => expect(getPresetApiVersions(byName(name))).toEqual(expect.arrayContaining([3, 4]))); + }); + + describe('v6', () => { + it('is declared by every preset, nitro without a v3 config as it did not exist on v3', () => { + const withoutV6 = presets.filter((preset) => !preset.configs?.[6]).map((preset) => preset.metadata.name); + expect(withoutV6).toEqual([]); + presets.forEach((preset) => + expect(getPresetApiVersions(preset)).toEqual(preset.metadata.name === 'nitro' ? [4, 6] : [3, 4, 6]), + ); + }); + + it.each(presets.map((preset) => [preset.metadata.name, preset] as const))( + '%s: validates and produces the manifest of the v4 config, with the environment, the deployment and the binding of the v6', + (name) => { + const config = resolvePresetConfig(byName(name), 6); + expect(config.version).toBe(6); + expect(() => validateConfig(config)).not.toThrow(); + + // functions (e.g. build.extend) are different instances in each config, so compare through JSON + const plain = (value: unknown) => JSON.parse(JSON.stringify(value)); + const v4 = processConfig(resolvePresetConfig(byName(name), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(plain(v6.build)).toEqual(plain(v4.build)); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(plain(v6.functions)).toEqual(withoutActive(plain(v4.functions))); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + expect(v6).not.toHaveProperty('workload_deployments'); + expect(v6.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); + expect(v6.environments.map((environment: { name: string }) => environment.name)).toEqual(['$ENVIRONMENT_NAME']); + expect(v6.workloads[0].bindings).toEqual([ + { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, + ]); + }, + ); + + it('javascript: validates and keeps the build of the v4 config', () => { + const config = resolvePresetConfig(byName('javascript'), 6); + expect(config.version).toBe(6); + expect(() => validateConfig(config)).not.toThrow(); + expect(config.build).toEqual(resolvePresetConfig(byName('javascript'), 4).build); + const manifest = processConfig(config); + expect(manifest.version).toBe(6); + expect(manifest.build).toEqual({ entry: 'index.js' }); + }); + + it('javascript: has the same functions and application in the manifest as the v4 config', () => { + const v4 = processConfig(resolvePresetConfig(byName('javascript'), 4)); + const v6 = processConfig(resolvePresetConfig(byName('javascript'), 6)); + + expect(v6.functions).toEqual(withoutActive(v4.functions)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + expect(v6.applications[0].modules.functions.enabled).toBe(true); + }); + + it('react: validates and has the same storage, connectors and application in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('react'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('react'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + expect(v6.applications[0].cache_settings).toHaveLength(1); + // the rules deliver the static assets from the storage connector + expect(JSON.stringify(v6.applications[0].rules)).toContain('"set_connector"'); + expect(v6.connectors.map((connector: { name: string }) => connector.name)).toEqual(['$CONNECTOR_NAME']); + }); + + it('eleventy: validates and has the same storage, connectors and application in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('eleventy'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('eleventy'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + expect(v6.applications[0].cache_settings).toHaveLength(1); + expect(v6.storage[0].dir).toBe('./_site'); + }); + + it('opennextjs: validates and has the same storage, connectors, functions and application in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('opennextjs'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('opennextjs'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + // the function keeps the storage binding + expect(v6.functions).toEqual(withoutActive(v4.functions)); + expect(v6.functions[0].bindings).toEqual({ storage: { bucket: '$BUCKET_NAME', prefix: '$BUCKET_PREFIX' } }); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + }); + + it('javascript: binds the workload to an environment and a deployment declared in the config', () => { + const manifest = processConfig(resolvePresetConfig(byName('javascript'), 6)); + + expect(manifest.environments.map((environment: { name: string }) => environment.name)).toEqual([ + '$ENVIRONMENT_NAME', + ]); + expect( + manifest.environments.map((environment: { deployment_policy: string }) => environment.deployment_policy), + ).toEqual(['single_version']); + expect(manifest.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); + expect(manifest.deployments.map((deployment: { binding_policy: string }) => deployment.binding_policy)).toEqual([ + 'FLEXIBLE', + ]); + expect(manifest.workloads).toHaveLength(1); + expect(manifest.workloads[0]).toEqual(expect.objectContaining({ name: '$WORKLOAD_NAME', infrastructure: 1 })); + expect(manifest.workloads[0].bindings).toEqual([ + { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, + ]); + }); + it.each( + ['nuxt', 'svelte', 'nitro'].flatMap((name) => ([4, 6] as const).map((version) => [name, version] as const)), + )( + '%s (v%s): the subpaths rule matches the paths without extension and not the files or the directories', + (name, version) => { + const manifest = processConfig(resolvePresetConfig(byName(name), version)); + const rule = manifest.applications[0].rules.find( + (item: { phase: string; rule: { name: string } }) => + item.phase === 'request' && item.rule.name === 'Redirect to index.html for Subpaths', + ); + const regex = new RegExp(rule.rule.criteria[0][0].argument); + + ['/about', '/docs/intro', '/a.b/c', '/v1.2/page'].forEach((uri) => expect(regex.test(uri)).toBe(true)); + ['/logo.png', '/favicon.ico', '/_nuxt/entry.js', '/file.tar.gz', '/', '/docs/'].forEach((uri) => + expect(regex.test(uri)).toBe(false), + ); + }, + ); }); describe.each(goldenPresets)('%s (v3)', (name) => { @@ -51,7 +199,8 @@ describe('preset configs by API version', () => { const config = resolvePresetConfig(byName(name), 3); expect(() => validateConfig(config)).not.toThrow(); // the golden is JSON, so compare through JSON as well (drops `undefined` fields) - expect(JSON.parse(JSON.stringify(processConfig(config)))).toEqual(golden(name, 'manifest')); + // the fixtures are frozen and do not carry the `version` the v3 manifest has (see v3/__fixtures__/README.md) + expect(JSON.parse(JSON.stringify(processConfig(config)))).toEqual({ version: 3, ...golden(name, 'manifest') }); }); }); diff --git a/packages/presets/src/presets/docusaurus/config.v6.ts b/packages/presets/src/presets/docusaurus/config.v6.ts new file mode 100644 index 00000000..6d2414d2 --- /dev/null +++ b/packages/presets/src/presets/docusaurus/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './build', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/docusaurus/index.ts b/packages/presets/src/presets/docusaurus/index.ts index fa5722f7..0852636b 100644 --- a/packages/presets/src/presets/docusaurus/index.ts +++ b/packages/presets/src/presets/docusaurus/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; @@ -8,7 +9,7 @@ import prebuild from './prebuild'; export const docusaurus: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/eleventy/config.v6.ts b/packages/presets/src/presets/eleventy/config.v6.ts new file mode 100644 index 00000000..afdc6d02 --- /dev/null +++ b/packages/presets/src/presets/eleventy/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './_site', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/eleventy/index.ts b/packages/presets/src/presets/eleventy/index.ts index db34c542..3ef5016d 100644 --- a/packages/presets/src/presets/eleventy/index.ts +++ b/packages/presets/src/presets/eleventy/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const eleventy: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const eleventy: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/emscripten/config.v6.ts b/packages/presets/src/presets/emscripten/config.v6.ts new file mode 100644 index 00000000..7720c9f4 --- /dev/null +++ b/packages/presets/src/presets/emscripten/config.v6.ts @@ -0,0 +1,107 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; +import webpack, { Configuration } from 'webpack'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + bundler: 'webpack', + polyfills: false, + extend: (context: Configuration) => { + context = { + ...context, + optimization: { + minimize: false, + }, + performance: { + maxEntrypointSize: 2097152, + maxAssetSize: 2097152, + }, + module: { + rules: [ + { + test: /\.wasm$/, + type: 'asset/inline', + }, + ], + }, + plugins: [ + new webpack.optimize.LimitChunkCountPlugin({ + maxChunks: 1, + }), + ], + }; + return context; + }, + } as AzionBuild, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/emscripten/index.ts b/packages/presets/src/presets/emscripten/index.ts index 04d5405e..35d77548 100644 --- a/packages/presets/src/presets/emscripten/index.ts +++ b/packages/presets/src/presets/emscripten/index.ts @@ -1,13 +1,14 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; export const emscripten: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/gatsby/config.v6.ts b/packages/presets/src/presets/gatsby/config.v6.ts new file mode 100644 index 00000000..559b1fd7 --- /dev/null +++ b/packages/presets/src/presets/gatsby/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/gatsby/index.ts b/packages/presets/src/presets/gatsby/index.ts index 12b0a936..54dc9e1f 100644 --- a/packages/presets/src/presets/gatsby/index.ts +++ b/packages/presets/src/presets/gatsby/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const gatsby: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const gatsby: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/hexo/config.v6.ts b/packages/presets/src/presets/hexo/config.v6.ts new file mode 100644 index 00000000..559b1fd7 --- /dev/null +++ b/packages/presets/src/presets/hexo/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/hexo/index.ts b/packages/presets/src/presets/hexo/index.ts index 0f8f6f1a..0084ed4c 100644 --- a/packages/presets/src/presets/hexo/index.ts +++ b/packages/presets/src/presets/hexo/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const hexo: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const hexo: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/html/config.v6.ts b/packages/presets/src/presets/html/config.v6.ts new file mode 100644 index 00000000..f1535552 --- /dev/null +++ b/packages/presets/src/presets/html/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './www', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/html/index.ts b/packages/presets/src/presets/html/index.ts index ddd4decb..5243a690 100644 --- a/packages/presets/src/presets/html/index.ts +++ b/packages/presets/src/presets/html/index.ts @@ -1,7 +1,8 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; -export const html: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler }; +export const html: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler }; diff --git a/packages/presets/src/presets/hugo/config.v6.ts b/packages/presets/src/presets/hugo/config.v6.ts new file mode 100644 index 00000000..559b1fd7 --- /dev/null +++ b/packages/presets/src/presets/hugo/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/hugo/index.ts b/packages/presets/src/presets/hugo/index.ts index 6d35d685..c5e5c3f5 100644 --- a/packages/presets/src/presets/hugo/index.ts +++ b/packages/presets/src/presets/hugo/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const hugo: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const hugo: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts new file mode 100644 index 00000000..8e212f9b --- /dev/null +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -0,0 +1,79 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +// TODO: add the remaining v6 resources (connectors, storage...) once their schemas are defined +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + }, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', // path to the edge function. This path is relative to the .edge folder. + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/javascript/index.ts b/packages/presets/src/presets/javascript/index.ts index cb5d7587..1ae396ad 100644 --- a/packages/presets/src/presets/javascript/index.ts +++ b/packages/presets/src/presets/javascript/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; -export const javascript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata }; +export const javascript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata }; diff --git a/packages/presets/src/presets/jekyll/config.v6.ts b/packages/presets/src/presets/jekyll/config.v6.ts new file mode 100644 index 00000000..afdc6d02 --- /dev/null +++ b/packages/presets/src/presets/jekyll/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './_site', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/jekyll/index.ts b/packages/presets/src/presets/jekyll/index.ts index abb44bed..af287d76 100644 --- a/packages/presets/src/presets/jekyll/index.ts +++ b/packages/presets/src/presets/jekyll/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const jekyll: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const jekyll: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/next/config.v6.ts b/packages/presets/src/presets/next/config.v6.ts new file mode 100644 index 00000000..ea9f962d --- /dev/null +++ b/packages/presets/src/presets/next/config.v6.ts @@ -0,0 +1,178 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + polyfills: true, + }, + storage: [ + { + name: '$BUCKET_NAME', + dir: '.edge/next-build-assets', + workloadsAccess: 'read_only', + prefix: '$BUCKET_PREFIX', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Next.js Static Assets and set cache policy', + description: 'Serve Next.js static assets through edge connector and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_next/static/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Serve static assets through edge connector and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json|xml|html)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Next.js Function', + description: 'Execute Next.js edge function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/next/index.ts b/packages/presets/src/presets/next/index.ts index c05255ac..2f374486 100644 --- a/packages/presets/src/presets/next/index.ts +++ b/packages/presets/src/presets/next/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import postbuild from './postbuild'; @@ -8,7 +9,7 @@ import prebuild from './prebuild'; export const next: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/nitro/config.ts b/packages/presets/src/presets/nitro/config.ts index b54384f6..d40a2143 100644 --- a/packages/presets/src/presets/nitro/config.ts +++ b/packages/presets/src/presets/nitro/config.ts @@ -64,7 +64,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/nitro/config.v6.ts b/packages/presets/src/presets/nitro/config.v6.ts new file mode 100644 index 00000000..6b1a3fbb --- /dev/null +++ b/packages/presets/src/presets/nitro/config.v6.ts @@ -0,0 +1,207 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: '.output/server/index.mjs', + polyfills: true, + bundler: 'esbuild', + preset: 'nitro', + } as AzionBuild, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.output/public', + workloadsAccess: 'read_write', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Deliver static assets directly from storage and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|json|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Nitro Function', + description: 'Execute Nitro function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/nitro/index.ts b/packages/presets/src/presets/nitro/index.ts index a1ea67c9..0b64bda5 100644 --- a/packages/presets/src/presets/nitro/index.ts +++ b/packages/presets/src/presets/nitro/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; +import configV6 from './config.v6'; import metadata from './metadata'; import prebuild from './prebuild'; -export const nitro: AzionBuildPreset = { config, configs: { 4: config }, metadata, prebuild }; +export const nitro: AzionBuildPreset = { config, configs: { 4: config, 6: configV6 }, metadata, prebuild }; diff --git a/packages/presets/src/presets/nuxt/config.ts b/packages/presets/src/presets/nuxt/config.ts index 93b84e6a..00df37b7 100644 --- a/packages/presets/src/presets/nuxt/config.ts +++ b/packages/presets/src/presets/nuxt/config.ts @@ -94,7 +94,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/nuxt/config.v6.ts b/packages/presets/src/presets/nuxt/config.v6.ts new file mode 100644 index 00000000..6410ca6c --- /dev/null +++ b/packages/presets/src/presets/nuxt/config.v6.ts @@ -0,0 +1,265 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + preset: 'nuxt', + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: '.output/public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Nuxt Static Assets and set cache policy', + description: 'Serve Nuxt static assets through edge connector and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_nuxt/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Execute Nuxt Function when starts with /api/_content', + description: + 'Handle @nuxt/content API requests - executes Nuxt function for content management endpoints. Remove this rule if your project does not use the @nuxt/content library.', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'starts_with', + argument: '/api/_content', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Deliver static assets directly from storage and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|json|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Nuxt Function', + description: 'Execute Nuxt function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/nuxt/index.ts b/packages/presets/src/presets/nuxt/index.ts index 3c63bcb7..62063bf0 100644 --- a/packages/presets/src/presets/nuxt/index.ts +++ b/packages/presets/src/presets/nuxt/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const nuxt: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const nuxt: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/nuxt/prebuild.ts b/packages/presets/src/presets/nuxt/prebuild.ts index 982ec0e8..97bb1eea 100644 --- a/packages/presets/src/presets/nuxt/prebuild.ts +++ b/packages/presets/src/presets/nuxt/prebuild.ts @@ -2,10 +2,19 @@ import { AzionPrebuildResult, BuildConfiguration, BuildContext } from '@aziontec import { exec } from '@aziontech/utils/node'; import { existsSync } from 'fs'; import { mkdir, readFile, readdir } from 'fs/promises'; +import { dirname, join } from 'path'; const NUXT_CONFIG_FILES = ['nuxt.config.js', 'nuxt.config.ts', 'nuxt.config.mjs', 'nuxt.config.cjs']; const PATHS = { - MANIFEST_DIR: '.nuxt/manifest/meta', + // Candidate locations of the Nuxt app manifest (`/.json`), in priority order: + // 1. final build output, independent of `buildDir` (Nuxt 4.5.x and 4.6.x) + // 2. Nuxt >= 4.6 builds into the cache dir when `.nuxt` already exists + // 3. default `buildDir` (Nuxt <= 4.5.x) + MANIFEST_DIRS: [ + '.output/public/_nuxt/builds/meta', + 'node_modules/.cache/nuxt/.nuxt/manifest/meta', + '.nuxt/manifest/meta', + ], OUTPUT_DIR: '.output/public', SERVER_ENTRY: '.output/server/index.mjs', } as const; @@ -40,11 +49,40 @@ async function readNuxtPreset() { } } -async function readManifest(dirManifest: string) { - const files = await readdir(dirManifest); - const manifestFile = files.find((file) => file.endsWith('.json')); - const manifest = await readFile(`${dirManifest}/${manifestFile}`, 'utf8'); - return JSON.parse(manifest); +async function readManifestFromDir(dirManifest: string) { + let manifestFile: string | undefined; + + // `latest.json` sits next to the `meta` dir and points to the current build id. + // Prefer it to avoid reading a stale manifest when more than one build id is present. + try { + const latest = JSON.parse(await readFile(join(dirname(dirManifest), 'latest.json'), 'utf8')); + if (typeof latest?.id === 'string' && existsSync(join(dirManifest, `${latest.id}.json`))) { + manifestFile = `${latest.id}.json`; + } + } catch { + // no latest.json, fall back to the first manifest file found + } + + if (!manifestFile) { + const files = await readdir(dirManifest); + manifestFile = files.find((file) => file.endsWith('.json')); + } + if (!manifestFile) { + throw new Error(`No manifest file found in ${dirManifest}`); + } + + return JSON.parse(await readFile(join(dirManifest, manifestFile), 'utf8')); +} + +async function readManifest(dirs: readonly string[] = PATHS.MANIFEST_DIRS) { + for (const dir of dirs) { + try { + return await readManifestFromDir(dir); + } catch { + // try next candidate + } + } + throw new Error(`Nuxt manifest not found in: ${dirs.join(', ')}`); } function createAzionPrebuildResult(manifest: Record): AzionPrebuildResult { @@ -79,7 +117,7 @@ async function prebuild(buildConfig: BuildConfiguration, ctx: BuildContext): Pro await mkdir(PATHS.OUTPUT_DIR, { recursive: true }); if (hasNitroPreset) { try { - const manifest = await readManifest(PATHS.MANIFEST_DIR); + const manifest = await readManifest(); configureNitroPreset(buildConfig); return createAzionPrebuildResult(manifest); } catch { @@ -97,7 +135,7 @@ async function prebuild(buildConfig: BuildConfiguration, ctx: BuildContext): Pro verbose: true, }); try { - const manifest = await readManifest(PATHS.MANIFEST_DIR); + const manifest = await readManifest(); configureNitroPreset(buildConfig); return createAzionPrebuildResult(manifest); } catch { diff --git a/packages/presets/src/presets/opennextjs/config.v6.ts b/packages/presets/src/presets/opennextjs/config.v6.ts new file mode 100644 index 00000000..de816d77 --- /dev/null +++ b/packages/presets/src/presets/opennextjs/config.v6.ts @@ -0,0 +1,181 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: '.open-next/worker.js', + polyfills: true, + bundler: 'esbuild', + preset: 'opennextjs', + } as AzionBuild, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_write', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/worker.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Set storage origin for all requests _next_static and set cache policy', + description: 'Serve Next.js static assets through edge connector and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_next/static/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Serve static assets through edge connector and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/opennextjs/index.ts b/packages/presets/src/presets/opennextjs/index.ts index b1f961cf..650b2616 100644 --- a/packages/presets/src/presets/opennextjs/index.ts +++ b/packages/presets/src/presets/opennextjs/index.ts @@ -1,7 +1,13 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; import prebuild from './prebuild'; -export const opennextjs: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, prebuild }; +export const opennextjs: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + prebuild, +}; diff --git a/packages/presets/src/presets/preact/config.v6.ts b/packages/presets/src/presets/preact/config.v6.ts new file mode 100644 index 00000000..cbdb8c84 --- /dev/null +++ b/packages/presets/src/presets/preact/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/preact/index.ts b/packages/presets/src/presets/preact/index.ts index c3a89af3..3d3b01af 100644 --- a/packages/presets/src/presets/preact/index.ts +++ b/packages/presets/src/presets/preact/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const preact: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const preact: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/qwik/config.v6.ts b/packages/presets/src/presets/qwik/config.v6.ts new file mode 100644 index 00000000..cbdb8c84 --- /dev/null +++ b/packages/presets/src/presets/qwik/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/qwik/index.ts b/packages/presets/src/presets/qwik/index.ts index 47204a05..79dc8424 100644 --- a/packages/presets/src/presets/qwik/index.ts +++ b/packages/presets/src/presets/qwik/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const qwik: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const qwik: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts new file mode 100644 index 00000000..cbdb8c84 --- /dev/null +++ b/packages/presets/src/presets/react/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/react/index.ts b/packages/presets/src/presets/react/index.ts index 26634814..ba557dfa 100644 --- a/packages/presets/src/presets/react/index.ts +++ b/packages/presets/src/presets/react/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const react: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const react: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/rustwasm/config.v6.ts b/packages/presets/src/presets/rustwasm/config.v6.ts new file mode 100644 index 00000000..af803187 --- /dev/null +++ b/packages/presets/src/presets/rustwasm/config.v6.ts @@ -0,0 +1,103 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + polyfills: false, + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: '.wasm-bindgen', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/rustwasm/index.ts b/packages/presets/src/presets/rustwasm/index.ts index c0d2359b..f6229d31 100644 --- a/packages/presets/src/presets/rustwasm/index.ts +++ b/packages/presets/src/presets/rustwasm/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; // import postbuild from './postbuild'; import prebuild from './prebuild'; -export const rustwasm: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const rustwasm: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/stencil/config.v6.ts b/packages/presets/src/presets/stencil/config.v6.ts new file mode 100644 index 00000000..f1535552 --- /dev/null +++ b/packages/presets/src/presets/stencil/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './www', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/stencil/index.ts b/packages/presets/src/presets/stencil/index.ts index 6fd83ad2..3207ee48 100644 --- a/packages/presets/src/presets/stencil/index.ts +++ b/packages/presets/src/presets/stencil/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const stencil: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const stencil: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/svelte/config.ts b/packages/presets/src/presets/svelte/config.ts index 1479eea4..07347279 100644 --- a/packages/presets/src/presets/svelte/config.ts +++ b/packages/presets/src/presets/svelte/config.ts @@ -94,7 +94,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/svelte/config.v6.ts b/packages/presets/src/presets/svelte/config.v6.ts new file mode 100644 index 00000000..b9f443f7 --- /dev/null +++ b/packages/presets/src/presets/svelte/config.v6.ts @@ -0,0 +1,236 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + preset: 'svelte', + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './build', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Deliver Immutable Assets and Set Cache Policy', + description: 'Delivers immutable assets and set cache policy.', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'starts_with', + argument: '/_app/immutable', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Deliver Static Assets and Set Cache Policy', + description: 'Deliver static assets directly from storage and set cache policy', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Svelte Function', + description: 'Execute Svelte function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/svelte/index.ts b/packages/presets/src/presets/svelte/index.ts index a56b2147..7ca768b4 100644 --- a/packages/presets/src/presets/svelte/index.ts +++ b/packages/presets/src/presets/svelte/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const svelte: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const svelte: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/typescript/config.v6.ts b/packages/presets/src/presets/typescript/config.v6.ts new file mode 100644 index 00000000..2b9f734b --- /dev/null +++ b/packages/presets/src/presets/typescript/config.v6.ts @@ -0,0 +1,78 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.ts', + }, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', // path to the edge function. This path is relative to the .edge folder. + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/typescript/index.ts b/packages/presets/src/presets/typescript/index.ts index 820c1e05..d1006eb7 100644 --- a/packages/presets/src/presets/typescript/index.ts +++ b/packages/presets/src/presets/typescript/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; -export const typescript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata }; +export const typescript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata }; diff --git a/packages/presets/src/presets/vitepress/config.v6.ts b/packages/presets/src/presets/vitepress/config.v6.ts new file mode 100644 index 00000000..38046f35 --- /dev/null +++ b/packages/presets/src/presets/vitepress/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vitepress/index.ts b/packages/presets/src/presets/vitepress/index.ts index 4a49c6ff..07f0aca1 100644 --- a/packages/presets/src/presets/vitepress/index.ts +++ b/packages/presets/src/presets/vitepress/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const vitepress: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const vitepress: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/vue/config.v6.ts b/packages/presets/src/presets/vue/config.v6.ts new file mode 100644 index 00000000..cbdb8c84 --- /dev/null +++ b/packages/presets/src/presets/vue/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vue/index.ts b/packages/presets/src/presets/vue/index.ts index 8c1e91c5..d32a6817 100644 --- a/packages/presets/src/presets/vue/index.ts +++ b/packages/presets/src/presets/vue/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const vue: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, handler, metadata, prebuild }; +export const vue: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + handler, + metadata, + prebuild, +}; diff --git a/packages/presets/src/presets/vuepress/config.v6.ts b/packages/presets/src/presets/vuepress/config.v6.ts new file mode 100644 index 00000000..38046f35 --- /dev/null +++ b/packages/presets/src/presets/vuepress/config.v6.ts @@ -0,0 +1,74 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vuepress/index.ts b/packages/presets/src/presets/vuepress/index.ts index ca2ce290..505ac9e5 100644 --- a/packages/presets/src/presets/vuepress/index.ts +++ b/packages/presets/src/presets/vuepress/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const vuepress: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const vuepress: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/vite-config/package.json b/packages/vite-config/package.json index aa9c735d..c122fd40 100644 --- a/packages/vite-config/package.json +++ b/packages/vite-config/package.json @@ -19,7 +19,7 @@ "src" ], "peerDependencies": { - "vite": "^7.3.6", + "vite": "^7.3.7", "vite-plugin-dts": "^4.5.4" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0ab510da..7c213884 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,8 +7,8 @@ settings: overrides: lodash: '>=4.18.0' postcss: '>=8.5.18' - fast-uri: '>=4.1.5' - qs: '>=6.15.2' + fast-uri: '>=4.2.3' + qs: '>=6.16.1' esbuild: '>=0.28.1' source-map-js: '>=1.2.2' brace-expansion@1: ^1.1.17 @@ -20,6 +20,10 @@ overrides: '@rushstack/ts-command-line>argparse': ^2.0.1 '@babel/core': '>=7.29.6' '@babel/plugin-transform-modules-systemjs': '>=7.29.4' + handlebars: '>=4.7.10' + vite@7: ^7.3.7 + minimatch@<11.0.1: '>=11.0.1' + glob@<14.0.2: '>=14.0.2' importers: @@ -65,11 +69,11 @@ importers: specifier: ^8.69.0 version: 8.69.0(eslint@10.10.0(jiti@2.6.1))(typescript@5.9.3) vite: - specifier: ^7.3.6 - version: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + specifier: ^7.3.7 + version: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) vite-plugin-dts: specifier: ^4.5.4 - version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)) + version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)) packages/ai: devDependencies: @@ -138,7 +142,7 @@ importers: version: 1.3.8 babel-loader: specifier: ^10.1.1 - version: 10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)) + version: 10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) browserify-zlib: specifier: ^0.2.0 version: 0.2.0 @@ -183,7 +187,7 @@ importers: version: 2.0.12 ts-loader: specifier: ^9.6.2 - version: 9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)) + version: 9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) unenv: specifier: 2.0.0-rc.24 version: 2.0.0-rc.24 @@ -198,7 +202,7 @@ importers: version: 1.1.2 webpack: specifier: ^5.110.3 - version: 5.110.3(esbuild@0.28.2) + version: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) devDependencies: '@aziontech/vite-config': specifier: workspace:* @@ -348,7 +352,7 @@ importers: version: 10.9.2(@types/node@22.20.1)(typescript@5.9.3) webpack: specifier: ^5.110.3 - version: 5.110.3(esbuild@0.28.2) + version: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) packages/cookies: devDependencies: @@ -456,7 +460,7 @@ importers: version: 0.2.17 webpack: specifier: ^5.110.3 - version: 5.110.3 + version: 5.110.3(lightningcss@1.33.0) devDependencies: '@aziontech/vite-config': specifier: workspace:* @@ -631,11 +635,11 @@ importers: packages/vite-config: dependencies: vite: - specifier: ^7.3.6 - version: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + specifier: ^7.3.7 + version: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) vite-plugin-dts: specifier: ^4.5.4 - version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)) + version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)) packages/wasm-image-processor: devDependencies: @@ -1658,9 +1662,8 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} - '@isaacs/cliui@8.0.2': - resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} - engines: {node: '>=12'} + '@isaacs/nonrecursive-glob-match@1.0.3': + resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==} '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} @@ -1918,10 +1921,6 @@ packages: resolution: {integrity: sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==} engines: {node: '>=14.18.0'} - '@pkgjs/parseargs@0.11.0': - resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} - engines: {node: '>=14'} - '@pkgr/core@0.3.6': resolution: {integrity: sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==} engines: {node: ^14.18.0 || >=16.0.0} @@ -2515,10 +2514,6 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} - ansi-regex@6.3.0: - resolution: {integrity: sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==} - engines: {node: '>=12'} - ansi-styles@3.2.1: resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} engines: {node: '>=4'} @@ -2531,10 +2526,6 @@ packages: resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} engines: {node: '>=10'} - ansi-styles@6.2.3: - resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} - engines: {node: '>=12'} - anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -2612,9 +2603,6 @@ packages: peerDependencies: '@babel/core': '>=7.29.6' - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -2627,9 +2615,6 @@ packages: engines: {node: '>=6.0.0'} hasBin: true - brace-expansion@2.1.7: - resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} - brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -2883,9 +2868,6 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} - eastasianwidth@0.2.0: - resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - electron-to-chromium@1.5.422: resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==} @@ -2896,9 +2878,6 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} - emoji-regex@9.2.2: - resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} - enhanced-resolve@5.24.5: resolution: {integrity: sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==} engines: {node: '>=10.13.0'} @@ -3044,8 +3023,8 @@ packages: fast-string-width@3.0.2: resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} - fast-uri@4.2.1: - resolution: {integrity: sha512-TmHQgewjHtMq1E5QKA0tOE0yeYGQs25KZC/ziJpubRtWI15W92e6vPFydWOeZBVROSHBYw/QhD9d5OefdD6LDg==} + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} fast-wrap-ansi@0.2.2: resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} @@ -3098,10 +3077,6 @@ packages: resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} engines: {node: '>= 0.4'} - foreground-child@3.3.1: - resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} - engines: {node: '>=14'} - fraction.js@5.3.4: resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} @@ -3155,13 +3130,8 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob@10.5.0: - resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me - hasBin: true - - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + glob@14.0.3: + resolution: {integrity: sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==} engines: {node: 18 || 20 || >=22} global-directory@4.0.1: @@ -3179,8 +3149,8 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -3358,9 +3328,6 @@ packages: resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} engines: {node: '>=8'} - jackspeak@3.4.3: - resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} - javascript-natural-sort@0.7.1: resolution: {integrity: sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==} @@ -3569,6 +3536,76 @@ packages: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} @@ -3632,9 +3669,6 @@ packages: lodash.upperfirst@4.3.1: resolution: {integrity: sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==} - lru-cache@10.4.3: - resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} - lru-cache@11.5.2: resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} engines: {node: 20 || >=22} @@ -3693,17 +3727,9 @@ packages: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} - minimatch@10.2.3: - resolution: {integrity: sha512-Rwi3pnapEqirPSbWbrZaa6N3nmqq4Xer/2XooiOKyV3q12ML06f7MOuc5DVH8ONZIFhwIYQ3yzPH4nt7iWHaTg==} - engines: {node: 18 || 20 || >=22} - - minimatch@10.2.6: - resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} - engines: {node: 18 || 20 || >=22} - - minimatch@9.0.9: - resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} - engines: {node: '>=16 || 14 >=14.17'} + minimatch@11.0.4: + resolution: {integrity: sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==} + engines: {node: 20 || >=22} minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -3887,9 +3913,6 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} - package-json-from-dist@1.0.1: - resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} - package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} @@ -3930,12 +3953,8 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - path-scurry@1.11.1: - resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} - engines: {node: '>=16 || 14 >=14.18'} - - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} engines: {node: 18 || 20 || >=22} pathe@2.0.3: @@ -4023,8 +4042,8 @@ packages: resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} engines: {node: '>=20'} - qs@6.16.0: - resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} quansync@0.2.11: @@ -4210,10 +4229,6 @@ packages: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} - string-width@5.1.2: - resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} - engines: {node: '>=12'} - string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} @@ -4221,10 +4236,6 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} - strip-ansi@7.2.0: - resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} - engines: {node: '>=12'} - strip-bom@3.0.0: resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} engines: {node: '>=4'} @@ -4467,13 +4478,13 @@ packages: resolution: {integrity: sha512-d4sOM8M/8z7vRXHHq/ebbblfaxENjogAAekcfcDCCwAyvGqnPrc7f4NZbvItS+g4WTgerW0xDwSz5qz11JT3vg==} peerDependencies: typescript: '*' - vite: '*' + vite: ^7.3.7 peerDependenciesMeta: vite: optional: true - vite@7.3.6: - resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==} + vite@7.3.7: + resolution: {integrity: sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -4565,10 +4576,6 @@ packages: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} - wrap-ansi@8.1.0: - resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} - engines: {node: '>=12'} - write-file-atomic@5.0.1: resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -5760,7 +5767,7 @@ snapshots: dependencies: '@eslint/object-schema': 3.0.5 debug: 4.4.3 - minimatch: 10.2.6 + minimatch: 11.0.4 transitivePeerDependencies: - supports-color @@ -5799,14 +5806,7 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} - '@isaacs/cliui@8.0.2': - dependencies: - string-width: 5.1.2 - string-width-cjs: string-width@4.2.3 - strip-ansi: 7.2.0 - strip-ansi-cjs: strip-ansi@6.0.1 - wrap-ansi: 8.1.0 - wrap-ansi-cjs: wrap-ansi@7.0.0 + '@isaacs/nonrecursive-glob-match@1.0.3': {} '@istanbuljs/load-nyc-config@1.1.0': dependencies: @@ -5924,7 +5924,7 @@ snapshots: chalk: 4.1.2 collect-v8-coverage: 1.0.3 exit-x: 0.2.2 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 istanbul-lib-coverage: 3.2.2 istanbul-lib-instrument: 6.0.3 @@ -6071,7 +6071,7 @@ snapshots: '@rushstack/terminal': 0.24.3(@types/node@22.20.1) '@rushstack/ts-command-line': 5.3.13(@types/node@22.20.1) diff: 8.0.4 - minimatch: 10.2.3 + minimatch: 11.0.4 resolve: 1.22.12 semver: 7.7.4 source-map: 0.6.1 @@ -6176,9 +6176,6 @@ snapshots: tslib: 2.8.1 webcrypto-core: 1.9.2 - '@pkgjs/parseargs@0.11.0': - optional: true - '@pkgr/core@0.3.6': {} '@pnpm/deps.graph-sequencer@1100.0.1': {} @@ -6471,7 +6468,7 @@ snapshots: '@typescript-eslint/types': 8.69.0 '@typescript-eslint/visitor-keys': 8.69.0 debug: 4.4.3 - minimatch: 10.2.6 + minimatch: 11.0.4 semver: 7.8.5 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -6604,7 +6601,7 @@ snapshots: '@vue/compiler-vue2': 2.7.16 '@vue/shared': 3.5.42 alien-signals: 0.4.14 - minimatch: 9.0.9 + minimatch: 11.0.4 muggle-string: 0.4.1 path-browserify: 1.0.1 optionalDependencies: @@ -6743,14 +6740,14 @@ snapshots: ajv@8.18.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 4.2.1 + fast-uri: 4.2.3 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 4.2.1 + fast-uri: 4.2.3 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -6762,8 +6759,6 @@ snapshots: ansi-regex@5.0.1: {} - ansi-regex@6.3.0: {} - ansi-styles@3.2.1: dependencies: color-convert: 1.9.3 @@ -6774,8 +6769,6 @@ snapshots: ansi-styles@5.2.0: {} - ansi-styles@6.2.3: {} - anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -6817,12 +6810,12 @@ snapshots: transitivePeerDependencies: - supports-color - babel-loader@10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)): + babel-loader@10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: '@babel/core': 7.29.7 find-up: 5.0.0 optionalDependencies: - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) babel-plugin-istanbul@8.0.0: dependencies: @@ -6887,18 +6880,12 @@ snapshots: babel-plugin-jest-hoist: 30.5.0 babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) - balanced-match@1.0.2: {} - balanced-match@4.0.4: {} base64-js@1.5.1: {} baseline-browser-mapping@2.11.21: {} - brace-expansion@2.1.7: - dependencies: - balanced-match: 1.0.2 - brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -7119,16 +7106,12 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 - eastasianwidth@0.2.0: {} - electron-to-chromium@1.5.422: {} emittery@0.13.1: {} emoji-regex@8.0.0: {} - emoji-regex@9.2.2: {} - enhanced-resolve@5.24.5: dependencies: graceful-fs: 4.2.11 @@ -7233,7 +7216,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 10.2.6 + minimatch: 11.0.4 natural-compare: 1.4.0 optionator: 0.9.4 optionalDependencies: @@ -7311,7 +7294,7 @@ snapshots: dependencies: fast-string-truncated-width: 3.0.3 - fast-uri@4.2.1: {} + fast-uri@4.2.3: {} fast-wrap-ansi@0.2.2: dependencies: @@ -7367,11 +7350,6 @@ snapshots: dependencies: is-callable: 1.2.7 - foreground-child@3.3.1: - dependencies: - cross-spawn: 7.0.6 - signal-exit: 4.1.0 - fraction.js@5.3.4: {} fs-extra@11.3.6: @@ -7423,20 +7401,11 @@ snapshots: dependencies: is-glob: 4.0.3 - glob@10.5.0: - dependencies: - foreground-child: 3.3.1 - jackspeak: 3.4.3 - minimatch: 9.0.9 - minipass: 7.1.3 - package-json-from-dist: 1.0.1 - path-scurry: 1.11.1 - - glob@13.0.6: + glob@14.0.3: dependencies: - minimatch: 10.2.6 + minimatch: 11.0.4 minipass: 7.1.3 - path-scurry: 2.0.2 + path-scurry: 3.0.0 global-directory@4.0.1: dependencies: @@ -7448,7 +7417,7 @@ snapshots: graceful-fs@4.2.11: {} - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -7607,12 +7576,6 @@ snapshots: html-escaper: 2.0.2 istanbul-lib-report: 3.0.1 - jackspeak@3.4.3: - dependencies: - '@isaacs/cliui': 8.0.2 - optionalDependencies: - '@pkgjs/parseargs': 0.11.0 - javascript-natural-sort@0.7.1: {} jest-changed-files@30.5.1: @@ -7677,7 +7640,7 @@ snapshots: chalk: 4.1.2 ci-info: 4.4.0 deepmerge: 4.3.1 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 jest-circus: 30.5.1 jest-docblock: 30.5.0 @@ -7854,7 +7817,7 @@ snapshots: cjs-module-lexer: 2.2.1 collect-v8-coverage: 1.0.3 es-module-lexer: 2.3.2 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 jest-haste-map: 30.5.1 jest-message-util: 30.5.1 @@ -8007,6 +7970,56 @@ snapshots: prelude-ls: 1.2.1 type-check: 0.4.0 + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + optional: true + lines-and-columns@1.2.4: {} load-json-file@4.0.0: @@ -8063,8 +8076,6 @@ snapshots: lodash.upperfirst@4.3.1: {} - lru-cache@10.4.3: {} - lru-cache@11.5.2: {} lru-cache@5.1.1: @@ -8115,37 +8126,33 @@ snapshots: mimic-fn@2.1.0: {} - minimatch@10.2.3: - dependencies: - brace-expansion: 5.0.12 - - minimatch@10.2.6: + minimatch@11.0.4: dependencies: + '@isaacs/nonrecursive-glob-match': 1.0.3 brace-expansion: 5.0.12 - minimatch@9.0.9: - dependencies: - brace-expansion: 2.1.7 - minimist@1.2.8: {} - minimizer-webpack-plugin@5.10.0(esbuild@0.28.2)(webpack@5.110.3(esbuild@0.28.2)): + minimizer-webpack-plugin@5.10.0(esbuild@0.28.2)(lightningcss@1.33.0)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 terser: 5.51.2 - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) optionalDependencies: esbuild: 0.28.2 + lightningcss: 1.33.0 - minimizer-webpack-plugin@5.10.0(webpack@5.110.3): + minimizer-webpack-plugin@5.10.0(lightningcss@1.33.0)(webpack@5.110.3(lightningcss@1.33.0)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 terser: 5.51.2 - webpack: 5.110.3 + webpack: 5.110.3(lightningcss@1.33.0) + optionalDependencies: + lightningcss: 1.33.0 minipass@7.1.3: {} @@ -8246,8 +8253,6 @@ snapshots: p-try@2.2.0: {} - package-json-from-dist@1.0.1: {} - package-manager-detector@1.9.0: {} pako@1.0.11: {} @@ -8280,12 +8285,7 @@ snapshots: path-parse@1.0.7: {} - path-scurry@1.11.1: - dependencies: - lru-cache: 10.4.3 - minipass: 7.1.3 - - path-scurry@2.0.2: + path-scurry@3.0.0: dependencies: lru-cache: 11.5.2 minipass: 7.1.3 @@ -8362,7 +8362,7 @@ snapshots: dependencies: hookified: 2.2.0 - qs@6.16.0: + qs@6.17.1: dependencies: es-define-property: 1.0.1 side-channel: 1.1.1 @@ -8577,12 +8577,6 @@ snapshots: is-fullwidth-code-point: 3.0.0 strip-ansi: 6.0.1 - string-width@5.1.2: - dependencies: - eastasianwidth: 0.2.0 - emoji-regex: 9.2.2 - strip-ansi: 7.2.0 - string_decoder@1.3.0: dependencies: safe-buffer: 5.2.1 @@ -8591,10 +8585,6 @@ snapshots: dependencies: ansi-regex: 5.0.1 - strip-ansi@7.2.0: - dependencies: - ansi-regex: 6.3.0 - strip-bom@3.0.0: {} strip-bom@4.0.0: {} @@ -8633,8 +8623,8 @@ snapshots: test-exclude@7.0.2: dependencies: '@istanbuljs/schema': 0.1.6 - glob: 10.5.0 - minimatch: 10.2.6 + glob: 14.0.3 + minimatch: 11.0.4 text-extensions@2.4.0: {} @@ -8665,7 +8655,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 jest: 30.5.1(@types/node@22.20.1)(ts-node@10.9.2(@types/node@22.20.1)(typescript@5.9.3)) json5: 2.2.3 lodash.memoize: 4.1.2 @@ -8682,13 +8672,13 @@ snapshots: esbuild: 0.28.2 jest-util: 30.5.1 - ts-loader@9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)): + ts-loader@9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: chalk: 4.1.2 picomatch: 4.0.7 source-map: 0.7.6 typescript: 5.9.3 - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) ts-node@10.9.2(@types/node@22.20.1)(typescript@5.9.3): dependencies: @@ -8801,7 +8791,7 @@ snapshots: url@0.11.4: dependencies: punycode: 1.4.1 - qs: 6.16.0 + qs: 6.17.1 util-deprecate@1.0.2: {} @@ -8821,7 +8811,7 @@ snapshots: '@types/istanbul-lib-coverage': 2.0.6 convert-source-map: 2.0.0 - vite-plugin-dts@4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)): + vite-plugin-dts@4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)): dependencies: '@microsoft/api-extractor': 7.59.0(@types/node@22.20.1) '@rollup/pluginutils': 5.4.0(rollup@4.63.1) @@ -8834,13 +8824,13 @@ snapshots: magic-string: 0.30.21 typescript: 5.9.3 optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + vite: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) transitivePeerDependencies: - '@types/node' - rollup - supports-color - vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1): + vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1): dependencies: esbuild: 0.28.2 fdir: 6.5.0(picomatch@4.0.7) @@ -8852,6 +8842,7 @@ snapshots: '@types/node': 22.20.1 fsevents: 2.3.3 jiti: 2.6.1 + lightningcss: 1.33.0 terser: 5.51.2 yaml: 2.9.1 @@ -8875,7 +8866,7 @@ snapshots: webpack-sources@3.5.1: {} - webpack@5.110.3: + webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0): dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 @@ -8890,7 +8881,7 @@ snapshots: events: 3.3.0 graceful-fs: 4.2.11 mime-db: 1.54.0 - minimizer-webpack-plugin: 5.10.0(webpack@5.110.3) + minimizer-webpack-plugin: 5.10.0(esbuild@0.28.2)(lightningcss@1.33.0)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.3 @@ -8914,7 +8905,7 @@ snapshots: - svgo - uglify-js - webpack@5.110.3(esbuild@0.28.2): + webpack@5.110.3(lightningcss@1.33.0): dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 @@ -8929,7 +8920,7 @@ snapshots: events: 3.3.0 graceful-fs: 4.2.11 mime-db: 1.54.0 - minimizer-webpack-plugin: 5.10.0(esbuild@0.28.2)(webpack@5.110.3(esbuild@0.28.2)) + minimizer-webpack-plugin: 5.10.0(lightningcss@1.33.0)(webpack@5.110.3(lightningcss@1.33.0)) neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.3 @@ -8982,12 +8973,6 @@ snapshots: string-width: 4.2.3 strip-ansi: 6.0.1 - wrap-ansi@8.1.0: - dependencies: - ansi-styles: 6.2.3 - string-width: 5.1.2 - strip-ansi: 7.2.0 - write-file-atomic@5.0.1: dependencies: imurmurhash: 0.1.4