@pmate/chat-sdk 0.12.0-next.0 → 0.12.0-next.10

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.
@@ -0,0 +1,28 @@
1
+ /** Small response windows, isolated by identity. Epochs fence late writes after
2
+ * access withdrawal. No localStorage or synchronous writes on the read path. */
3
+ export declare class IndexedDbResponseCache<T> {
4
+ private scope;
5
+ private db;
6
+ private rows;
7
+ private epochs;
8
+ private pending;
9
+ private tasks;
10
+ private running?;
11
+ private closed;
12
+ private closing?;
13
+ constructor(scope: string, options?: {
14
+ indexedDB?: IDBFactory;
15
+ name?: string;
16
+ });
17
+ read(key: string): Promise<{
18
+ epoch: number;
19
+ cached: {
20
+ value: T;
21
+ time: number;
22
+ } | undefined;
23
+ }>;
24
+ write(key: string, value: T, epoch: number): Promise<void>;
25
+ invalidate(): Promise<void>;
26
+ flush(): Promise<void>;
27
+ close(): Promise<void>;
28
+ }
@@ -0,0 +1,106 @@
1
+ import { Dexie } from "dexie";
2
+ import { WindowedTasks } from "./coalescer.js";
3
+ /** Small response windows, isolated by identity. Epochs fence late writes after
4
+ * access withdrawal. No localStorage or synchronous writes on the read path. */
5
+ export class IndexedDbResponseCache {
6
+ scope;
7
+ db;
8
+ rows;
9
+ epochs;
10
+ pending = [];
11
+ tasks = new WindowedTasks(16, () => { });
12
+ running;
13
+ closed = false;
14
+ closing;
15
+ constructor(scope, options = {}) {
16
+ this.scope = scope;
17
+ this.db = new Dexie(options.name ?? "pmate-chat-response-windows", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
18
+ this.db.version(1).stores({ windows: "[scope+key],scope", epochs: "scope" });
19
+ this.rows = this.db.table("windows");
20
+ this.epochs = this.db.table("epochs");
21
+ }
22
+ async read(key) {
23
+ if (this.closed)
24
+ throw new Error("RESPONSE_CACHE_CLOSED");
25
+ return this.db.transaction("r", this.rows, this.epochs, async () => {
26
+ const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
27
+ const row = await this.rows.get([this.scope, key]);
28
+ return { epoch, cached: row?.epoch === epoch ? { value: row.value, time: row.time } : undefined };
29
+ });
30
+ }
31
+ write(key, value, epoch) {
32
+ if (this.closed)
33
+ return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
34
+ const copy = structuredClone(value), bytes = new TextEncoder().encode(JSON.stringify(copy)).byteLength;
35
+ // Count in-flight data as well as queued data; requests cannot create an
36
+ // unbounded backlog while IndexedDB is blocked by another tab.
37
+ if (bytes > 65536 || this.pending.length >= 128 || this.pending.reduce((n, w) => n + w.row.bytes, 0) + bytes > 1048576)
38
+ return Promise.reject(new Error("RESPONSE_CACHE_BACKPRESSURE"));
39
+ const promise = new Promise((resolve, reject) => this.pending.push({ row: { scope: this.scope, key, epoch, time: Date.now(), bytes, value: copy }, resolve, reject }));
40
+ this.tasks.schedule("write", () => this.flush());
41
+ return promise;
42
+ }
43
+ async invalidate() {
44
+ if (this.closed)
45
+ throw new Error("RESPONSE_CACHE_CLOSED");
46
+ await this.db.transaction("rw", this.rows, this.epochs, async () => {
47
+ const epoch = ((await this.epochs.get(this.scope))?.epoch ?? 0) + 1;
48
+ await this.epochs.put({ scope: this.scope, epoch });
49
+ await this.rows.where("scope").equals(this.scope).delete();
50
+ });
51
+ }
52
+ async flush() {
53
+ if (this.running) {
54
+ await this.running;
55
+ if (this.pending.length)
56
+ return this.flush();
57
+ return;
58
+ }
59
+ const batch = [...this.pending];
60
+ if (!batch.length)
61
+ return;
62
+ const task = (async () => {
63
+ try {
64
+ const accepted = await this.db.transaction("rw", this.rows, this.epochs, async () => {
65
+ const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
66
+ const valid = batch.filter(write => write.row.epoch === epoch);
67
+ const unique = new Map(valid.map(write => [write.row.key, write.row]));
68
+ await this.rows.bulkPut([...unique.values()]);
69
+ const stored = await this.rows.where("scope").equals(this.scope).toArray();
70
+ stored.sort((a, b) => b.time - a.time || a.key.localeCompare(b.key));
71
+ let bytes = 0;
72
+ const evicted = [];
73
+ stored.forEach((row, index) => { bytes += row.bytes; if (index >= 256 || bytes > 1048576)
74
+ evicted.push([this.scope, row.key]); });
75
+ await this.rows.bulkDelete(evicted);
76
+ return new Set(valid);
77
+ });
78
+ batch.forEach(write => accepted.has(write) ? write.resolve() : write.reject(new Error("RESPONSE_CACHE_INVALIDATED")));
79
+ }
80
+ catch (error) {
81
+ batch.forEach(write => write.reject(error));
82
+ throw error;
83
+ }
84
+ finally {
85
+ this.pending.splice(0, batch.length);
86
+ }
87
+ })().finally(() => { if (this.running === task)
88
+ this.running = undefined; });
89
+ this.running = task;
90
+ return task;
91
+ }
92
+ close() {
93
+ if (this.closing)
94
+ return this.closing;
95
+ this.closed = true;
96
+ this.tasks.close();
97
+ return this.closing = (async () => {
98
+ try {
99
+ await this.flush();
100
+ }
101
+ finally {
102
+ this.db.close();
103
+ }
104
+ })();
105
+ }
106
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.12.0-next.0",
3
+ "version": "0.12.0-next.10",
4
4
  "description": "Cross-platform PMate chat input components, voice input primitives, and ASR helpers",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",