import { type Database } from "./database.js"; import { type SiteDataAccessMode, type SiteDataGuestAccess, type SiteDataRole } from "./site-data-policy.js"; export * from "./site-data-policy.js"; export type SiteDataErrorCode = "validation" | "conflict" | "not_found" | "forbidden" | "quota_exceeded" | "rate_limited"; export declare class SiteDataError extends Error { readonly code: SiteDataErrorCode; readonly details: Record; constructor(code: SiteDataErrorCode, message: string, details?: Record); } export type SiteDataScope = { accountId: string; workspaceId: string; siteId: string; }; /** * Who is calling. `principal` owns records (the person, or the person an agent * acts for); `actor` is recorded as the writer. `framed` marks requests from * Site HTML: they are always viewers and never manage collections. */ export type SiteDataCaller = SiteDataScope & { role: SiteDataRole; principal: string; actor: string; framed: boolean; /** * An anonymous guest of a published Site (`guest:`): a framed * viewer that reaches only what each collection's guest rule allows, and * no files. */ guest?: boolean; /** * How many automation hops led to this write (0 for people, a scheduled * run's chain depth for its agents), recorded on change events so * automations reacting to them can stop loops. */ chainDepth?: number; /** The automation and run that caused this write, recorded on App change events. */ automationId?: string | null; automationRunId?: string | null; }; /** What kind of change a Site Data transaction made. */ export type SiteDataChangeKind = "write" | "import" | "reset" | "collection" | "files"; /** The pseudo-collection name change hints use for the Site's files. */ export declare const SITE_DATA_FILES_CHANGE = "$files"; /** Record ids a change event keeps; more set `truncated`. */ export declare const SITE_DATA_CHANGE_RECORD_IDS = 20; /** Change events kept per Site (the newest). */ export declare const SITE_DATA_CHANGES_KEPT = 200; /** * A committed change to a Site's data, reported to the store's change * listener after the transaction commits, and only while the Site has a live * listener (see `watch`). It names collections, never record data. */ export type SiteDataChange = SiteDataScope & { seq: number; kind: SiteDataChangeKind; collections: string[]; }; export type SiteDataChangeListener = (change: SiteDataChange) => void; export type SiteDataStoreOptions = { /** Called after each committed change while the Site is watched; must not throw. */ onChange?: SiteDataChangeListener; }; /** Each started 5 ms of schema validation counts one more write operation. */ export declare const SITE_DATA_VALIDATION_MS_PER_OPERATION = 5; /** What a write's admission needs to know to reserve validation time. */ export type SiteDataValidationAdmission = { /** Collections whose records the request validates. */ collections?: readonly string[]; /** Whether the request compiles a schema itself (defining a collection with one). */ schema?: boolean; /** Validation time to reserve for what the request sends, capped at its budget. */ reserveMs: number; /** * Stored records the request merges into and then validates whole * (patches and increments). Their stored size, in collections with a * schema, adds `reserveMsPerStoredByte` per byte to the reservation, up to * `maxReserveMs`; a record that does not exist adds nothing. */ touched?: readonly SiteDataTouchedRecord[]; reserveMsPerStoredByte?: number; maxReserveMs?: number; }; /** A stored record a write merges into: its collection and id or key. */ export type SiteDataTouchedRecord = { collection: string; } & SiteDataRecordRef; /** * Validation time a write reserved at admission, and the one-minute window * (epoch seconds of its start) it was reserved in; null when nothing was. */ export type SiteDataValidationReservation = { reservedMs: number; windowStartedAt: number | null; }; export type SiteDataLimits = { recordBytesPerSite: number; maxRecordBytes: number; maxCollectionsPerSite: number; fileBytesPerSite: number; maxFileBytes: number; workspaceBytes: number; maxRecordsPerCollection: number; viewerWritesPerMinute: number; siteWritesPerMinute: number; viewerReadsPerMinute: number; /** Write operations per minute by all of a Site's managers (API and agent tools). */ managerWritesPerMinute: number; /** Schema-validation milliseconds per minute for one Site. */ siteValidationMsPerMinute: number; /** Schema-validation milliseconds per minute across all of a workspace's Sites. */ workspaceValidationMsPerMinute: number; }; export type SiteDataCollectionDefinition = { name: string; accessMode: SiteDataAccessMode; privateRecords?: boolean; /** Omitted keeps the current rule (none for a new collection). */ guestAccess?: SiteDataGuestAccess; jsonSchema?: Record | null; indexedFields?: string[]; uniqueFields?: string[][]; }; export type SiteDataCollection = { id: string; name: string; accessMode: SiteDataAccessMode; privateRecords: boolean; guestAccess: SiteDataGuestAccess; jsonSchema: Record | null; indexedFields: string[]; uniqueFields: string[][]; recordCount: number; recordBytes: number; createdAt: string; updatedAt: string; }; export type SiteDataRecord = { id: string; key: string | null; data: Record; owner: string; createdBy: string; updatedBy: string; version: number; sizeBytes: number; createdAt: string; updatedAt: string; }; export type SiteDataUsage = { collectionCount: number; recordCount: number; recordBytes: number; fileCount: number; fileBytes: number; workspaceBytes: number; }; export type SiteDataFilterOp = "eq" | "ne" | "in" | "gt" | "gte" | "lt" | "lte" | "contains" | "exists"; export type SiteDataFilter = { field: string; op: SiteDataFilterOp; value?: unknown | undefined; }; export type SiteDataSort = { field: string; direction?: "asc" | "desc" | undefined; }; export type SiteDataQuery = { collection: string; where?: SiteDataFilter[]; sort?: SiteDataSort[]; limit?: number; cursor?: string | null; count?: boolean; /** `own` limits reads to the caller's records; `all` is everything the caller may read. */ scope?: "own" | "all"; }; export type SiteDataQueryResult = { records: SiteDataRecord[]; nextCursor: string | null; count?: number; }; export type SiteDataRecordRef = { id?: string; key?: string; }; export type SiteDataWriteOp = { op: "insert"; collection: string; key?: string; data: Record; /** * Retrying an insert with the same key (per collection and principal) * returns the record the first attempt created instead of a duplicate, * for a day or until that record is deleted. */ idempotencyKey?: string; } | { op: "put"; collection: string; key: string; data: Record; expectedVersion?: number; } | ({ op: "patch"; collection: string; data: Record; expectedVersion?: number; } & SiteDataRecordRef) | ({ op: "delete"; collection: string; expectedVersion?: number; } & SiteDataRecordRef) | ({ op: "increment"; collection: string; field: string; by?: number; } & SiteDataRecordRef); export type SiteDataWriteResultItem = { op: "insert"; record: SiteDataRecord; replayed?: boolean; } | { op: "put" | "patch" | "increment"; record: SiteDataRecord; } | { op: "delete"; deleted: { id: string; }; }; export type SiteDataWriteSummary = { operations: number; bytesWritten: number; recordDelta: number; byteDelta: number; }; export type SiteDataWriteOptions = { limits: SiteDataLimits; /** JSON Schema validation, supplied by the service layer. */ validate?: (schema: Record, data: Record) => string | null; /** Usage metering inside the same transaction. */ afterWrite?: (tx: Database, summary: SiteDataWriteSummary) => Promise; /** `import` records one coarse change event per batch, without record ids. */ changeKind?: "write" | "import"; }; export type SiteDataFileScope = "shared" | "private"; export type SiteDataFile = { id: string; name: string; contentType: string; sizeBytes: number; sha256: string; scope: SiteDataFileScope; owner: string; createdBy: string; createdAt: string; }; export type SiteDataStoredFile = SiteDataFile & { objectKey: string; }; export type SiteDataSite = { id: string; title: string; status: "active" | "archived"; visibility: "workspace_shared" | "user_private"; ownerSubjectId: string | null; createdBySubjectId: string | null; }; /** * Backend-neutral Site Data store. Postgres implements it today; another * backend implements the same contract. Authorization (role and principal) is * resolved by the caller; the store enforces the per-collection matrix, * quotas, uniqueness and write windows. */ export interface SiteDataStore { describe(scope: SiteDataScope): Promise<{ collections: SiteDataCollection[]; usage: SiteDataUsage; }>; getCollection(scope: SiteDataScope, name: string): Promise; defineCollection(caller: SiteDataCaller, definition: SiteDataCollectionDefinition, limits: SiteDataLimits): Promise<{ collection: SiteDataCollection; created: boolean; }>; deleteCollection(caller: SiteDataCaller, name: string): Promise<{ deletedRecords: number; }>; resetCollection(caller: SiteDataCaller, name: string): Promise<{ deletedRecords: number; }>; query(caller: SiteDataCaller, query: SiteDataQuery): Promise; get(caller: SiteDataCaller, collection: string, ref: SiteDataRecordRef): Promise; write(caller: SiteDataCaller, ops: SiteDataWriteOp[], options: SiteDataWriteOptions): Promise<{ results: SiteDataWriteResultItem[]; summary: SiteDataWriteSummary; }>; listFiles(caller: SiteDataCaller, options?: { limit?: number; cursor?: string | null; }): Promise<{ files: SiteDataFile[]; nextCursor: string | null; }>; getFile(caller: SiteDataCaller, fileId: string): Promise; /** Check file quotas before any bytes are stored; insertFile checks again under the lock. */ checkFileQuota(caller: SiteDataCaller, sizeBytes: number, limits: SiteDataLimits): Promise; insertFile(caller: SiteDataCaller, file: Omit, options: Pick): Promise; /** * Count an attempt against the caller's and the Site's one-minute window in * its own committed transaction, before any work: failed attempts count too. * * A write that will validate records (it touches a collection with a * schema, or defines one with a schema) also reserves `reserveMs` of * validation time against the Site's and the workspace's validation * windows in the same transaction, and is refused when either cannot take * it. Other writes touch no validation window. */ consumeRate(caller: SiteDataCaller, kind: "write" | "read", operations: number, limits: SiteDataLimits, validation?: SiteDataValidationAdmission): Promise; /** * Settle a write's validation time, whatever its outcome: replace the * reservation with the time spent on the Site's and workspace's validation * windows, and add one operation per started 5 ms spent (from 1 ms) to the * caller's write windows. Never refused: the work is done. Does nothing * when nothing was reserved or spent. A reservation is refunded only in the * window it was taken from: after the minute rolled over, only time spent * beyond the reservation is charged, to the current window. */ settleValidation(caller: SiteDataCaller, time: SiteDataValidationReservation & { spentMs: number; }, limits: SiteDataLimits): Promise; deleteFile(caller: SiteDataCaller, fileId: string): Promise; /** * Mark the Site as watched for up to `ttlSeconds` (so writes record change * events and notify the change listener) and return its change number, the * collections the caller may read (plus `$files` when it may read files), * and how long this watch lasts (until `live_until`, which may be sooner * than asked). Renewing early is cheap: the lease is only extended once * less than half of it is left. */ watch(caller: SiteDataCaller, ttlSeconds: number): Promise<{ seq: number; collections: string[]; ttlSeconds: number; }>; } export declare function publicSiteDataFile(file: SiteDataStoredFile): SiteDataFile; /** Storage charged against quotas for a record of this JSON size. */ export declare function siteDataChargedBytes(sizeBytes: number): number; /** Validate and normalize a collection definition. */ export declare function normalizeSiteDataCollectionDefinition(definition: SiteDataCollectionDefinition): Required> & { guestAccess?: SiteDataGuestAccess; }; /** Who wrote, coarsely: never the principal itself. */ export declare function siteDataActorKind(caller: Pick): "user" | "guest" | "agent" | "schedule" | "service" | "other"; /** * Server-evaluated time in a filter value: `$now`, or `$now` plus or minus a * whole number of ms, s, m, h or d (`$now-5m`), clamped to a century. Returns the * offset in milliseconds, or null when the value is not a `$now` expression. */ export declare function siteDataNowOffsetMs(value: unknown): number | null; export declare function createPostgresSiteDataStore(db: Database, storeOptions?: SiteDataStoreOptions): SiteDataStore; /** * The Site as a Site Data caller sees it: visible to the viewer by audience * (workspace Sites, or their own Only me Sites), or null. */ export declare function getSiteDataSite(db: Database, scope: { accountId: string; workspaceId: string; }, viewer: { subjectId: string | null; }, siteId: string): Promise; /** The scheduled task behind this session's Site Data principal, never caller metadata. */ export declare function getSiteDataScheduledTaskId(db: Database, scope: { accountId: string; workspaceId: string; }, sessionId: string): Promise; /** * The scheduled run that created this session, if any: its task (the Site * Data principal) and its automation chain depth (recorded on change events). */ export declare function getSiteDataScheduledRun(db: Database, scope: { accountId: string; workspaceId: string; }, sessionId: string): Promise<{ taskId: string; chainDepth: number; } | null>; export declare const SITE_DATA_MAX_BATCH_OPERATIONS = 100;