import { Config } from "./config"; import Loader from "./loader"; import { QuonfigInitError } from "./initError"; import TelemetryUploader from "./telemetry/uploader"; import type { ConfigValue, Contexts, Duration, EvaluationCallback, EvaluationDetails, EvaluationPayload, InitOptions } from "./types"; /** Default overall init deadline for a client SDK (design doc A.1). */ export declare const DEFAULT_INIT_TIMEOUT = 5000; type PollStatus = { status: "not-started"; } | { status: "pending"; } | { status: "stopped"; } | { status: "running"; frequencyInMs: number; }; export interface QuonfigBootstrap { evaluations: EvaluationPayload["evaluations"]; context: Contexts; } export declare class Quonfig { private _configs; private _telemetryUploader; private _pollCount; private _pollStatus; private _pollTimeoutId; private _pollOutage; private _authFailed; private _pollGeneration; private _instanceHash; private _collectEvaluationSummaries; private evaluationSummaryAggregator; private _hydratedConfigs; private _heldHydratedReads; private _telemetryWired; private _preInitReads; private telemetryReporter; private pageHideListener; private _contexts; private _loggerKey; private _logger; private _customLogger; private _loadedContextSig; private _dataVersion; private _heldGeneration; private _configInstalls; private _stale; private _awaitingSwitchedContext; private _cacheSavedAt; private _subscribers; private _bootstrapConsumed; private _ready; private _initError; private _initGeneration; private _retryGeneration; private _retryTimeoutId; private _backgroundLogTimeoutId; private _initStartedAt; private _initFailedOnce; private _onReady; private _resumeInitRetry; private _latestInit; clientName: string; clientVersion: string; loaded: boolean; loader: Loader | undefined; afterEvaluationCallback: EvaluationCallback; /** * Initialize the SDK. Must be called before any other methods. */ init({ sdkKey, context, domain, apiUrls, apiUrl, telemetryUrl, timeout, hedgeDelay, onInitFailure, initTimeout, afterEvaluationCallback, collectEvaluationSummaries, collectContextMode, loggerKey, logger, telemetryFlushIntervalMs, telemetryTimeoutMs, telemetryMaxRetainedBatches, telemetryMaxRetainedBytes, telemetryMaxRetainedAgeMs, telemetryMaxEvaluationSummaries, }: InitOptions): Promise; /** * The init retry loop (design doc B.3). Attempts a hedged load, retrying with * backoff until config arrives. The returned promise settles: * - resolved on the first live answer or cached last-known-good copy (a * cache counts as config in every mode); * - at `initTimeout` per `mode`: `fail` rejects with QuonfigInitError, * `continue` resolves on code defaults, `wait` keeps waiting. With * `initTimeout <= 0` the policy applies once the first attempt fails; * - at once under `fail` (reject) or `continue` when every leg rejects the * key (401/403/404/410). * The same loop keeps running in the background after it settles, until the * client is ready, so no client is left permanently dead. */ private runInit; /** * Install the cached last-known-good copy for the current context (stale), * if one exists and nothing live is held. Returns whether the client now * serves the cache. */ private installCachedCopy; /** "CACHED CONFIG from ago", or "(age unknown)" for a copy written without a timestamp. */ private cachedConfigLabel; /** Stop the init/background retry loop (it does not settle a pending init()). */ private stopInitRetry; /** * Readiness flips true on the first live answer for the current context * (from any path: init's retry loop, a poll tick, updateContext). Clears the * init error, logs the heal when init had failed, stops the retry loop and * settles a still-pending init(). */ private markReady; /** * Whether the client holds live config: a network answer (or an SSR * bootstrap) for the current context. False before the first answer, while * serving a cached last-known-good copy, and after a failed init until the * background retry (or `poll()`) heals it. */ isReady(): boolean; /** * The `QuonfigInitError` the latest `init()` rejected with * (`onInitFailure: "fail"`), or undefined. Cleared when the client heals. */ get error(): QuonfigInitError | undefined; get configs(): { [key: string]: Config; }; get contexts(): Contexts; get instanceHash(): string; get pollTimeoutId(): NodeJS.Timeout | undefined; get pollCount(): number; get pollStatus(): PollStatus; get telemetryUploader(): TelemetryUploader | undefined; /** The init-time `loggerKey` used by the `shouldLog({loggerPath, ...})` overload. */ get loggerKey(): string | undefined; /** * Monotonic version counter that increments every time the in-memory config * changes (via `setConfig` or `hydrate`). Pair with `subscribe()` and * React's `useSyncExternalStore` to drive re-renders on poll updates. */ get dataVersion(): number; /** * Meta.generation of the config the client is currently holding (0 before the * first install, or when the server predates the watermark). A higher * generation is strictly newer; the reject-older guard compares against it on * every network install path (qfg-7h5d.2.1, spec 5f). */ get heldGeneration(): number; /** * Whether the currently-served config came from the last-known-good * localStorage cache because every API URL was unreachable (spec 5h). When * true the values are non-authoritative; the next successful network load * heals this back to false. `getDetails()` also reports reason "STALE". */ get stale(): boolean; /** * Register a listener invoked synchronously after every config mutation * (poll fetch, `setConfig`, `hydrate`). Returns an unsubscribe function. * * Listeners must not throw — exceptions are swallowed so one bad subscriber * cannot break the others. */ subscribe(listener: () => void): () => void; private notifySubscribers; /** * Internal: load configs from server. */ private load; /** * Apply a loader result to the in-memory config, enforcing the reject-older * install guard (qfg-7h5d.2.1, spec 5f). Shared by `load()` and `poll()` so * the guard lives in exactly one place. `sig` is the encoded signature of the * context that was requested. * * Two orthogonal conditions gate an install: * 1. Did the server return data for us to apply? A 200 (or a 304 whose * cached payload is for a DIFFERENT context than `_configs` currently * holds, after an `updateContext`) does; a 304 for the already-held * context is a no-op. * 2. Is the data new enough to install? A SAME-context refresh runs through * `shouldInstall` — the reject-older watermark check that stops a slow * primary or a failover to a lagging (equal-or-lower generation) * secondary from regressing or flapping an established client. A context * SWITCH is a different query * whose generation is not comparable to the held one, so it always * installs (the "fresh for this context" case — a stale secondary may * seed it, bounded, exactly as the spec allows; the guard must never * strand `updateContext` on the held generation). */ private applyLoaderResult; /** * Canonical reject-older rule for a SAME-context network install (mirrors * sdk-node/src/quonfig.ts:1251 `shouldInstall`). Reject-older is the whole * rule — there is no source ranking (spec 5f point 2): * * - A fresh client (nothing installed yet) accepts the first snapshot, even * an unversioned or stale-secondary one — it has nothing to regress. * - An incoming generation <= 0 (absent, or a server that predates the * watermark) carries no ordering information, so it cannot be rejected as * "older": install it (the carve-out). This is mandatory from day one so * the frontend never repeats the backend's 5-of-6 miss where established * clients froze against gen=0 servers (qfg-7h5d.1.18). * - Otherwise install iff the incoming generation strictly exceeds the held * one. Equal-or-lower is a no-op, so a late failover can't move an * established client backward, an equal second leg can't flap, and a later * newer leg heals forward. * * Both delivery legs emit the honest true commit count (spec 5f.1, revised by * the 2026-06-29 A2 fix): a caught-up secondary matches the held generation * (equal = no-op) and a lagging one is strictly lower, so it is rejected by * the strict-greater check, NOT by the carve-out. Only a truly unversioned * (<= 0) payload takes the carve-out. */ private shouldInstall; /** * Update the context and re-fetch evaluated configs from the server. */ updateContext(context: Contexts, skipLoad?: boolean): Promise; /** * qfg-xiub: on a switch to another context, stop serving the previous * context's values at once, before (and regardless of) the refetch: serve * the new context's last-known-good copy (stale) when there is one, or * nothing (caller defaults) until its fetch lands. Mirrors sdk-swift's * updateContext. A no-op when `sig` is the context already served, or when * nothing has been installed for any context yet. */ private switchServedContext; /** * Start polling the server for config updates at the given frequency. */ poll({ frequencyInMs }: { frequencyInMs: number; }): Promise; /** * Run one poll cycle and apply the auth-failure rule to its outcome (plan * 2026-10-07-sdk-auth-failure-rule R2, R4, R5). `run` performs the hedged * fetch; it reports an auth rejection (every leg failed, primary * 401/403/404/410) and every live 200/304 it installs or confirms. The * returned promise settles as `run`'s does. */ private pollCycle; private doPolling; /** * Stop polling for config updates. Does not stop the init/background retry: * a client that is not ready yet (including a pending `init()` under * `onInitFailure: "wait"`) keeps retrying until config arrives. `close()` * stops everything. */ stopPolling(): void; private stopPollLoop; /** * Drain in-memory telemetry counters by POSTing them to the telemetry * endpoint. Use this when you want to ensure counters are shipped without * tearing down the SDK (e.g. before a context swap in a long-lived SPA). * After a failed POST it respects the 30s resend floor and Retry-After. * Never rejects. */ flush(): Promise; /** * Tear down the SDK: stop polling and the telemetry timer, then send the * current telemetry window once (2s deadline, keepalive). Kept batches from * an earlier failure are not resent. Never rejects and leaves no timer armed. */ close(): Promise; /** * Stop the telemetry timer and abort any in-flight POST without a final * flush. Prefer `close()` or `flush()` for normal teardown. */ stopTelemetry(): void; private teardownTelemetry; private removePageHideListener; /** P7 telemetry logger over the SDK logger; debug is gated by {@link TELEMETRY_LOG_LEVEL_KEY}. */ private telemetryLogger; /** * Set configs from a raw evaluation payload. This is the single install * mutation every network path funnels through; it stamps the held generation * watermark and bumps the install count so the reject-older guard * (`shouldInstall`) can order the next install. Callers on a network path go * through `applyLoaderResult`, which enforces the guard first; `setConfig` * itself installs unconditionally (a local SSR `hydrate`/bootstrap seed is a * source of truth and intentionally skips the guard). */ setConfig(rawValues: EvaluationPayload): void; /** * Seed the client with pre-evaluated flags (e.g. for SSR hydration). * Flags are flat key-value pairs: { flagKey: value }. */ hydrate(flags: Record): void; /** * Extract the current evaluated config as a flat key-value map. */ extract(): Record; /** * Check if a feature flag is enabled: true only for a resolved boolean * `true`. Never throws. Returns false, and logs once per key, for a missing * key, a non-boolean value (no string coercion: a stored "true" is a * string) or a value that could not be read (qfg-zvyy). */ isEnabled(key: string): boolean; /** * Count one evaluation of `key` (its Config is undefined for a missing key) * and, when `fireCallback`, schedule afterEvaluationCallback. Before init() * has wired telemetry, a read of a Config is buffered and replayed by * flushPreInitReads() with the callback init() installs. */ private recordEvaluation; /** Record `count` reads of `config`, holding hydrated (metadata-less) ones. */ private recordToAggregator; /** * Replay reads made before init(): record them and fire the * afterEvaluationCallback init() installed, once per read. */ private flushPreInitReads; /** * After a network install, settle held hydrated reads: a key whose new * Config has the same value is recorded with that Config's metadata; a * different value, or a key the install does not carry, drops them. Keys * still served by their hydrated Config stay held. */ private resolveHeldHydratedReads; /** * Read the evaluated value for a config key without counting it as an * evaluation: no evaluation summary is recorded, `afterEvaluationCallback` * does not fire, and nothing is logged before the client has loaded (the * result is then `undefined`). For framework bindings that read a snapshot * more often than the application consumes the value, such as React's * `useSyncExternalStore`. Application code should use `get()`. */ peek(key: string): ConfigValue; /** * Get the evaluated value for a config key. */ get(key: string): ConfigValue; /** * Return the evaluated value plus OpenFeature-style resolution details * (reason, variant, flagMetadata) for the given key. * * Mirrors sdk-node's `getBoolDetails` / `getStringDetails` etc. so the * openfeature-web provider can populate `variant` and `flagMetadata` per * `project/plans/openfeature-resolution-details.md`. */ getDetails(key: string): EvaluationDetails; /** * Get a duration config. Returns `defaultValue` (undefined when omitted) * for a missing key, and for a value that is not a duration: another type * (a stored string "PT1S" is a string, not a duration) or a value outside * the duration grammar. Never throws; a failed read logs once per key * (qfg-zvyy). */ getDuration(key: string, defaultValue?: Duration): Duration | undefined; private warnedReadFailureKeys; /** * One warning per key per client for a read that returned no value (a * wrong type or a malformed value), so a broken config is not mistaken * for "using the default". Never includes the raw value. */ private warnReadFailure; /** * Determine whether a log message at the given level should be emitted. * * Two shapes are supported: * * 1. `{configKey, ...}` — primitive shape. Evaluates the named config as a * log level. The caller is responsible for any per-logger routing. * * 2. `{loggerPath, ...}` — convenience shape. Requires `loggerKey` on * `init()`. The SDK uses `loggerKey` as the underlying config key. * `loggerPath` does not change the client's context or what is fetched: * the browser SDK evaluates server-side once per fetched context, so every * `loggerPath` gets the same answer from a given config. */ shouldLog(args: { configKey: string; desiredLevel: string; defaultLevel: string; }): boolean; shouldLog(args: { loggerPath: string; desiredLevel: string; defaultLevel?: string; }): boolean; /** * Whether evaluation summary telemetry is being collected. */ isCollectingEvaluationSummaries(): boolean; } /** Singleton instance for convenience. */ export declare const quonfig: Quonfig; export {};