import { literalUnion, valita_exports } from "../../../shared/src/valita.js";
import { singleProcessMode } from "../types/processes.js";
import { DEFAULT_PREFERRED_PREFIXES } from "./network.js";
import { assertNormalized, isDevelopmentMode } from "./normalize.js";
import { logOptions } from "../../../otel/src/log-options.js";
import { flagToEnv, parseOptions } from "../../../shared/src/options.js";
import package_default from "../../../zero/package.js";
import { runtimeDebugFlags } from "../../../zql/src/builder/debug-delegate.js";
import { ALLOWED_APP_ID_CHARACTERS, INVALID_APP_ID_MESSAGE } from "../types/shards.js";
import { timingSafeEqual } from "node:crypto";
//#region ../zero-cache/src/config/zero-config.ts
var ZERO_ENV_VAR_PREFIX = "ZERO_";
var appOptions = {
	id: {
		type: valita_exports.string().default("zero").assert((id) => ALLOWED_APP_ID_CHARACTERS.test(id), INVALID_APP_ID_MESSAGE),
		desc: [
			"Unique identifier for the app.",
			"",
			"Multiple zero-cache apps can run on a single upstream database, each of which",
			"is isolated from the others, with its own permissions, sharding (future feature),",
			"and change/cvr databases.",
			"",
			"The metadata of an app is stored in an upstream schema with the same name,",
			"e.g. \"zero\", and the metadata for each app shard, e.g. client and mutation",
			"ids, is stored in the \"\\{app-id\\}_\\{#\\}\" schema. (Currently there is only a single",
			"\"0\" shard, but this will change with sharding).",
			"",
			"The CVR and Change data are managed in schemas named \"\\{app-id\\}_\\{shard-num\\}/cvr\"",
			"and \"\\{app-id\\}_\\{shard-num\\}/cdc\", respectively, allowing multiple apps and shards",
			"to share the same database instance (e.g. a Postgres \"cluster\") for CVR and Change management.",
			"",
			"Due to constraints on replication slot names, an App ID may only consist of",
			"lower-case letters, numbers, and the underscore character.",
			"",
			"Note that this option is used by both {bold zero-cache} and {bold zero-deploy-permissions}."
		]
	},
	publications: {
		type: valita_exports.array(valita_exports.string()).optional(() => []),
		desc: [
			`Postgres {bold PUBLICATION}s that define the tables and columns to`,
			`replicate. Publication names may not begin with an underscore,`,
			`as zero reserves that prefix for internal use.`,
			``,
			`If unspecified, zero-cache will create and use an internal publication that`,
			`publishes all tables in the {bold public} schema, i.e.:`,
			``,
			`CREATE PUBLICATION _\\{app-id\\}_public_0 FOR TABLES IN SCHEMA public;`,
			``,
			`Note that changing the set of publications will result in resyncing the replica,`,
			`which may involve downtime (replication lag) while the new replica is initializing.`,
			`To change the set of publications without disrupting an existing app, a new app`,
			`should be created.`
		]
	}
};
var shardOptions = {
	id: {
		type: valita_exports.string().assert(() => {
			throw new Error(`ZERO_SHARD_ID is no longer an option. Please use ZERO_APP_ID instead.`);
		}).optional(),
		hidden: true
	},
	num: {
		type: valita_exports.number().default(0),
		desc: [
			`The shard number (from 0 to NUM_SHARDS) of the App. zero will eventually`,
			`support data sharding as a first-class primitive; until then, deploying`,
			`multiple shard-nums creates functionally identical shards. Until sharding is`,
			`actually meaningful, this flag is hidden but available for testing.`
		],
		hidden: true
	}
};
var replicaOptions = {
	file: {
		type: valita_exports.string().default("zero.db"),
		desc: [
			`File path to the SQLite replica that zero-cache maintains.`,
			`This can be lost, but if it is, zero-cache will have to re-replicate next`,
			`time it starts up.`
		]
	},
	vacuumIntervalHours: {
		type: valita_exports.number().optional(),
		desc: [
			`Performs a VACUUM at server startup if the specified number of hours has elapsed`,
			`since the last VACUUM (or initial-sync). The VACUUM operation is heavyweight`,
			`and requires double the size of the db in disk space. If unspecified, VACUUM`,
			`operations are not performed.`
		]
	}
};
var perUserMutationLimit = {
	max: {
		type: valita_exports.number().optional(),
		desc: [`The maximum mutations per user within the specified {bold windowMs}.`, `If unset, no rate limiting is enforced.`]
	},
	windowMs: {
		type: valita_exports.number().default(6e4),
		desc: [`The sliding window over which the {bold perUserMutationLimitMax} is enforced.`]
	}
};
var authOptions = {
	jwk: {
		type: valita_exports.string().optional(),
		desc: [`A public key in JWK format used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`],
		deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
	},
	jwksUrl: {
		type: valita_exports.string().optional(),
		desc: [`A URL that returns a JWK set used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`],
		deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
	},
	secret: {
		type: valita_exports.string().optional(),
		desc: [`A symmetric key used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`],
		deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
	},
	issuer: {
		type: valita_exports.string().optional(),
		desc: [`Expected issuer ({bold iss} claim) for JWT validation.`, `If set, tokens with a different or missing issuer will be rejected.`],
		deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
	},
	audience: {
		type: valita_exports.string().optional(),
		desc: [`Expected audience ({bold aud} claim) for JWT validation.`, `If set, tokens with a different or missing audience will be rejected.`],
		deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
	},
	revalidateIntervalSeconds: {
		type: valita_exports.number().optional(),
		desc: [`The interval in seconds between periodic /query auth revalidation for validated connections.`, `If unset, periodic auth revalidation is disabled.`]
	},
	retransformIntervalSeconds: {
		type: valita_exports.number().optional(),
		desc: [`The interval in seconds between periodic shared /query retransform work for a client group.`, `If unset, periodic shared retransform is disabled.`]
	}
};
var makeDeprecationMessage = (flag) => `Use {bold ${flagToEnv(ZERO_ENV_VAR_PREFIX, flag)}} (or {bold --${flag}}) instead.`;
var makeMutatorQueryOptions = (replacement, suffix) => ({
	url: {
		type: valita_exports.array(valita_exports.string()).optional(),
		desc: [
			`The URL of the API server to which zero-cache will ${suffix}.`,
			``,
			`{bold IMPORTANT:} URLs are matched using {bold URLPattern}, a standard Web API.`,
			``,
			`{bold Pattern Syntax:}`,
			`  URLPattern uses a simple and intuitive syntax similar to Express routes.`,
			`  Wildcards and named parameters make it easy to match multiple URLs.`,
			``,
			`{bold Basic Examples:}`,
			`  Exact URL match:`,
			`    "https://api.example.com/mutate"`,
			`  `,
			`  Any subdomain using wildcard:`,
			`    "https://*.example.com/mutate"`,
			`  `,
			`  Multiple subdomain levels:`,
			`    "https://*.*.example.com/mutate"`,
			`  `,
			`  Any path under a domain:`,
			`    "https://api.example.com/*"`,
			`  `,
			`  Named path parameters:`,
			`    "https://api.example.com/:version/mutate"`,
			`    ↳ Matches "https://api.example.com/v1/mutate", "https://api.example.com/v2/mutate", etc.`,
			``,
			`{bold Advanced Patterns:}`,
			`  Optional path segments:`,
			`    "https://api.example.com/:path?"`,
			`  `,
			`  Regex in segments (for specific patterns):`,
			`    "https://api.example.com/:version(v\\\\d+)/mutate"`,
			`    ↳ Matches only "v" followed by digits`,
			``,
			`{bold Multiple patterns:}`,
			`  ["https://api1.example.com/mutate", "https://api2.example.com/mutate"]`,
			``,
			`{bold Note:} Query parameters and URL fragments (#) are automatically ignored during matching.`,
			``,
			`For full URLPattern syntax, see: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern`
		],
		...replacement ? { deprecated: [makeDeprecationMessage(`${replacement}-url`)] } : {}
	},
	apiKey: {
		type: valita_exports.string().optional(),
		desc: [`An optional secret used to authorize zero-cache to call the API server handling writes.`],
		...replacement ? { deprecated: [makeDeprecationMessage(`${replacement}-api-key`)] } : {}
	},
	forwardCookies: {
		type: valita_exports.boolean().default(false),
		desc: [
			`If true, zero-cache will forward cookies from the request.`,
			`This is useful for passing authentication cookies to the API server.`,
			`If false, cookies are not forwarded.`
		],
		...replacement ? { deprecated: [makeDeprecationMessage(`${replacement}-forward-cookies`)] } : {}
	},
	allowedClientHeaders: {
		type: valita_exports.array(valita_exports.string()).optional(),
		desc: [
			`A list of header names that clients are allowed to set via custom headers.`,
			`If specified, only headers in this list will be forwarded to the ${suffix === "push mutations" ? "push" : "query"} URL.`,
			`Header names are case-insensitive.`,
			`If not specified, no client-provided headers are forwarded (secure by default).`,
			`Example: ZERO_${replacement ? replacement.toUpperCase() : suffix === "push mutations" ? "MUTATE" : "QUERY"}_ALLOWED_CLIENT_HEADERS=x-request-id,x-correlation-id`
		],
		...replacement ? { deprecated: [makeDeprecationMessage(`${replacement}-allowed-client-headers`)] } : {}
	}
});
var mutateOptions = makeMutatorQueryOptions(void 0, "push mutations");
var pushOptions = makeMutatorQueryOptions("mutate", "push mutations");
var queryOptions = makeMutatorQueryOptions(void 0, "send synced queries");
var getQueriesOptions = makeMutatorQueryOptions("query", "send synced queries");
var zeroOptions = {
	upstream: {
		db: {
			type: valita_exports.string(),
			desc: [`The "upstream" authoritative postgres database.`, `In the future we will support other types of upstream besides PG.`]
		},
		type: {
			type: literalUnion("pg", "custom").default("pg"),
			desc: [
				`The meaning of the {bold upstream-db} depends on the upstream type:`,
				`* {bold pg}: The connection database string, e.g. "postgres://..."`,
				`* {bold custom}: The base URI of the change source "endpoint, e.g.`,
				`          "https://my-change-source.dev/changes/v0/stream?apiKey=..."`
			],
			hidden: true
		},
		maxConns: {
			type: valita_exports.number().default(20),
			desc: [
				`The maximum number of connections to open to the upstream database`,
				`for committing mutations. This is divided evenly amongst sync workers.`,
				`In addition to this number, zero-cache uses one connection for the`,
				`replication stream.`,
				``,
				`Note that this number must allow for at least one connection per`,
				`sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`
			]
		},
		maxConnsPerWorker: {
			type: valita_exports.number().optional(),
			hidden: true
		},
		pgReplicationSlotFailover: {
			type: valita_exports.boolean().optional(),
			desc: [
				`For upstream Postgres versions 17+, creates replication slots with the`,
				`{bold failover} parameter set to {bold true} to enable slot synchronization`,
				`and failover. Note that additional Postgres-level configuration is necessary`,
				`when enabling this option. For details, see:`,
				``,
				`https://www.postgresql.org/docs/current/logicaldecoding-explanation.html#LOGICALDECODING-REPLICATION-SLOTS-SYNCHRONIZATION`,
				``,
				`(Note that this option has no effect for Postgres versions before 17.)`
			]
		}
	},
	push: pushOptions,
	mutate: mutateOptions,
	getQueries: getQueriesOptions,
	query: queryOptions,
	enableCrudMutations: {
		type: valita_exports.boolean().default(true),
		desc: [
			`Enables support for legacy CRUD mutations. When this is {bold false}, no connections`,
			`are made from view-syncers to the upstream db, and push messages with CRUD mutations`,
			`result in an InvalidPush response.`
		]
	},
	cvr: {
		db: {
			type: valita_exports.string().optional(),
			desc: [
				`The Postgres database used to store CVRs. CVRs (client view records) keep track`,
				`of the data synced to clients in order to determine the diff to send on reconnect.`,
				`If unspecified, the {bold upstream-db} will be used.`
			]
		},
		maxConns: {
			type: valita_exports.number().default(30),
			desc: [
				`The maximum number of connections to open to the CVR database.`,
				`This is divided evenly amongst sync workers.`,
				``,
				`Note that this number must allow for at least one connection per`,
				`sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`
			]
		},
		maxConnsPerWorker: {
			type: valita_exports.number().optional(),
			hidden: true
		},
		garbageCollectionInactivityThresholdHours: {
			type: valita_exports.number().default(48),
			desc: [
				`The duration after which an inactive CVR is eligible for garbage collection.`,
				`Note that garbage collection is an incremental, periodic process which does not`,
				`necessarily purge all eligible CVRs immediately.`
			]
		},
		garbageCollectionInitialIntervalSeconds: {
			type: valita_exports.number().default(60),
			desc: [
				`The initial interval at which to check and garbage collect inactive CVRs.`,
				`This interval is increased exponentially (up to 16 minutes) when there is`,
				`nothing to purge.`
			]
		},
		garbageCollectionInitialBatchSize: {
			type: valita_exports.number().default(25),
			desc: [
				`The initial number of CVRs to purge per garbage collection interval.`,
				`This number is increased linearly if the rate of new CVRs exceeds the rate of`,
				`purged CVRs, in order to reach a steady state.`,
				``,
				`Setting this to 0 effectively disables CVR garbage collection.`
			]
		}
	},
	queryHydrationStats: {
		type: valita_exports.boolean().optional(),
		desc: [
			`Track and log the number of rows considered by query hydrations which`,
			`take longer than {bold log-slow-hydrate-threshold} milliseconds.`,
			`This is useful for debugging and performance tuning.`
		]
	},
	enableQueryPlanner: {
		type: valita_exports.boolean().default(true),
		desc: [
			`Enable the query planner for optimizing ZQL queries.`,
			``,
			`The query planner analyzes and optimizes query execution by determining`,
			`the most efficient join strategies.`,
			``,
			`You can disable the planner if it is picking bad strategies.`
		]
	},
	yieldThresholdMs: {
		type: valita_exports.number().default(10),
		desc: [
			`The maximum amount of time in milliseconds that a sync worker will`,
			`spend in IVM (processing query hydration and advancement) before yielding`,
			`to the event loop. Lower values increase responsiveness and fairness at`,
			`the cost of reduced throughput.`
		]
	},
	change: {
		db: {
			type: valita_exports.string().optional(),
			desc: [
				`The Postgres database used to store recent replication log entries, in order`,
				`to sync multiple view-syncers without requiring multiple replication slots on`,
				`the upstream database. If unspecified, the {bold upstream-db} will be used.`
			]
		},
		maxConns: {
			type: valita_exports.number().default(5),
			desc: [
				`The maximum number of connections to open to the change database.`,
				`This is used by the {bold change-streamer} for catching up`,
				`{bold zero-cache} replication subscriptions.`
			]
		}
	},
	replica: replicaOptions,
	log: logOptions,
	app: appOptions,
	shard: shardOptions,
	auth: authOptions,
	port: {
		type: valita_exports.number().default(4848),
		desc: [`The port for sync connections.`]
	},
	changeStreamer: {
		uri: {
			type: valita_exports.string().optional(),
			desc: [
				`When set, connects to the {bold change-streamer} at the given URI.`,
				`In a multi-node setup, this should be specified in {bold view-syncer} options,`,
				`pointing to the {bold replication-manager} URI, which runs a {bold change-streamer}`,
				`on port 4849.`
			]
		},
		mode: {
			type: literalUnion("dedicated", "discover").default("dedicated"),
			desc: [
				`As an alternative to {bold ZERO_CHANGE_STREAMER_URI}, the {bold ZERO_CHANGE_STREAMER_MODE}`,
				`can be set to "{bold discover}" to instruct the {bold view-syncer} to connect to the `,
				`ip address registered by the {bold replication-manager} upon startup.`,
				``,
				`This may not work in all networking configurations, e.g. certain private `,
				`networking or port forwarding configurations. Using the {bold ZERO_CHANGE_STREAMER_URI}`,
				`with an explicit routable hostname is recommended instead.`,
				``,
				`Note: This option is ignored if the {bold ZERO_CHANGE_STREAMER_URI} is set.`
			]
		},
		port: {
			type: valita_exports.number().optional(),
			desc: [
				`The port on which the {bold change-streamer} runs. This is an internal`,
				`protocol between the {bold replication-manager} and {bold view-syncers}, which`,
				`runs in the same process tree in local development or a single-node configuration.`,
				``,
				`If unspecified, defaults to {bold --port} + 1.`
			]
		},
		address: {
			type: valita_exports.string().optional(),
			deprecated: [`Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`],
			hidden: true
		},
		protocol: {
			type: literalUnion("ws", "wss").default("ws"),
			deprecated: [`Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`],
			hidden: true
		},
		discoveryInterfacePreferences: {
			type: valita_exports.array(valita_exports.string()).default([...DEFAULT_PREFERRED_PREFIXES]),
			desc: [
				`The name prefixes to prefer when introspecting the network interfaces to determine`,
				`the externally reachable IP address for change-streamer discovery. This defaults`,
				`to commonly used names for standard ethernet interfaces in order to prevent selecting`,
				`special interfaces such as those for VPNs.`
			],
			hidden: true
		},
		startupDelayMs: {
			type: valita_exports.number().default(15e3),
			desc: [
				`The delay to wait before the change-streamer takes over the replication stream`,
				`(i.e. the handoff during replication-manager updates), to allow loadbalancers to register`,
				`the task as healthy based on healthcheck parameters. Note that if a change stream request`,
				`is received during this interval, the delay will be canceled and the takeover will happen`,
				`immediately, since the incoming request indicates that the task is registered as a target.`
			]
		},
		backPressureLimitHeapProportion: {
			type: valita_exports.number().default(.04),
			desc: [
				`The percentage of {bold --max-old-space-size} to use as a buffer for absorbing replication`,
				`stream spikes. When the estimated amount of queued data exceeds this threshold, back pressure`,
				`is applied to the replication stream, delaying downstream sync as a result.`,
				``,
				`The threshold was determined empirically with load testing. Higher thresholds have resulted`,
				`in OOMs. Note also that the byte-counting logic in the queue is strictly an underestimate of`,
				`actual memory usage (but importantly, proportionally correct), so the queue is actually`,
				`using more than what this proportion suggests.`,
				``,
				`This parameter is exported as an emergency knob to reduce the size of the buffer in the`,
				`event that the server OOMs from back pressure. Resist the urge to {italic increase} this`,
				`proportion, as it is mainly useful for absorbing periodic spikes and does not meaningfully`,
				`affect steady-state replication throughput; the latter is determined by other factors such`,
				`as object serialization and PG throughput`,
				``,
				`In other words, the back pressure limit does not constrain replication throughput;`,
				`rather, it protects the system when the upstream throughput exceeds the downstream`,
				`throughput.`
			]
		},
		flowControlConsensusPaddingSeconds: {
			type: valita_exports.number().default(1),
			desc: [
				`During periodic flow control checks (every 64kb), the amount of time to wait after the`,
				`majority of subscribers have acked, after which replication will continue even if`,
				`some subscribers have yet to ack. (Note that this is not a timeout for the {italic entire} send,`,
				`but a timeout that starts {italic after} the majority of receivers have acked.)`,
				``,
				`This allows a bounded amount of time for backlogged subscribers to catch up on each flush`,
				`without forcing all subscribers to wait for the entire backlog to be processed. It is also`,
				`useful for mitigating the effect of unresponsive subscribers due to severed websocket`,
				`connections (until liveness checks disconnect them).`,
				``,
				`Set this to a negative number to disable early flow control releases. (Not recommended, but`,
				`available as an emergency measure.)`
			]
		}
	},
	taskID: {
		type: valita_exports.string().optional(),
		desc: [
			`Globally unique identifier for the zero-cache instance.`,
			``,
			`Setting this to a platform specific task identifier can be useful for debugging.`,
			`If unspecified, zero-cache will attempt to extract the TaskARN if run from within`,
			`an AWS ECS container, and otherwise use a random string.`
		]
	},
	perUserMutationLimit,
	numSyncWorkers: {
		type: valita_exports.number().optional(),
		desc: [
			`The number of processes to use for view syncing.`,
			`Leave this unset to use the maximum available parallelism.`,
			`If set to 0, the server runs without sync workers, which is the`,
			`configuration for running the {bold replication-manager}.`
		]
	},
	autoReset: {
		type: valita_exports.boolean().default(true),
		desc: [
			`Automatically wipe and resync the replica when replication is halted.`,
			`This situation can occur for configurations in which the upstream database`,
			`provider prohibits event trigger creation, preventing the zero-cache from`,
			`being able to correctly replicate schema changes. For such configurations,`,
			`an upstream schema change will instead result in halting replication with an`,
			`error indicating that the replica needs to be reset.`,
			``,
			`When {bold auto-reset} is enabled, zero-cache will respond to such situations`,
			`by shutting down, and when restarted, resetting the replica and all synced `,
			`clients. This is a heavy-weight operation and can result in user-visible`,
			`slowness or downtime if compute resources are scarce.`
		]
	},
	replicationLag: { reportIntervalMs: {
		type: valita_exports.number().default(3e4),
		desc: [
			`The minimum interval at which replication lag reports are written upstream and`,
			`reported via the {bold zero.replication.total_lag} opentelemetry metric. Because`,
			`replication lag reports are only issued after the previous one was received, the`,
			`actual interval between reports may be longer when there is a backlog in the`,
			`replication stream. A negative or 0 value disables lag reporting.`,
			``,
			`This monitoring feature is only support on the postgres upstream type.`
		]
	} },
	adminPassword: {
		type: valita_exports.string().optional(),
		desc: [
			`A password used to administer zero-cache server, for example to access the`,
			`/statz endpoint.`,
			"",
			"A password is optional in development mode but {bold required in production} mode."
		]
	},
	websocketCompression: {
		type: valita_exports.boolean().default(false),
		desc: [
			"Enable WebSocket per-message deflate compression.",
			"",
			"Compression can reduce bandwidth usage for sync traffic but",
			"increases CPU usage on both client and server. Disabled by default.",
			"",
			"See: https://github.com/websockets/ws#websocket-compression"
		]
	},
	websocketCompressionOptions: {
		type: valita_exports.string().optional(),
		desc: [
			"JSON string containing WebSocket compression options.",
			"",
			"Only used if websocketCompression is enabled.",
			"",
			"Example: \\{\"zlibDeflateOptions\":\\{\"level\":3\\},\"threshold\":1024\\}",
			"",
			"See https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback for available options."
		]
	},
	websocketMaxPayloadBytes: {
		type: valita_exports.number().default(10 * 1024 * 1024),
		desc: [
			"Maximum size of incoming WebSocket messages in bytes.",
			"",
			"Messages exceeding this limit are rejected before parsing.",
			"Default: 10MB (10 * 1024 * 1024 = 10485760)"
		]
	},
	litestream: {
		executable: {
			type: valita_exports.string().optional(),
			desc: [
				`Path to the {bold litestream} executable. This must be built from the`,
				`{bold rocicorp/litestream} fork. Support for the official binary at v0.5.x`,
				`is planned.`
			]
		},
		executableV5: {
			type: valita_exports.string().optional(),
			desc: [
				`The v0.5.x litestream executable which is used for restoring the backup`,
				`backup when {bold ZERO_LITESTREAM_RESTORE_USING_V5} is specified.`,
				`litestream v0.5.8+ can restore from both v0.3.x and v0.5.x backup formats,`,
				`affording forwards compatibility with a future zero-cache`,
				`version that will use litestream v0.5.x to backup the replica.`
			]
		},
		restoreUsingV5: {
			type: valita_exports.boolean().default(false),
			desc: [`Restores the backup using the {bold ZERO_LITESTREAM_EXECUTABLE_V5} if specified.`]
		},
		configPath: {
			type: valita_exports.string().default("./src/services/litestream/config.yml"),
			desc: [
				`Path to the litestream yaml config file. zero-cache will run this with its`,
				`environment variables, which can be referenced in the file via $\\{ENV\\}`,
				`substitution, for example:`,
				`* {bold ZERO_REPLICA_FILE} for the db path`,
				`* {bold ZERO_LITESTREAM_BACKUP_LOCATION} for the db replica url`,
				`* {bold ZERO_LITESTREAM_LOG_LEVEL} for the log level`,
				`* {bold ZERO_LOG_FORMAT} for the log type`
			]
		},
		logLevel: { type: literalUnion("debug", "info", "warn", "error").default("warn") },
		backupURL: {
			type: valita_exports.string().optional(),
			desc: [
				`The location of the litestream backup, usually an {bold s3://} URL.`,
				`This is only consulted by the {bold replication-manager}.`,
				`{bold view-syncers} receive this information from the {bold replication-manager}.`
			]
		},
		endpoint: {
			type: valita_exports.string().optional(),
			desc: [`The S3-compatible endpoint URL to use for the litestream backup. Only required for non-AWS services.`, `The {bold replication-manager} and {bold view-syncers} must have the same endpoint.`]
		},
		port: {
			type: valita_exports.number().optional(),
			desc: [
				`Port on which litestream exports metrics, used to determine the replication`,
				`watermark up to which it is safe to purge change log records.`,
				``,
				`If unspecified, defaults to {bold --port} + 2.`
			]
		},
		checkpointThresholdMB: {
			type: valita_exports.number().default(40),
			desc: [
				`The size of the WAL file at which to perform an SQlite checkpoint to apply`,
				`the writes in the WAL to the main database file. Each checkpoint creates`,
				`a new WAL segment file that will be backed up by litestream. Smaller thresholds`,
				`may improve read performance, at the expense of creating more files to download`,
				`when restoring the replica from the backup.`
			]
		},
		minCheckpointPageCount: {
			type: valita_exports.number().optional(),
			desc: [
				`The WAL page count at which SQLite attempts a PASSIVE checkpoint, which`,
				`transfers pages to the main database file without blocking writers.`,
				`Defaults to {bold checkpointThresholdMB * 250} (since SQLite page size is 4KB).`
			]
		},
		maxCheckpointPageCount: {
			type: valita_exports.number().optional(),
			desc: [
				`The WAL page count at which SQLite performs a RESTART checkpoint, which`,
				`blocks writers until complete. Defaults to {bold minCheckpointPageCount * 10}.`,
				`Set to {bold 0} to disable RESTART checkpoints entirely.`
			]
		},
		incrementalBackupIntervalMinutes: {
			type: valita_exports.number().default(15),
			desc: [
				`The interval between incremental backups of the replica. Shorter intervals`,
				`reduce the amount of change history that needs to be replayed when catching`,
				`up a new view-syncer, at the expense of increasing the number of files needed`,
				`to download for the initial litestream restore.`
			]
		},
		snapshotBackupIntervalHours: {
			type: valita_exports.number().default(12),
			desc: [
				`The interval between snapshot backups of the replica. Snapshot backups`,
				`make a full copy of the database to a new litestream generation. This`,
				`improves restore time at the expense of bandwidth. Applications with a`,
				`large database and low write rate can increase this interval to reduce`,
				`network usage for backups (litestream defaults to 24 hours).`
			]
		},
		restoreParallelism: {
			type: valita_exports.number().default(48),
			desc: [`The number of WAL files to download in parallel when performing the`, `initial restore of the replica from the backup.`]
		},
		multipartConcurrency: {
			type: valita_exports.number().default(48),
			desc: [`The number of parts (of size {bold --litestream-multipart-size} bytes)`, `to upload or download in parallel when backing up or restoring the snapshot.`]
		},
		multipartSize: {
			type: valita_exports.number().default(16 * 1024 * 1024),
			desc: [
				`The size of each part when uploading or downloading the snapshot with`,
				`{bold --multipart-concurrency}. Note that up to {bold concurrency * size}`,
				`bytes of memory are used when backing up or restoring the snapshot.`
			]
		}
	},
	storageDBTmpDir: {
		type: valita_exports.string().optional(),
		desc: [`tmp directory for IVM operator storage. Leave unset to use os.tmpdir()`]
	},
	initialSync: {
		tableCopyWorkers: {
			type: valita_exports.number().default(5),
			desc: [
				`The number of parallel workers used to copy tables during initial sync.`,
				`Each worker uses a database connection and will buffer up to (approximately)`,
				`10 MB of table data in memory during initial sync. Increasing the number of`,
				`workers may improve initial sync speed; however, note that local disk throughput`,
				`(i.e. IOPS), upstream CPU, and network bandwidth may also be bottlenecks.`
			]
		},
		profileCopy: {
			type: valita_exports.boolean().optional(),
			hidden: true,
			desc: [`Takes a cpu profile during the copy phase initial-sync, storing it as a JSON file`, `initial-copy.cpuprofile in the tmp directory.`]
		},
		textCopy: {
			type: valita_exports.boolean().default(false),
			desc: [
				`Use text-format COPY instead of binary COPY for the initial sync.`,
				`This is slower but can work around issues with binary encoding of`,
				`certain data types.`
			]
		}
	},
	targetClientRowCount: {
		type: valita_exports.number().default(2e4),
		deprecated: [
			"This option is no longer used and will be removed in a future version.",
			"The client-side cache no longer enforces a row limit. Instead, TTL-based expiration",
			"automatically manages cache size to prevent unbounded growth."
		],
		hidden: true
	},
	lazyStartup: {
		type: valita_exports.boolean().default(false),
		desc: [
			"Delay starting the majority of zero-cache until first request.",
			"",
			"This is mainly intended to avoid connecting to Postgres replication stream",
			"until the first request is received, which can be useful i.e., for preview instances.",
			"",
			"Currently only supported in single-node mode."
		]
	},
	serverVersion: {
		type: valita_exports.string().optional(),
		desc: [`The version string outputted to logs when the server starts up.`]
	},
	enableTelemetry: {
		type: valita_exports.boolean().default(true),
		desc: [
			`Set to false to opt out of telemetry collection.`,
			``,
			`This helps us improve Zero by collecting anonymous usage data.`,
			`Setting the DO_NOT_TRACK environment variable also disables telemetry.`
		]
	},
	cloudEvent: {
		sinkEnv: {
			type: valita_exports.string().optional(),
			desc: [
				`ENV variable containing a URI to a CloudEvents sink. When set, ZeroEvents`,
				`will be published to the sink as the {bold data} field of CloudEvents.`,
				`The {bold source} field of the CloudEvents will be set to the {bold ZERO_TASK_ID},`,
				`along with any extension attributes specified by the {bold ZERO_CLOUD_EVENT_EXTENSION_OVERRIDES_ENV}.`,
				``,
				`This configuration is modeled to easily integrate with a knative K_SINK binding,`,
				`(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,
				`However, any CloudEvents sink can be used.`
			]
		},
		extensionOverridesEnv: {
			type: valita_exports.string().optional(),
			desc: [
				`ENV variable containing a JSON stringified object with an {bold extensions} field`,
				`containing attributes that should be added or overridden on outbound CloudEvents.`,
				``,
				`This configuration is modeled to easily integrate with a knative K_CE_OVERRIDES binding,`,
				`(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`
			]
		}
	}
};
var loadedConfig;
function getZeroConfig(opts = {}) {
	if (!loadedConfig || singleProcessMode()) {
		loadedConfig = parseOptions(zeroOptions, {
			envNamePrefix: ZERO_ENV_VAR_PREFIX,
			emitDeprecationWarnings: false,
			...opts
		});
		if (loadedConfig.queryHydrationStats) runtimeDebugFlags.trackRowCountsVended = true;
	}
	return loadedConfig;
}
/**
* Same as {@link getZeroConfig}, with an additional check that the
* config has already been normalized (i.e. by the top level server/runner).
*/
function getNormalizedZeroConfig(opts = {}) {
	const config = getZeroConfig(opts);
	assertNormalized(config);
	return config;
}
/**
* Gets the server version from the config if provided. Otherwise it gets it
* from the Zero package.json.
*/
function getServerVersion(config) {
	return config?.serverVersion ?? package_default.version;
}
function isAdminPasswordValid(lc, config, password) {
	if (!password && !config.adminPassword && isDevelopmentMode()) {
		warnOnce(lc, "No admin password set; allowing access in development mode only");
		return true;
	}
	if (!config.adminPassword) {
		lc.warn?.("No admin password set; denying access");
		return false;
	}
	const passwordBuffer = Buffer.from(password ?? "");
	const configBuffer = Buffer.from(config.adminPassword);
	if (passwordBuffer.length !== configBuffer.length) {
		timingSafeEqual(configBuffer, configBuffer);
		lc.warn?.("Invalid admin password");
		return false;
	}
	if (!timingSafeEqual(passwordBuffer, configBuffer)) {
		lc.warn?.("Invalid admin password");
		return false;
	}
	lc.debug?.("Admin password accepted");
	return true;
}
var hasWarned = false;
function warnOnce(lc, msg) {
	if (!hasWarned) {
		lc.warn?.(msg);
		hasWarned = true;
	}
}
//#endregion
export { ZERO_ENV_VAR_PREFIX, appOptions, getNormalizedZeroConfig, getServerVersion, getZeroConfig, isAdminPasswordValid, shardOptions, zeroOptions };

//# sourceMappingURL=zero-config.js.map