@docstack/client 0.1.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +373 -132
  3. package/lib/core/attribute.d.ts +0 -0
  4. package/lib/core/class.d.ts +0 -0
  5. package/lib/core/content-transfer.d.ts +0 -0
  6. package/lib/core/crypto-engine/index.d.ts +63 -5
  7. package/lib/core/crypto-engine/utils.d.ts +10 -2
  8. package/lib/core/datamodel/index.d.ts +0 -0
  9. package/lib/core/domain.d.ts +0 -0
  10. package/lib/core/guarded-db.d.ts +0 -0
  11. package/lib/core/index.d.ts +4 -2
  12. package/lib/core/job-engine/index.d.ts +0 -0
  13. package/lib/core/job-engine/schedule.d.ts +0 -0
  14. package/lib/core/job-engine/scheduler.d.ts +0 -0
  15. package/lib/core/query-engine/accumulators.d.ts +0 -0
  16. package/lib/core/query-engine/classes.d.ts +0 -0
  17. package/lib/core/query-engine/evaluator.d.ts +0 -0
  18. package/lib/core/query-engine/executor.d.ts +0 -0
  19. package/lib/core/query-engine/index.d.ts +0 -0
  20. package/lib/core/query-engine/parser.d.ts +0 -0
  21. package/lib/core/query-engine/planner.d.ts +0 -0
  22. package/lib/core/stack.d.ts +223 -8
  23. package/lib/core/sync/class-filter.d.ts +0 -0
  24. package/lib/core/sync/filter-identity.d.ts +0 -0
  25. package/lib/core/sync/index.d.ts +17 -2
  26. package/lib/core/sync/internal-docs.d.ts +0 -0
  27. package/lib/core/sync/tenants.d.ts +0 -0
  28. package/lib/core/test-utils/docstack.d.ts +0 -0
  29. package/lib/core/transaction-engine/errors.d.ts +57 -0
  30. package/lib/core/transaction-engine/handle.d.ts +165 -0
  31. package/lib/core/transaction-engine/index.d.ts +82 -0
  32. package/lib/core/transaction-engine/overlay.d.ts +66 -0
  33. package/lib/core/transaction-engine/stage.d.ts +50 -0
  34. package/lib/core/transaction-engine/sweep.d.ts +25 -0
  35. package/lib/core/trigger/index.d.ts +0 -0
  36. package/lib/index.d.ts +12 -2
  37. package/lib/index.js +4710 -733
  38. package/lib/index.umd.js +5259 -623
  39. package/lib/index2.js +641 -0
  40. package/lib/plugins/pouchdb.d.ts +16 -1
  41. package/lib/utils/crypto/index.d.ts +0 -0
  42. package/lib/utils/index.d.ts +4 -2
  43. package/lib/utils/logger/index.d.ts +0 -0
  44. package/lib/utils/logger/transport.d.ts +0 -0
  45. package/lib/workers/dataModel.d.ts +0 -0
  46. package/package.json +3 -1
  47. package/lib/core/policy-engine/index.d.ts +0 -132
@@ -0,0 +1,165 @@
1
+ import { Document } from "@docstack/shared";
2
+ import type ClientStack from "../stack.js";
3
+ import { TransactionStage, StagedEntry } from "./stage.js";
4
+ import { MangoSort } from "./overlay.js";
5
+ import type { TransactionEngine, TransactionCommitReport } from "./index.js";
6
+ export type TransactionStatus = "open" | "committed" | "discarded" | "partial";
7
+ /**
8
+ * One transaction: a private write journal plus a read view that overlays it on
9
+ * committed state (ADR-0039).
10
+ *
11
+ * Writes through the handle are validated at the call site (the sweep - failing
12
+ * stages nothing) and stage in memory; nothing reaches the database until
13
+ * {@link commit}, which flushes the journal as one batch through the stack's full
14
+ * authoring pipeline. Reads through the handle see the journal; `stack.db`, other
15
+ * handles, replication and live subscriptions see only committed state.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const t = stack.beginTransaction();
20
+ * await t.createDoc(null, "Task", { title: "write-up" });
21
+ * await t.db.put({ ...(await t.db.get("Task-77")), done: true });
22
+ * const drafted = await t.findDocuments({ "~class": { $eq: "Task" } });
23
+ * const report = await t.commit(); // or stack.commit(t)
24
+ * ```
25
+ */
26
+ export declare class TransactionHandle {
27
+ readonly id: string;
28
+ /** @internal */
29
+ readonly stage: TransactionStage;
30
+ /** @internal - ids this handle minted, counted into the id counter after commit. */
31
+ readonly mintedIds: Set<string>;
32
+ /**
33
+ * True for handles DocStack mints for its own machinery (patch application,
34
+ * ADR-0042). Internal handles may stage class models; public ones refuse them.
35
+ * @internal
36
+ */
37
+ readonly internal: boolean;
38
+ private statusValue;
39
+ private readonly stack;
40
+ private readonly engine;
41
+ /** The db-like surface: staged writes, overlaid reads. */
42
+ readonly db: TransactionDb;
43
+ /** @internal */
44
+ constructor(stack: ClientStack, engine: TransactionEngine, id: string, internal?: boolean);
45
+ get status(): TransactionStatus;
46
+ /** @internal */
47
+ setStatus(status: TransactionStatus): void;
48
+ stagedCount(): number;
49
+ /** @internal */
50
+ assertWritable(operation: string): void;
51
+ /**
52
+ * Stages a write. The sweep runs first: a document that fails validation, policy,
53
+ * or the locked-stack check is not staged and the journal is untouched.
54
+ * @internal
55
+ */
56
+ stageWrite(doc: Document, op?: "write" | "delete"): Promise<StagedEntry>;
57
+ /**
58
+ * Creates or updates a document in the transaction - `stack.createDoc`'s UX with
59
+ * a staged destination: `docId: null` mints an id, an existing id merges params
60
+ * over the overlay-visible document.
61
+ */
62
+ createDoc(docId: string | null, type: string, params: {
63
+ [key: string]: any;
64
+ }): Promise<Document>;
65
+ /** Batch counterpart of {@link createDoc}; validated sequentially, fail-fast. */
66
+ createDocs(docs: {
67
+ docId: string | null;
68
+ params: {
69
+ [key: string]: any;
70
+ };
71
+ }[], type: string): Promise<Document[]>;
72
+ /** Soft-deletes in the transaction: the overlay stops showing the document under the default `active: true`. */
73
+ deleteDocument(docId: string): Promise<boolean>;
74
+ /** The stack's polished read, against this transaction's view. */
75
+ findDocuments<T extends Document = Document>(selector: {
76
+ [key: string]: any;
77
+ }, fields?: string[], skip?: number, limit?: number, sort?: MangoSort): Promise<{
78
+ [key: string]: any;
79
+ docs: T[];
80
+ }>;
81
+ /**
82
+ * SQL against this transaction's view. The executor reaches data only through
83
+ * stack APIs, so a facade routes them at the overlay; LIMIT/OFFSET pushdown and
84
+ * sort indexes are disabled while staged - staged documents exist in no index,
85
+ * so windows and orderings must be computed after the merge.
86
+ */
87
+ query(sql: string, ...params: any[]): Promise<{
88
+ rows: any;
89
+ ast: (import("@docstack/shared").SelectAST | import("@docstack/shared").UnionAST)[];
90
+ }>;
91
+ /** Flushes the journal - sugar for `stack.commit(t)`. */
92
+ commit(): Promise<TransactionCommitReport>;
93
+ /** Drops the journal - sugar for `stack.discardTransaction(t)`. */
94
+ discard(): void;
95
+ }
96
+ /**
97
+ * The handle's db-like surface. Writes stage; reads overlay. Not a Proxy over the
98
+ * guarded db on purpose: this object *has no* adapter methods or escape hatches to
99
+ * forward, so staging cannot become a fourth door around the authoring path.
100
+ */
101
+ export declare class TransactionDb {
102
+ private readonly stack;
103
+ private readonly handle;
104
+ /** @internal */
105
+ constructor(stack: ClientStack, handle: TransactionHandle);
106
+ get(docId: string, options?: any): Promise<Document>;
107
+ bulkGet(request: {
108
+ docs: {
109
+ id: string;
110
+ rev?: string;
111
+ }[];
112
+ }): Promise<{
113
+ results: any[];
114
+ }>;
115
+ /**
116
+ * Raw-style Mango find over the transaction's view. Like `stack.db.find`, this
117
+ * skips the read pipeline (no policy filter, no decryption of committed rows);
118
+ * `findDocuments` on the handle is the polished read.
119
+ */
120
+ find(query: {
121
+ selector: {
122
+ [key: string]: any;
123
+ };
124
+ fields?: string[];
125
+ skip?: number;
126
+ limit?: number;
127
+ sort?: any;
128
+ }): Promise<{
129
+ docs: Document[];
130
+ }>;
131
+ put(doc: Document, options?: any): Promise<{
132
+ ok: true;
133
+ id: string;
134
+ rev?: string;
135
+ staged: true;
136
+ }>;
137
+ post(doc: Document): Promise<{
138
+ ok: true;
139
+ id: string;
140
+ rev?: string;
141
+ staged: true;
142
+ }>;
143
+ /** Hard removal, staged: the commit writes `_deleted: true`. Soft deletion is `handle.deleteDocument`. */
144
+ remove(doc: {
145
+ _id: string;
146
+ _rev?: string;
147
+ } | string, rev?: string): Promise<{
148
+ ok: true;
149
+ id: string;
150
+ staged: true;
151
+ }>;
152
+ /**
153
+ * Stages a batch. Validated sequentially - the first refusal unwinds every entry
154
+ * this call staged, so a failing batch stages nothing. Documents stage before
155
+ * relations, mirroring the commit batch, so a relation and its endpoint can
156
+ * arrive in one array in any order.
157
+ */
158
+ bulkDocs(docs: Document[] | {
159
+ docs: Document[];
160
+ }, options?: any): Promise<{
161
+ ok: true;
162
+ id: string;
163
+ staged: true;
164
+ }[]>;
165
+ }
@@ -0,0 +1,82 @@
1
+ import type ClientStack from "../stack.js";
2
+ import { TransactionHandle } from "./handle.js";
3
+ export { TransactionHandle, TransactionDb } from "./handle.js";
4
+ export type { TransactionStatus } from "./handle.js";
5
+ export { TransactionStage } from "./stage.js";
6
+ export type { StagedEntry, StagedOp } from "./stage.js";
7
+ export { stageCoversSelector, mergeStageIntoResults, widenProjection } from "./overlay.js";
8
+ export { classFromStage } from "./sweep.js";
9
+ export { TransactionsDisabledError, TransactionStateError, TransactionValidationError, TransactionConflictError, TransactionUnsupportedDocError, } from "./errors.js";
10
+ /** What one commit did, and on what guarantee. */
11
+ export type TransactionCommitReport = {
12
+ transactionId: string;
13
+ /** Documents that landed, with their new revisions. */
14
+ written: {
15
+ id: string;
16
+ rev: string;
17
+ }[];
18
+ /** Documents that did not - possible only on adapters where `atomicBatch` is false. */
19
+ failed: {
20
+ id: string;
21
+ error: string;
22
+ name?: string;
23
+ }[];
24
+ /** Journal size at the moment commit ran. */
25
+ stagedCount: number;
26
+ durationMs: number;
27
+ /**
28
+ * The storage adapter's honest guarantee for this commit: `atomicBatch: true`
29
+ * means the batch landed (or failed) as one storage transaction; `false` means
30
+ * per-document results, mitigated by the rev pre-flight but not eliminated.
31
+ */
32
+ adapter: {
33
+ name: string;
34
+ atomicBatch: boolean;
35
+ };
36
+ };
37
+ /**
38
+ * Named write transactions for one stack (ADR-0039).
39
+ *
40
+ * Enabled per stack by `transactions: true` in its configuration - the flag only
41
+ * unlocks {@link begin}; direct writes stay immediate, and the framework's own
42
+ * writers (scheduler, jobs, sync) always write directly. The stage lives above the
43
+ * plugin: nothing a transaction does touches the database until commit, and commit
44
+ * is exactly one `stack.db.bulkDocs` through the full authoring pipeline.
45
+ */
46
+ export declare class TransactionEngine {
47
+ private readonly stack;
48
+ private readonly enabled;
49
+ private readonly handles;
50
+ /** Commits serialize here so one commit's rev pre-flight cannot be invalidated by another's write. */
51
+ private commitChain;
52
+ constructor(stack: ClientStack, enabled: boolean);
53
+ isEnabled(): boolean;
54
+ /** How many transactions are currently open (or partial). */
55
+ openCount(): number;
56
+ begin(): TransactionHandle;
57
+ /**
58
+ * Opens a transaction for DocStack's own machinery - patch application
59
+ * (ADR-0042). Independent of the `transactions: true` config gate (the flag
60
+ * governs the consumer feature, not the framework's internals) and permitted to
61
+ * stage class models: an internal handle claims staged validation and a single
62
+ * class-write batch, never propagation atomicity.
63
+ * @internal
64
+ */
65
+ beginInternal(): TransactionHandle;
66
+ private resolve;
67
+ /**
68
+ * Drops a transaction's journal. Idempotent, and a no-op on a handle already in
69
+ * a terminal state - discarding what is already gone is not an error.
70
+ */
71
+ discard(t: TransactionHandle | string): void;
72
+ /** Discards every open transaction - what `close()` and `reset()` do. */
73
+ discardAll(): void;
74
+ /**
75
+ * Flushes a transaction's journal as one batch through the stack's authoring
76
+ * pipeline. Refusals - validation, or a staged document whose base revision
77
+ * moved - throw with nothing persisted and the transaction still open.
78
+ */
79
+ commit(t: TransactionHandle | string): Promise<TransactionCommitReport>;
80
+ private commitNow;
81
+ private adapterInfo;
82
+ }
@@ -0,0 +1,66 @@
1
+ import { Document } from "@docstack/shared";
2
+ import { TransactionStage } from "./stage.js";
3
+ /** The sort shape `findDocuments` accepts. */
4
+ export type MangoSort = {
5
+ [field: string]: "asc" | "desc";
6
+ }[] | string[];
7
+ /**
8
+ * True when a query with this selector could see documents this stage holds.
9
+ *
10
+ * Derived from the selector's `~class` / `~domain` constraint against the stage's
11
+ * partitions; a selector naming no class is answered conservatively. This is the
12
+ * per-query fast path: a find over a class the transaction never touched runs
13
+ * exactly as it would outside the transaction.
14
+ */
15
+ export declare const stageCoversSelector: (stage: TransactionStage, selector: {
16
+ [key: string]: any;
17
+ }) => boolean;
18
+ /**
19
+ * Fields the widened committed query (and the staged docs) must carry beyond the
20
+ * caller's projection, so masking, sorting and the read pipeline can work; the
21
+ * extras are stripped again after the merge.
22
+ */
23
+ export declare const widenProjection: (fields: string[] | undefined, sort: MangoSort | undefined) => {
24
+ queryFields: string[] | undefined;
25
+ extras: string[];
26
+ };
27
+ /**
28
+ * Merges a stage into a committed query result: every staged id masks its committed
29
+ * row (superseded and deleted alike), staged writes matching the selector join the
30
+ * set, then sort, window and projection apply in memory - the database's index can
31
+ * never see a staged document, so the window has to be computed after the union.
32
+ *
33
+ * `committedDocs` must come from a query WITHOUT skip/limit (the mask changes what
34
+ * the window contains) and carrying `widenProjection`'s fields.
35
+ */
36
+ export declare const mergeStageIntoResults: (stage: TransactionStage, selector: {
37
+ [key: string]: any;
38
+ }, committedDocs: Document[], options?: {
39
+ sort?: MangoSort;
40
+ skip?: number;
41
+ limit?: number;
42
+ fields?: string[];
43
+ extras?: string[];
44
+ }) => Document[];
45
+ /** A PouchDB-shaped `not_found`, so overlay reads refuse like the database does. */
46
+ export declare const notFoundError: (id: string) => any;
47
+ /**
48
+ * Read-your-writes for a point read: a staged delete is a 404, a staged write is the
49
+ * authored plaintext (its `_rev` is the base revision - the revision the commit will
50
+ * replace), anything else is the stack's ordinary decrypting read.
51
+ */
52
+ export declare const overlayGet: (stack: {
53
+ db: any;
54
+ }, stage: TransactionStage, id: string, options?: any) => Promise<Document>;
55
+ /** `bulkGet` counterpart of {@link overlayGet}, preserving request order. */
56
+ export declare const overlayBulkGet: (stack: {
57
+ db: any;
58
+ }, stage: TransactionStage, request: {
59
+ docs: {
60
+ id: string;
61
+ rev?: string;
62
+ }[];
63
+ [key: string]: any;
64
+ }) => Promise<{
65
+ results: any[];
66
+ }>;
@@ -0,0 +1,50 @@
1
+ import { Document } from "@docstack/shared";
2
+ /** What one staged entry means for its document id. */
3
+ export type StagedOp = "write" | "delete";
4
+ export interface StagedEntry {
5
+ /** The authored document, plaintext, cloned at stage time. */
6
+ doc: Document;
7
+ /** The winning revision the entry was staged against; absent for a new document. */
8
+ baseRev?: string;
9
+ op: StagedOp;
10
+ /** True when the id did not exist (in stage or store) when first staged. */
11
+ isNew: boolean;
12
+ stagedAt: number;
13
+ }
14
+ /**
15
+ * The write journal of one transaction: authored documents keyed by id, in memory.
16
+ *
17
+ * Also partitioned by class (`~class`, or `~domain` for relations) so a read can ask
18
+ * "could this stage affect a query over class X" in O(1) - the overlay only pays the
19
+ * merge for queries whose class the transaction actually touched (ADR-0039).
20
+ */
21
+ export declare class TransactionStage {
22
+ private entries;
23
+ private partitions;
24
+ private partitionKeys;
25
+ /**
26
+ * Stages an entry. Re-staging an id replaces the document but keeps the original
27
+ * `baseRev` and `isNew` - the conflict check is against the world as it was when
28
+ * the transaction first touched the id, not against its own previous draft.
29
+ */
30
+ set(id: string, entry: StagedEntry): void;
31
+ get(id: string): StagedEntry | undefined;
32
+ has(id: string): boolean;
33
+ get size(): number;
34
+ ids(): string[];
35
+ /** Entries in stage order (insertion order of first staging). */
36
+ values(): StagedEntry[];
37
+ hasPartition(name: string): boolean;
38
+ /** Keeps only the given ids - what a partial commit leaves behind. */
39
+ retain(ids: Set<string>): void;
40
+ /**
41
+ * A point-in-time copy of the journal, for {@link restore}. Used by the patch
42
+ * chain (ADR-0044) to unwind exactly one patch's staging - a pre-apply job's
43
+ * writes included - when a locked refusal converts that patch to a deferral
44
+ * while the already-staged prefix goes on to commit.
45
+ */
46
+ snapshot(): Map<string, StagedEntry>;
47
+ restore(snapshot: Map<string, StagedEntry>): void;
48
+ remove(id: string): void;
49
+ clear(): void;
50
+ }
@@ -0,0 +1,25 @@
1
+ import Class from "../class.js";
2
+ import type ClientStack from "../stack.js";
3
+ import { TransactionStage, StagedEntry } from "./stage.js";
4
+ /**
5
+ * Resolves a class from the transaction's own stage: the ADR-0043 rule
6
+ * (the batch outranks the store - it is what is about to be committed) applied to
7
+ * staging. A patch chain's job can create documents of a class an earlier patch
8
+ * staged (ADR-0044), and the sweep must judge them by that staged model, not by a
9
+ * committed predecessor or a not-found. Built DETACHED - `Class.get` + `setModel`,
10
+ * never `buildFromModel`, which writes rev-less models (ADR-0043).
11
+ */
12
+ export declare const classFromStage: (stack: ClientStack, stage: TransactionStage, className: string) => Class | null;
13
+ /**
14
+ * The validation sweep - the transaction's atomicity boundary in practice.
15
+ *
16
+ * Runs read-only checks against public stack APIs: it decides whether a document
17
+ * *could* be written, and touches nothing. Stage time runs it so a bad write fails at
18
+ * the call site with zero consequences; commit re-runs it so the batch is judged
19
+ * against the world as it stands at commit. The commit-time pipeline (the plugin's
20
+ * `bulkDocs`) remains the sole authority - this sweep is a deliberate subset, and a
21
+ * document it passes can still be refused there, atomically for the whole batch.
22
+ */
23
+ export declare const sweepEntry: (stack: ClientStack, stage: TransactionStage, entry: StagedEntry, options?: {
24
+ allowClassModels?: boolean;
25
+ }) => Promise<void>;
File without changes
package/lib/index.d.ts CHANGED
@@ -18,9 +18,19 @@ export type { SchedulerOptions, SchedulerHost, JobScheduleState, TickReport, Ski
18
18
  * application hands over, so DocStack never learns about Google Drive, Firestore or
19
19
  * anything else, and no consumer pays for a transport it does not use.
20
20
  */
21
- export { StackSyncHandle, DocStackSyncHandle, SyncSchemaMismatchError, SYNC_META_DOC_ID, readRemoteSchemaVersion, publishSchemaVersion, createReplicationFilter, isInternalDoc, resolveInternalClasses, createClassFilter, hasClassRules, DATA_MODEL_CLASSES, withFilterIdentity, describeFilter, INTERNAL_DOC_IDS, INTERNAL_DOC_ID_PREFIXES, INTERNAL_DOC_CLASSES, OPTIONAL_INTERNAL_DOC_CLASSES, StackWriteGuardError, StackLockedError, deriveKeyId, isEncryptedPayload, deriveTenantScope, classTenants, } from "./core/index.js";
21
+ export { StackSyncHandle, DocStackSyncHandle, SyncSchemaMismatchError, SYNC_META_DOC_ID, readRemoteSchemaVersion, readRemoteConsumerSchemaVersion, publishSchemaVersion, createReplicationFilter, isInternalDoc, resolveInternalClasses, createClassFilter, hasClassRules, DATA_MODEL_CLASSES, withFilterIdentity, describeFilter, INTERNAL_DOC_IDS, INTERNAL_DOC_ID_PREFIXES, INTERNAL_DOC_CLASSES, OPTIONAL_INTERNAL_DOC_CLASSES, StackWriteGuardError, StackLockedError, StackScopeMismatchError, deriveKeyId, isEncryptedPayload, deriveTenantScope, classTenants, } from "./core/index.js";
22
22
  export { SYSTEM_SEEDED_DOC_IDS, collectQueryClasses } from "./core/index.js";
23
23
  export type { EncryptedPayload, ClassBuildOptions } from "./core/index.js";
24
+ /**
25
+ * Named write transactions (ADR-0039).
26
+ *
27
+ * Opt-in per stack via `transactions: true`. A handle stages validated writes in
28
+ * memory and reads its own staged state overlaid on committed state; `commit`
29
+ * flushes the journal as one batch through the full authoring pipeline, and the
30
+ * report states the storage adapter's honest atomicity guarantee.
31
+ */
32
+ export { TransactionEngine, TransactionHandle, TransactionDb, TransactionsDisabledError, TransactionStateError, TransactionValidationError, TransactionConflictError, TransactionUnsupportedDocError, } from "./core/index.js";
33
+ export type { TransactionCommitReport, TransactionStatus } from "./core/index.js";
24
34
  /**
25
35
  * Moving application content between stacks, without the datamodel that describes it.
26
36
  */
@@ -37,5 +47,5 @@ export type { SyncDirection, SyncState, SyncStatus, StackSyncOptions, DocStackSy
37
47
  * Note that `Document` shadows the DOM's global `Document` in whichever module imports
38
48
  * it; alias it (`import type { Document as DocStackDocument }`) in code that needs both.
39
49
  */
40
- export type { AttributeType, AttributeTypeConfig, AttributeModel, ClassModel, DomainModel, TriggerModel, Document, RelationDocument, Patch, SelectAST, UnionAST, ClientCredentials, DocstackReady, StackConfig, StackOptions, } from "@docstack/shared";
50
+ export type { AttributeType, AttributeTypeConfig, AttributeModel, ClassModel, DomainModel, TriggerModel, Document, RelationDocument, Patch, PatchJob, SelectAST, UnionAST, ClientCredentials, DocstackReady, StackConfig, StackOptions, } from "@docstack/shared";
41
51
  export default DocStack;