import { Ref, App, InjectionKey } from 'vue'; /** * Minimal HTTP client interface that kita's AsyncStore depends on. * * This is intentionally axios-shaped so an AxiosInstance can be passed * directly without any adapter. Any client matching this duck-type works: * axios, ky, redaxios, or a custom fetch wrapper. * * See `axiosAdapter` if you want explicit typing, or implement this * interface against your client of choice. */ interface HttpResponse { data: T; } interface HttpRequestConfig { /** Query parameters appended to the URL. Loosely typed to mirror axios's `params: any`. */ params?: any; /** AbortSignal for request cancellation. */ signal?: AbortSignal; /** Per-request headers. */ headers?: Record; } interface HttpClient { get(url: string, config?: HttpRequestConfig): Promise>; post(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; put(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; delete(url: string, config?: HttpRequestConfig): Promise>; } /** * Options for findRecords with query caching support. */ interface FindRecordsOptions { /** Whether to use cached results (default: true) */ cache?: boolean; /** Cache TTL in milliseconds (default: 60000 = 1 minute) */ cacheTTL?: number; /** Whether to replace the store contents (default: false) */ replaceStore?: boolean; } declare abstract class AbstractStore { static readonly id: string; protected _records: Ref; protected _recordsById: Map; get records(): T[]; set records(value: T[]); protected abstract reset(): void; abstract findRecord(id: string): T | undefined; abstract _pushRecord(record: T): void; abstract _deleteRecord(record: T): void; abstract _updateRecord(record: T): T; } declare class Store extends AbstractStore { constructor(..._args: any[]); findRecord(id: string): T | undefined; peekRecord(id: string): T | undefined; _pushRecord(record: T): T; _removeRecord(record: T): void; _updateRecord(record: T): T; _deleteRecord(record: T): void; protected reset(): void; } /** * Metadata returned from paginated API responses. */ interface PaginationMeta { page: number; totalPages: number; totalCount: number; hasMore: boolean; } /** * Result from a paginated fetch operation. */ interface PaginatedResult { records: T[]; meta: PaginationMeta; } /** * Manages paginated data fetching with automatic page tracking. * * State is backed by Vue `ref`s so the getters are reactive: read `hasMore` / * `isLoading` / `page` in a template or `computed` and they update as pages * load, even when the query instance is held in a `shallowRef`. */ declare class PaginatedQuery { private fetcher; private _currentPage; private _hasMore; private _isLoading; private _totalCount; private _totalPages; constructor(fetcher: (page: number) => Promise>); /** Whether more pages are available to load */ get hasMore(): boolean; /** Whether a fetch is currently in progress */ get isLoading(): boolean; /** Current page number (1-indexed) */ get page(): number; /** Total number of records across all pages (if known) */ get totalCount(): number; /** Total number of pages (if known) */ get totalPages(): number; /** * Load the next page of results. * Returns empty array if no more pages or already loading. */ loadMore(): Promise; /** * Reset pagination state to fetch from the beginning. */ reset(): void; } /** * Deduplicates in-flight requests by tracking pending promises. * When multiple callers request the same resource simultaneously, * only one network request is made and the result is shared. */ declare class RequestTracker { private pending; /** * Execute a request with deduplication. If a request with the same key * is already in flight, returns the existing promise instead of starting a new one. */ dedupe(key: string, request: () => Promise): Promise; /** * Check if a request with the given key is currently in flight. */ hasPending(key: string): boolean; /** * Clear all pending requests (useful for cleanup/reset). */ clear(): void; } interface ConstructorArgs { APIUrl?: string; } declare class AsyncStore { static readonly id: string; protected readonly _records: Ref; protected readonly _recordsById: Map; protected readonly client: TClient; protected page: number; protected nextPage: number; protected APIUrl: string; protected requestTracker: RequestTracker; private queryCache; private nextTemporaryId; private readonly pendingCreates; constructor(client: TClient, args: ConstructorArgs); get records(): T[]; set records(value: T[]); get stores(): Record | AsyncStore>; protected get modelType(): typeof AsyncModel; protected reset(): void; /** * Synchronous cache read — no fetch. Reactive per key, so it is safe inside * computeds/watchers even on a cache miss. */ peekRecord(id: string): T | undefined; /** * Find a single record by ID. Returns the cached record if present, * otherwise fetches from the API and caches it. * * Concurrent requests for the same record are deduplicated. * * @param id - Record ID to fetch * @param params - Query parameters for the request * @param revalidate - Force a refetch even if a cached record exists */ findRecord(id: string, params?: Record, revalidate?: boolean): Promise; /** * Fetch a record from the API and merge it into the local cache. * Exposed as `protected` so SWR/custom subclasses can hook into the fetch path. */ protected _fetchAndCacheRecord(id: string, params: Record): Promise; /** * Find multiple records with query caching support. * Deduplicates concurrent requests with the same params. * * @param params - Query parameters for the request * @param options - Cache options or boolean for legacy replaceStore */ findRecords(params?: Record, options?: FindRecordsOptions | boolean): Promise<{ records: T[]; meta?: Record; }>; /** * Invalidate all cached query results. * Optionally provide a predicate to selectively invalidate. */ invalidateQueries(predicate?: (params: Record) => boolean): void; /** * Persist a record. POSTs if the record is new (no id), PUTs otherwise. * Returns the server-confirmed record. * * Higher-level than the protected `_createRecord` / `_updateRecord` — * normal consumer code should call this (or `model.save()`). */ save(record: T): Promise; /** * Delete a record. Removes locally if the record is new (no id), * otherwise issues a DELETE then removes locally. * * Higher-level than the protected `_deleteRecord` — normal consumer * code should call this (or `model.delete()`). */ delete(record: T): Promise; protected _updateRecord(record: T): Promise; /** * POST a record and merge the server response onto it. Store membership is * left to the caller, so both the `save()` path and the optimistic path can * share the request. * * @param record - The model instance to persist and merge the response into * @param payload - Request body; defaults to the record's current state */ protected _postRecord(record: T, payload?: string): Promise; protected _createRecord(record: T): Promise; protected _deleteRecord(record: T): Promise; _removeRecord(record: T): void; _pushRecord(record: T): T; /** * Create a record optimistically - adds to store immediately, syncs with server. * Rolls back on error. * * The record instance itself is inserted under a temporary id and stays in * `records` for the whole round-trip, so it keeps its prototype and never * flickers out of the list. On success only the `_recordsById` key is swapped * from the temporary id to the server id. * * The pending record carries the temporary id, so it is *not* `isNew` while * the POST is in flight — do not call `save()` / `delete()` on it until this * promise settles. Re-entrant calls for the same instance (a double-submitted * form) share the in-flight request rather than issuing a second POST. * * @param record - A record not yet in the store; pass an existing one to `save()` * @throws If the store already holds this instance under its current id */ optimisticCreate(record: T): Promise; /** * Update a record optimistically - applies changes immediately, syncs with server. * Rolls back to previous state on error. */ optimisticUpdate(record: T): Promise; /** * Delete a record optimistically - removes from store immediately, syncs with server. * * On error the original model instance is restored at its previous position, so * references the caller still holds stay valid and keep their model behaviour. */ optimisticDelete(record: T): Promise; /** * Create a paginated query helper for fetching records in pages. * Handles page tracking, loading state, and hasMore detection. * * @param params - Base query parameters (page will be added automatically) * @returns PaginatedQuery instance with loadMore(), reset(), and state getters */ createPaginatedQuery(params?: Record): PaginatedQuery; } declare class Model extends AbstractModel { store: Store; static create(this: new (params: Record) => T, params?: U): T & U; } declare abstract class AbstractModel { static id: string; readonly id: string; /** `!this.id` — a record with no id has never been persisted. */ get isNew(): boolean; toString(): string; constructor(params: Record); get stores(): Record | AsyncStore>; serialize(removeKeys?: string[]): string; } declare class AsyncModel extends AbstractModel { store: AsyncStore; get stores(): ApplicationStore; save(): Promise; /** * Apply a partial patch and persist. Equivalent to `Object.assign(this, patch); await this.save();`. * * @example * await user.update({ email: "new@example.com" }); */ update(patch: Record): Promise; delete(): Promise; static create(this: new (params: Record) => T, params?: U): T & U; } /** * Register a model class with the ModelStoreRegistry. * Call this in a static initialization block in your model class. * * @example * ```typescript * export default class UserModel extends AsyncModel { * static readonly id = "users"; * static { registerModel(this); } * } * ``` */ declare function registerModel(modelClass: T): void; /** * @deprecated Use `registerModel(this)` in a `static {}` initialization block instead. * `connectToStore` will be removed in a future major release. * * @example * // Old (deprecated): * @connectToStore * class UserModel extends AsyncModel { … } * * // New: * class UserModel extends AsyncModel { * static { registerModel(this); } * } */ declare function connectToStore(cls: T): void; /** * Symbol-based injection key for the ApplicationStore. Used by kita's own * `useStore` helper. Exported so advanced consumers can write their own * inject() calls without colliding on a string key like `"store"`. */ declare const KITA_STORE_KEY: InjectionKey; declare class ApplicationStore { client: TClient; [key: string]: any; constructor(client: TClient); registerStore | typeof AsyncStore>(StoreClass: T): this; getStore | AsyncStore>(recordType: string): T; install(app: App): void; } declare function createStore ApplicationStore>(appStoreClass: T, client: ConstructorParameters[0]): { appStore: InstanceType; useStore: () => InstanceType; }; declare function createAndRegisterStore ApplicationStore>(appStoreClass: T, modelStores: Array | typeof AsyncStore>, client: ConstructorParameters[0]): { appStore: InstanceType; useStore: () => InstanceType; }; /** * Use to define a reactive property on an object. Creates a getter and setter on the target * object that maintain a Vue ref under the hood. * * Example usage (Stage 3 decorators): * @reactive() * accessor reactiveArray: string[] = []; * * Note: The decorator argument is optional and ignored for backwards compatibility. * The initial value comes from the class field initializer. */ declare function reactive(_defaultValue?: unknown): (_target: ClassAccessorDecoratorTarget, _context: ClassAccessorDecoratorContext) => ClassAccessorDecoratorResult; declare const _default: { install(app: App /** options = {} */): Promise | undefined; }; /** * Options for stale-while-revalidate `findRecord`. */ interface FindRecordOptions { /** Milliseconds before data is considered stale (default: 0 = always stale) */ staleTime?: number; /** Force background revalidation even if data is fresh */ revalidate?: boolean; } /** * Opt-in stale-while-revalidate variant of {@link AsyncStore}. * * Extends `AsyncStore` with per-record freshness tracking. `findRecord` * returns cached data immediately when present, then revalidates in the * background when the record is older than `staleTime` or when * `revalidate: true` is passed. * * If you don't need SWR semantics, extend {@link AsyncStore} directly — * it has simpler typing and a smaller surface. * * @example * ```ts * class UserStore extends AsyncStoreSWR { * static readonly id = "users"; * } * * // Returns cached user instantly if < 30s old; refetches in background otherwise. * await users.findRecord("u-1", {}, { staleTime: 30_000 }); * ``` */ declare class AsyncStoreSWR extends AsyncStore { protected recordTimestamps: Map; private pendingRevalidations; protected reset(): void; /** * Returns true if the record doesn't exist locally or is older than `staleTime`. */ isRecordStale(id: string, staleTime: number): boolean; /** * Drop the record's freshness timestamp so the next `findRecord` refetches. * Does not remove the record from the local cache. */ invalidateRecord(id: string): void; /** * Find a single record by ID with stale-while-revalidate semantics. * * - If a fresh cached record exists, returns it immediately. * - If a stale cached record exists, returns it immediately and revalidates in the background. * - If no cached record exists, awaits the fetch. * * @param id - Record ID to fetch * @param params - Query parameters for the request * @param options - SWR options, or `true` for the legacy "force revalidate" boolean form */ findRecord(id: string, params?: Record, options?: FindRecordOptions | boolean): Promise; /** * Called when a *background* revalidation fails. The default implementation is a * deliberate no-op: under stale-while-revalidate a failed refresh is non-fatal — * the caller already has the stale record and the record stays stale, so the next * `findRecord` retries. * * Override it to surface the failure to your error reporter. A rejection from the * awaited path (no cached record) still propagates to the caller and does not * reach this hook. * * Fires once per background revalidation, not once per caller: concurrent * `findRecord` calls for the same record share a single refresh. An error thrown by * an override is swallowed — a failing reporter must not become the unhandled * rejection this hook exists to prevent. * * @param _error - Rejection value from the background fetch * @param _id - ID of the record being revalidated * * @example * ```ts * class UserStore extends AsyncStoreSWR { * static readonly id = "users"; * * protected onRevalidationError(error: unknown, id: string) { * Sentry.captureException(error, { tags: { store: "users", recordId: id } }); * } * } * ``` */ protected onRevalidationError(_error: unknown, _id: string): void; private revalidateInBackground; /** * Override the base fetch to stamp the record with a fresh timestamp. * * The stamp lands only after `super` resolves, so a failed fetch leaves the * previous timestamp untouched and the record stays stale. */ protected _fetchAndCacheRecord(id: string, params: Record): Promise; } /** * Execute an optimistic update with automatic rollback on error. * * @param optimisticAction - Function that performs the optimistic UI update and returns a snapshot for rollback * @param serverAction - Function that performs the actual server request * @param rollback - Function that restores the previous state using the snapshot * @returns The result from the server action * @throws Re-throws any error from the server action after rolling back */ declare function withOptimisticUpdate(optimisticAction: () => TSnapshot, serverAction: () => Promise, rollback: (snapshot: TSnapshot) => void): Promise; /** * Configuration for a {@link QueryCache}. */ interface QueryCacheOptions { /** * Milliseconds an entry stays valid for. Must be a positive integer. * Defaults to `60_000`. */ ttl?: number; /** * Maximum number of entries to retain. Once exceeded, the oldest entries are * evicted. Must be a positive integer. Defaults to `100`. */ maxSize?: number; } /** * Caches query results with TTL-based expiration and invalidation support. * * Optionally carries response metadata (`M`) alongside the records — e.g. * pagination meta — so a cache hit can return it via {@link QueryCache.getEntry}. * * The cache is bounded: every {@link QueryCache.set} first sweeps expired * entries, then evicts from the oldest end until `size <= maxSize`. This keeps * high-cardinality params (a search box caching per keystroke, per-user filters, * pagination cursors) from growing the cache forever. * * Eviction is insertion-order (FIFO), not LRU: reading an entry does not refresh * its recency, only re-writing it does. */ declare class QueryCache> { private cache; private defaultTTL; private maxSize; /** * Create a cache with a custom TTL in milliseconds, or the default TTL (60s) * and max size (100 entries) when omitted. * * @throws {RangeError} If `ttl` is not a positive integer. */ constructor(ttl?: number); /** * Create a cache with a custom TTL and/or max size. * * @throws {RangeError} If `ttl` or `maxSize` is not a positive integer. */ constructor(options?: QueryCacheOptions); /** * Create a stable cache key from query parameters. * Sorts keys to ensure consistent ordering. */ private makeKey; /** * Get cached records if a valid (unexpired) entry exists, else null. */ get(params: Record, ttl?: number): T[] | null; /** * Get the full cached entry — records plus any stored metadata — if a valid * (unexpired) entry exists, else null. Use this when the cached query carried * response metadata (e.g. pagination meta) you need on a cache hit. */ getEntry(params: Record, ttl?: number): { data: T[]; meta?: M; } | null; private deleteExpiredEntries; private enforceMaximumSize; /** * Store data in the cache, optionally with response metadata. * * Sweeps expired entries and evicts the oldest ones if the write pushes the * cache past `maxSize`. Re-writing an existing key makes it the newest entry. * * Pass `ttl` to give this entry a lifetime other than the cache's default. The * sweep honours each entry's own ttl, so a longer-lived entry survives writes * to unrelated keys. */ set(params: Record, data: T[], meta?: M, ttl?: number): void; /** * Check if a cache entry exists and is still valid. */ has(params: Record, ttl?: number): boolean; /** * Invalidate cache entries. * If no predicate is provided, clears all entries. * If a predicate is provided, only clears entries where predicate returns true. */ invalidate(predicate?: (params: Record) => boolean): void; /** * Get the number of cached entries. */ get size(): number; /** * Clear all cached entries. */ clear(): void; } export { AbstractModel, AbstractStore, ApplicationStore, AsyncModel, AsyncStore, AsyncStoreSWR, type FindRecordOptions, type FindRecordsOptions, type HttpClient, type HttpRequestConfig, type HttpResponse, KITA_STORE_KEY, Model, PaginatedQuery, type PaginatedResult, type PaginationMeta, QueryCache, type QueryCacheOptions, RequestTracker, Store, connectToStore, createAndRegisterStore, createStore, _default as dataStorePlugin, reactive, registerModel, withOptimisticUpdate };