@wats/persistence 0.3.29 → 0.3.30

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,19 @@
1
+ import { type ConversationWindowInput, type ConversationWindowState, type PersistenceStore } from "./index";
2
+ /**
3
+ * Compute the 24-hour customer-service-window state for a phone number.
4
+ *
5
+ * The window is open when the most recent inbound message from `phone` is less
6
+ * than `windowMs` (default 24h) before `now`. The boundary is strict: an
7
+ * inbound exactly `windowMs` ago closes the window (you need a template).
8
+ *
9
+ * Clock skew: if `lastInboundAt` is in the future relative to `now`, the window
10
+ * is treated as open with the full remaining duration. This is the safe choice
11
+ * for a WhatsApp ops caller — a free-form send that Meta rejects costs a
12
+ * retry, while wrongly forcing a template silences a live conversation.
13
+ */
14
+ export declare function getConversationWindowState(store: PersistenceStore, input: ConversationWindowInput): Promise<ConversationWindowState>;
15
+ /**
16
+ * True when free-form messages are allowed right now (the 24h window is open).
17
+ * Outside the window, send an approved template.
18
+ */
19
+ export declare function canSendFreeForm(store: PersistenceStore, input: ConversationWindowInput): Promise<boolean>;
@@ -0,0 +1,100 @@
1
+ import {
2
+ PersistenceError
3
+ } from "./index";
4
+ const DEFAULT_WINDOW_MS = 86400000;
5
+ const MIN_WINDOW_MS = 1;
6
+ const MAX_WINDOW_MS = 604800000;
7
+ const MAX_STRING_LENGTH = 1024;
8
+ function hasControlChars(value) {
9
+ return Array.from(value).some((char) => {
10
+ const code = char.codePointAt(0) ?? 0;
11
+ return code < 32 || code === 127;
12
+ });
13
+ }
14
+ function isRecord(value) {
15
+ if (typeof value !== "object" || value === null || Array.isArray(value))
16
+ return false;
17
+ const prototype = Object.getPrototypeOf(value);
18
+ return prototype === null || prototype === Object.prototype;
19
+ }
20
+ function validatePhone(value) {
21
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > MAX_STRING_LENGTH || hasControlChars(value)) {
22
+ throw new PersistenceError("invalid_record", "phone must be a safe non-empty string.");
23
+ }
24
+ return value;
25
+ }
26
+ function validateTimestamp(value, label) {
27
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > MAX_STRING_LENGTH || hasControlChars(value)) {
28
+ throw new PersistenceError("invalid_record", `${label} must be an ISO timestamp.`);
29
+ }
30
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(value)) {
31
+ throw new PersistenceError("invalid_record", `${label} must be an ISO timestamp.`);
32
+ }
33
+ if (new Date(value).toISOString() !== value) {
34
+ throw new PersistenceError("invalid_record", `${label} must be an ISO timestamp.`);
35
+ }
36
+ return value;
37
+ }
38
+ function validateWindowMs(value) {
39
+ if (value === undefined)
40
+ return DEFAULT_WINDOW_MS;
41
+ if (typeof value !== "number" || !Number.isInteger(value) || value < MIN_WINDOW_MS || value > MAX_WINDOW_MS) {
42
+ throw new PersistenceError("invalid_record", "windowMs must be an integer from 1 to 604800000.");
43
+ }
44
+ return value;
45
+ }
46
+ function validateConversationWindowInput(input) {
47
+ if (!isRecord(input)) {
48
+ throw new PersistenceError("invalid_record", "conversation window input must be an object.");
49
+ }
50
+ return Object.freeze({
51
+ phone: validatePhone(input.phone),
52
+ now: validateTimestamp(input.now, "now"),
53
+ windowMs: validateWindowMs(input.windowMs)
54
+ });
55
+ }
56
+ function isoFromMs(ms) {
57
+ return new Date(ms).toISOString();
58
+ }
59
+ export async function getConversationWindowState(store, input) {
60
+ const validated = validateConversationWindowInput(input);
61
+ const lastInboundAt = await store.getLatestInboundMessageAt({ phone: validated.phone });
62
+ if (lastInboundAt === null) {
63
+ return Object.freeze({
64
+ open: false,
65
+ lastInboundAt: null,
66
+ expiresAt: null,
67
+ remainingMs: 0
68
+ });
69
+ }
70
+ const lastMs = new Date(lastInboundAt).getTime();
71
+ const nowMs = new Date(validated.now).getTime();
72
+ if (lastMs > nowMs) {
73
+ return Object.freeze({
74
+ open: true,
75
+ lastInboundAt,
76
+ expiresAt: isoFromMs(lastMs + validated.windowMs),
77
+ remainingMs: validated.windowMs
78
+ });
79
+ }
80
+ const elapsed = nowMs - lastMs;
81
+ const remainingMs = validated.windowMs - elapsed;
82
+ if (remainingMs > 0) {
83
+ return Object.freeze({
84
+ open: true,
85
+ lastInboundAt,
86
+ expiresAt: isoFromMs(lastMs + validated.windowMs),
87
+ remainingMs
88
+ });
89
+ }
90
+ return Object.freeze({
91
+ open: false,
92
+ lastInboundAt,
93
+ expiresAt: isoFromMs(lastMs + validated.windowMs),
94
+ remainingMs: 0
95
+ });
96
+ }
97
+ export async function canSendFreeForm(store, input) {
98
+ const state = await getConversationWindowState(store, input);
99
+ return state.open;
100
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const CURRENT_SCHEMA_VERSION: 3;
1
+ export declare const CURRENT_SCHEMA_VERSION: 4;
2
2
  export declare const REDACTED_SQLITE_LOCATION: "[REDACTED_SQLITE_DATABASE]";
3
3
  export type PersistenceBackend = "sqlite" | "postgres";
4
4
  export type PersistenceErrorCode = "invalid_options" | "invalid_filename" | "invalid_record" | "migration_failed" | "migration_checksum_mismatch" | "migration_lock_failed" | "outbox_failed" | "store_closed";
@@ -107,6 +107,20 @@ export interface ListMessagesResult {
107
107
  readonly items: readonly MessageRecord[];
108
108
  readonly nextCursor: string | null;
109
109
  }
110
+ export interface LatestInboundMessageInput {
111
+ readonly phone: string;
112
+ }
113
+ export interface ConversationWindowInput {
114
+ readonly phone: string;
115
+ readonly now: string;
116
+ readonly windowMs?: number;
117
+ }
118
+ export interface ConversationWindowState {
119
+ readonly open: boolean;
120
+ readonly lastInboundAt: string | null;
121
+ readonly expiresAt: string | null;
122
+ readonly remainingMs: number;
123
+ }
110
124
  export interface PersistenceStore {
111
125
  readonly backend: PersistenceBackend;
112
126
  migrate(): Promise<MigrationReport>;
@@ -124,6 +138,8 @@ export interface PersistenceStore {
124
138
  waMessageId: string;
125
139
  }): Promise<MessageRecord | null>;
126
140
  listMessages(input: ListMessagesInput): Promise<ListMessagesResult>;
141
+ getLatestInboundMessageAt(input: LatestInboundMessageInput): Promise<string | null>;
142
+ countOutboxPending(): Promise<number>;
127
143
  close(): Promise<void>;
128
144
  }
129
145
  export declare class PersistenceError extends Error {
@@ -134,5 +150,8 @@ export { createSqlitePersistence } from "./sqlite";
134
150
  export type { SqlitePersistenceOptions } from "./sqlite";
135
151
  export { runOutboxWorkerOnce } from "./outbox";
136
152
  export type { OutboxWorkerOptions, OutboxWorkerReport } from "./outbox";
153
+ export { startOutboxWorker } from "./outboxWorker";
154
+ export type { OutboxScheduler, OutboxTimerHandle, OutboxWorkerHandle, OutboxWorkerTickReport, StartOutboxWorkerOptions } from "./outboxWorker";
155
+ export { getConversationWindowState, canSendFreeForm } from "./conversationWindow";
137
156
  export { createPostgresPersistence, createPostgresPersistenceWithClient, REDACTED_POSTGRES_LOCATION } from "./postgres";
138
157
  export type { PostgresPersistenceOptions, PostgresClientLike, PostgresQueryResult } from "./postgres";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const CURRENT_SCHEMA_VERSION = 3;
1
+ export const CURRENT_SCHEMA_VERSION = 4;
2
2
  export const REDACTED_SQLITE_LOCATION = "[REDACTED_SQLITE_DATABASE]";
3
3
 
4
4
  export class PersistenceError extends Error {
@@ -11,6 +11,11 @@ export class PersistenceError extends Error {
11
11
  }
12
12
  export { createSqlitePersistence } from "./sqlite";
13
13
  export { runOutboxWorkerOnce } from "./outbox";
14
+ export { startOutboxWorker } from "./outboxWorker";
15
+ export {
16
+ getConversationWindowState,
17
+ canSendFreeForm
18
+ } from "./conversationWindow";
14
19
  export {
15
20
  createPostgresPersistence,
16
21
  createPostgresPersistenceWithClient,
@@ -0,0 +1,43 @@
1
+ import type { OutboxItem, PersistenceStore } from "./index";
2
+ import { type OutboxWorkerReport } from "./outbox";
3
+ /** Opaque timer handle returned by {@link OutboxScheduler.setTimeout}. */
4
+ export type OutboxTimerHandle = unknown;
5
+ /**
6
+ * Injectable timer seam. The default implementation uses the global
7
+ * `setTimeout`/`clearTimeout`; tests pass a fake that queues callbacks for
8
+ * manual, deterministic firing.
9
+ */
10
+ export interface OutboxScheduler {
11
+ setTimeout(callback: () => void, delayMs: number): OutboxTimerHandle;
12
+ clearTimeout(handle: OutboxTimerHandle): void;
13
+ }
14
+ /** Report delivered to {@link OutboxWorkerOptions.onReport} after each tick. */
15
+ export interface OutboxWorkerTickReport extends OutboxWorkerReport {
16
+ /** Pending outbox depth at the moment the tick completed. */
17
+ readonly pending: number;
18
+ }
19
+ export interface StartOutboxWorkerOptions {
20
+ /** Called for each claimed outbox item. Errors are caught per item. */
21
+ readonly handler: (item: OutboxItem) => Promise<void>;
22
+ /** Tick interval in ms. Integer 100..3_600_000. Default 5000. */
23
+ readonly intervalMs?: number;
24
+ /** Items claimed per tick. Integer 1..100. Default 10. */
25
+ readonly batchLimit?: number;
26
+ /** Retry delay for failed items in ms. Integer 0..86_400_000. Default 30000. */
27
+ readonly retryDelayMs?: number;
28
+ /** Invoked with the combined tick report after each run. */
29
+ readonly onReport?: (report: OutboxWorkerTickReport) => void;
30
+ /** Invoked when claim/count/store errors are swallowed inside a tick. */
31
+ readonly onError?: (error: unknown) => void;
32
+ /** Injectable ISO clock for runOutboxWorkerOnce + countOutboxPending. */
33
+ readonly now?: () => string;
34
+ /** Injectable timer seam. Defaults to the global timers. */
35
+ readonly schedule?: OutboxScheduler;
36
+ }
37
+ export interface OutboxWorkerHandle {
38
+ /** Cancel the pending timer and await any in-flight run. Double-stop is a no-op. */
39
+ stop(): Promise<void>;
40
+ /** True until stop() has been called. */
41
+ running(): boolean;
42
+ }
43
+ export declare function startOutboxWorker(store: PersistenceStore, options: StartOutboxWorkerOptions): OutboxWorkerHandle;
@@ -0,0 +1,123 @@
1
+ import { runOutboxWorkerOnce } from "./outbox";
2
+ const DEFAULT_INTERVAL_MS = 5000;
3
+ const DEFAULT_BATCH_LIMIT = 10;
4
+ const DEFAULT_RETRY_DELAY_MS = 30000;
5
+ const MIN_INTERVAL_MS = 100;
6
+ const MAX_INTERVAL_MS = 3600000;
7
+ const MIN_BATCH_LIMIT = 1;
8
+ const MAX_BATCH_LIMIT = 100;
9
+ const MIN_RETRY_DELAY_MS = 0;
10
+ const MAX_RETRY_DELAY_MS = 86400000;
11
+ function validateInteger(value, min, max, name) {
12
+ if (!Number.isInteger(value) || value < min || value > max) {
13
+ throw new RangeError(`${name} must be an integer from ${min} to ${max}.`);
14
+ }
15
+ return value;
16
+ }
17
+ const DEFAULT_SCHEDULER = {
18
+ setTimeout(callback, delayMs) {
19
+ return globalThis.setTimeout(callback, delayMs);
20
+ },
21
+ clearTimeout(handle) {
22
+ globalThis.clearTimeout(handle);
23
+ }
24
+ };
25
+ function isStoreLike(value) {
26
+ return value !== null && typeof value === "object" && typeof value.claimOutboxItems === "function" && typeof value.countOutboxPending === "function";
27
+ }
28
+ export function startOutboxWorker(store, options) {
29
+ if (!isStoreLike(store))
30
+ throw new TypeError("store must be a PersistenceStore exposing claimOutboxItems and countOutboxPending.");
31
+ if (!isRecord(options))
32
+ throw new TypeError("options must be an object.");
33
+ if (typeof options.handler !== "function")
34
+ throw new TypeError("options.handler must be a function.");
35
+ const intervalMs = validateInteger(options.intervalMs ?? DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, MAX_INTERVAL_MS, "intervalMs");
36
+ const batchLimit = validateInteger(options.batchLimit ?? DEFAULT_BATCH_LIMIT, MIN_BATCH_LIMIT, MAX_BATCH_LIMIT, "batchLimit");
37
+ const retryDelayMs = validateInteger(options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS, MIN_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, "retryDelayMs");
38
+ const onReport = options.onReport;
39
+ if (onReport !== undefined && typeof onReport !== "function")
40
+ throw new TypeError("options.onReport must be a function.");
41
+ const onError = options.onError;
42
+ if (onError !== undefined && typeof onError !== "function")
43
+ throw new TypeError("options.onError must be a function.");
44
+ const now = options.now ?? (() => new Date().toISOString());
45
+ if (typeof now !== "function")
46
+ throw new TypeError("options.now must be a function.");
47
+ const schedule = options.schedule ?? DEFAULT_SCHEDULER;
48
+ if (!isRecord(schedule) || typeof schedule.setTimeout !== "function" || typeof schedule.clearTimeout !== "function") {
49
+ throw new TypeError("options.schedule must expose setTimeout and clearTimeout functions.");
50
+ }
51
+ const handler = options.handler;
52
+ let stopped = false;
53
+ let inFlight = false;
54
+ let timerHandle = null;
55
+ let stopResolve = null;
56
+ function arm() {
57
+ if (stopped)
58
+ return;
59
+ timerHandle = schedule.setTimeout(fire, intervalMs);
60
+ }
61
+ async function fire() {
62
+ timerHandle = null;
63
+ if (stopped || inFlight)
64
+ return;
65
+ inFlight = true;
66
+ try {
67
+ let report;
68
+ try {
69
+ const once = await runOutboxWorkerOnce(store, {
70
+ now: now(),
71
+ limit: batchLimit,
72
+ retryDelayMs,
73
+ handler
74
+ });
75
+ const pending = await store.countOutboxPending();
76
+ report = Object.freeze({ processed: once.processed, succeeded: once.succeeded, failed: once.failed, pending });
77
+ } catch (cause) {
78
+ if (onError) {
79
+ try {
80
+ onError(cause);
81
+ } catch {}
82
+ }
83
+ report = Object.freeze({ processed: 0, succeeded: 0, failed: 0, pending: 0 });
84
+ }
85
+ if (onReport && !stopped) {
86
+ try {
87
+ onReport(report);
88
+ } catch {}
89
+ }
90
+ } finally {
91
+ inFlight = false;
92
+ if (stopped) {
93
+ if (stopResolve)
94
+ stopResolve();
95
+ } else {
96
+ arm();
97
+ }
98
+ }
99
+ }
100
+ arm();
101
+ return {
102
+ async stop() {
103
+ if (stopped)
104
+ return;
105
+ stopped = true;
106
+ if (timerHandle !== null) {
107
+ schedule.clearTimeout(timerHandle);
108
+ timerHandle = null;
109
+ }
110
+ if (inFlight) {
111
+ await new Promise((resolve) => {
112
+ stopResolve = resolve;
113
+ });
114
+ }
115
+ },
116
+ running() {
117
+ return !stopped;
118
+ }
119
+ };
120
+ }
121
+ function isRecord(value) {
122
+ return typeof value === "object" && value !== null;
123
+ }
package/dist/postgres.js CHANGED
@@ -178,6 +178,23 @@ class PostgresPersistenceStore {
178
178
  const nextCursor = rows.length > query.limit ? items[items.length - 1]?.rowId ?? null : null;
179
179
  return Object.freeze({ items, nextCursor });
180
180
  }
181
+ async getLatestInboundMessageAt(input) {
182
+ this.#assertOpen();
183
+ const record = validateRecordInput(input, "latest inbound lookup");
184
+ const phone = validateRecordString(record.phone, "phone");
185
+ const result = await this.#client.query(`SELECT created_at FROM wats_messages
186
+ WHERE direction = 'inbound' AND from_phone = $1
187
+ ORDER BY created_at DESC
188
+ LIMIT 1`, [phone]);
189
+ const row = result.rows[0];
190
+ return row === undefined ? null : row.created_at;
191
+ }
192
+ async countOutboxPending() {
193
+ this.#assertOpen();
194
+ const result = await this.#client.query("SELECT COUNT(*) AS count FROM wats_outbox WHERE status = $1", ["pending"]);
195
+ const row = result.rows[0];
196
+ return row === undefined ? 0 : numeric(row.count);
197
+ }
181
198
  async close() {
182
199
  if (this.#closed)
183
200
  return;
@@ -284,6 +301,15 @@ const POSTGRES_MIGRATIONS = Object.freeze([
284
301
  )`,
285
302
  `CREATE INDEX IF NOT EXISTS wats_message_status_events_wa_message_id_idx ON wats_message_status_events (wa_message_id, id)`
286
303
  ])
304
+ },
305
+ {
306
+ id: "004_inbound_window_index",
307
+ version: 4,
308
+ checksum: "sha256:wats-persistence-004-inbound-window-index-v1",
309
+ statements: Object.freeze([
310
+ `CREATE INDEX IF NOT EXISTS wats_messages_direction_from_phone_created_at_idx
311
+ ON wats_messages (direction, from_phone, created_at DESC)`
312
+ ])
287
313
  }
288
314
  ]);
289
315
  function hasControlChars(value) {
package/dist/sqlite.js CHANGED
@@ -197,6 +197,21 @@ class SqlitePersistenceStore {
197
197
  const nextCursor = rows.length > query.limit ? items[items.length - 1]?.rowId ?? null : null;
198
198
  return Object.freeze({ items, nextCursor });
199
199
  }
200
+ async getLatestInboundMessageAt(input) {
201
+ this.#assertOpen();
202
+ const record = validateRecordInput(input, "latest inbound lookup");
203
+ const phone = validateRecordString(record.phone, "phone");
204
+ const row = this.#database.query(`SELECT created_at FROM wats_messages
205
+ WHERE direction = 'inbound' AND from_phone = ?
206
+ ORDER BY created_at DESC
207
+ LIMIT 1`).get(phone);
208
+ return row === null ? null : row.created_at;
209
+ }
210
+ async countOutboxPending() {
211
+ this.#assertOpen();
212
+ const row = this.#database.query("SELECT COUNT(*) AS count FROM wats_outbox WHERE status = ?").get("pending");
213
+ return row === null ? 0 : row.count;
214
+ }
200
215
  async close() {
201
216
  if (this.#closed)
202
217
  return;
@@ -320,6 +335,15 @@ const MIGRATIONS = Object.freeze([
320
335
  )`,
321
336
  `CREATE INDEX IF NOT EXISTS wats_message_status_events_wa_message_id_idx ON wats_message_status_events (wa_message_id, id)`
322
337
  ])
338
+ },
339
+ {
340
+ id: "004_inbound_window_index",
341
+ version: 4,
342
+ checksum: "sha256:wats-persistence-004-inbound-window-index-v1",
343
+ statements: Object.freeze([
344
+ `CREATE INDEX IF NOT EXISTS wats_messages_direction_from_phone_created_at_idx
345
+ ON wats_messages (direction, from_phone, created_at DESC)`
346
+ ])
323
347
  }
324
348
  ]);
325
349
  function hasControlChars(value) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wats/persistence",
3
- "version": "0.3.29",
3
+ "version": "0.3.30",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "type": "module",