@arcaelas/whatsapp 4.5.0 → 6.0.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 (106) hide show
  1. package/README.md +282 -239
  2. package/build/cjs/decorators.js +0 -1
  3. package/build/cjs/index.d.ts +6 -4
  4. package/build/cjs/index.js +22 -3
  5. package/build/cjs/lib/bot/decorator.d.ts +2 -0
  6. package/build/cjs/lib/bot/decorator.js +6 -1
  7. package/build/cjs/lib/bot/decorators.d.ts +2 -2
  8. package/build/cjs/lib/bot/decorators.js +4 -4
  9. package/build/cjs/lib/bot/index.js +0 -1
  10. package/build/cjs/lib/chat/index.d.ts +381 -204
  11. package/build/cjs/lib/chat/index.js +243 -212
  12. package/build/cjs/lib/contact/index.d.ts +162 -179
  13. package/build/cjs/lib/contact/index.js +96 -191
  14. package/build/cjs/lib/internal.d.ts +40 -0
  15. package/build/cjs/lib/internal.js +38 -0
  16. package/build/cjs/lib/message/index.d.ts +468 -289
  17. package/build/cjs/lib/message/index.js +871 -743
  18. package/build/cjs/lib/status/index.d.ts +60 -70
  19. package/build/cjs/lib/status/index.js +106 -112
  20. package/build/cjs/lib/store/engine/index.d.ts +35 -7
  21. package/build/cjs/lib/store/engine/index.js +6 -4
  22. package/build/cjs/lib/store/engine/lib/file_system/index.d.ts +48 -8
  23. package/build/cjs/lib/store/engine/lib/file_system/index.js +117 -66
  24. package/build/cjs/lib/store/engine/lib/index.d.ts +112 -0
  25. package/build/cjs/lib/store/engine/lib/index.js +212 -0
  26. package/build/cjs/lib/store/engine/lib/redis/index.d.ts +44 -15
  27. package/build/cjs/lib/store/engine/lib/redis/index.js +75 -43
  28. package/build/cjs/lib/store/engine/lib/s3/index.d.ts +44 -1
  29. package/build/cjs/lib/store/engine/lib/s3/index.js +112 -65
  30. package/build/cjs/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  31. package/build/cjs/lib/store/engine/lib/sqlite/index.js +132 -0
  32. package/build/cjs/lib/store/index.d.ts +7 -3
  33. package/build/cjs/lib/store/index.js +14 -5
  34. package/build/cjs/lib/whatsapp/index.d.ts +106 -68
  35. package/build/cjs/lib/whatsapp/index.js +393 -167
  36. package/build/esm/decorators.js +0 -1
  37. package/build/esm/index.d.ts +6 -4
  38. package/build/esm/index.js +5 -3
  39. package/build/esm/lib/bot/decorator.d.ts +2 -0
  40. package/build/esm/lib/bot/decorator.js +6 -1
  41. package/build/esm/lib/bot/decorators.d.ts +2 -2
  42. package/build/esm/lib/bot/decorators.js +4 -4
  43. package/build/esm/lib/bot/index.js +0 -1
  44. package/build/esm/lib/chat/index.d.ts +381 -204
  45. package/build/esm/lib/chat/index.js +243 -212
  46. package/build/esm/lib/contact/index.d.ts +162 -179
  47. package/build/esm/lib/contact/index.js +96 -190
  48. package/build/esm/lib/internal.d.ts +40 -0
  49. package/build/esm/lib/internal.js +34 -0
  50. package/build/esm/lib/message/index.d.ts +468 -289
  51. package/build/esm/lib/message/index.js +866 -738
  52. package/build/esm/lib/status/index.d.ts +60 -70
  53. package/build/esm/lib/status/index.js +105 -111
  54. package/build/esm/lib/store/engine/index.d.ts +35 -7
  55. package/build/esm/lib/store/engine/index.js +4 -3
  56. package/build/esm/lib/store/engine/lib/file_system/index.d.ts +48 -8
  57. package/build/esm/lib/store/engine/lib/file_system/index.js +117 -66
  58. package/build/esm/lib/store/engine/lib/index.d.ts +112 -0
  59. package/build/esm/lib/store/engine/lib/index.js +205 -0
  60. package/build/esm/lib/store/engine/lib/redis/index.d.ts +44 -15
  61. package/build/esm/lib/store/engine/lib/redis/index.js +73 -41
  62. package/build/esm/lib/store/engine/lib/s3/index.d.ts +44 -1
  63. package/build/esm/lib/store/engine/lib/s3/index.js +111 -64
  64. package/build/esm/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  65. package/build/esm/lib/store/engine/lib/sqlite/index.js +128 -0
  66. package/build/esm/lib/store/index.d.ts +7 -3
  67. package/build/esm/lib/store/index.js +13 -5
  68. package/build/esm/lib/whatsapp/index.d.ts +106 -68
  69. package/build/esm/lib/whatsapp/index.js +395 -169
  70. package/package.json +25 -6
  71. package/build/cjs/decorators.js.map +0 -1
  72. package/build/cjs/index.js.map +0 -1
  73. package/build/cjs/lib/bot/decorator.js.map +0 -1
  74. package/build/cjs/lib/bot/decorators.js.map +0 -1
  75. package/build/cjs/lib/bot/index.js.map +0 -1
  76. package/build/cjs/lib/chat/index.js.map +0 -1
  77. package/build/cjs/lib/contact/index.js.map +0 -1
  78. package/build/cjs/lib/message/index.js.map +0 -1
  79. package/build/cjs/lib/status/index.js.map +0 -1
  80. package/build/cjs/lib/store/engine/index.js.map +0 -1
  81. package/build/cjs/lib/store/engine/lib/file_system/index.js.map +0 -1
  82. package/build/cjs/lib/store/engine/lib/redis/index.js.map +0 -1
  83. package/build/cjs/lib/store/engine/lib/s3/index.js.map +0 -1
  84. package/build/cjs/lib/store/index.js.map +0 -1
  85. package/build/cjs/lib/whatsapp/index.js.map +0 -1
  86. package/build/cjs/test.d.ts +0 -1
  87. package/build/cjs/test.js +0 -71
  88. package/build/cjs/test.js.map +0 -1
  89. package/build/esm/decorators.js.map +0 -1
  90. package/build/esm/index.js.map +0 -1
  91. package/build/esm/lib/bot/decorator.js.map +0 -1
  92. package/build/esm/lib/bot/decorators.js.map +0 -1
  93. package/build/esm/lib/bot/index.js.map +0 -1
  94. package/build/esm/lib/chat/index.js.map +0 -1
  95. package/build/esm/lib/contact/index.js.map +0 -1
  96. package/build/esm/lib/message/index.js.map +0 -1
  97. package/build/esm/lib/status/index.js.map +0 -1
  98. package/build/esm/lib/store/engine/index.js.map +0 -1
  99. package/build/esm/lib/store/engine/lib/file_system/index.js.map +0 -1
  100. package/build/esm/lib/store/engine/lib/redis/index.js.map +0 -1
  101. package/build/esm/lib/store/engine/lib/s3/index.js.map +0 -1
  102. package/build/esm/lib/store/index.js.map +0 -1
  103. package/build/esm/lib/whatsapp/index.js.map +0 -1
  104. package/build/esm/test.d.ts +0 -1
  105. package/build/esm/test.js +0 -66
  106. package/build/esm/test.js.map +0 -1
@@ -6,21 +6,21 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.RedisEngine = void 0;
9
- /**
10
- * Normaliza un path colapsando slashes redundantes.
11
- * Normalizes a path by collapsing redundant slashes.
12
- */
13
- function normalize_path(path) {
14
- return path.replace(/\/+/g, '/').replace(/^\/|\/$/g, '');
15
- }
9
+ const lib_1 = require("../../../../../lib/store/engine/lib");
16
10
  /**
17
11
  * Driver de persistencia con Redis.
18
12
  *
19
13
  * Keyspaces:
20
14
  * - `<prefix>:doc:<path>` → string del documento.
21
- * - `<prefix>:idx:<parent>` → sorted set (score=mtime, member=path completo).
15
+ * - `<prefix>:idx:<parent>` → sorted set (score explícito o de escritura, member=path completo).
22
16
  *
23
- * `list` combina ZREVRANGE + MGET O(log N + M) en una sola round-trip.
17
+ * El índice ordenado vive en Redis: `list` combina ZREVRANGE + MGET (dos round-trips, O(log N + M))
18
+ * y `count` es un ZCARD O(1); las escrituras agrupan documento e índice en un pipeline para que
19
+ * no queden documentos huérfanos del índice si el proceso muere entre ambas operaciones.
20
+ *
21
+ * Redis persistence driver. The sorted index lives in Redis: `list` combines ZREVRANGE + MGET
22
+ * and `count` is an O(1) ZCARD; writes group document and index in a pipeline so no document
23
+ * is left orphaned from the index when the process dies between both operations.
24
24
  *
25
25
  * @example
26
26
  * import IORedis from 'ioredis';
@@ -33,20 +33,11 @@ class RedisEngine {
33
33
  }
34
34
  /** @internal */
35
35
  _doc_key(path) {
36
- return `${this._prefix}:doc:${normalize_path(path)}`;
36
+ return `${this._prefix}:doc:${(0, lib_1.normalize_path)(path)}`;
37
37
  }
38
38
  /** @internal */
39
39
  _idx_key(parent) {
40
- return `${this._prefix}:idx:${normalize_path(parent)}`;
41
- }
42
- /** @internal */
43
- _split(path) {
44
- const full = normalize_path(path);
45
- const i = full.lastIndexOf('/');
46
- if (i === -1) {
47
- return { parent: '', full };
48
- }
49
- return { parent: full.slice(0, i), full };
40
+ return `${this._prefix}:idx:${(0, lib_1.normalize_path)(parent)}`;
50
41
  }
51
42
  /**
52
43
  * Lee el valor de un documento.
@@ -56,38 +47,62 @@ class RedisEngine {
56
47
  return this._client.get(this._doc_key(path));
57
48
  }
58
49
  /**
59
- * Escribe el valor y actualiza el índice del padre con el timestamp actual.
60
- * Writes the value and updates the parent's index with current timestamp.
50
+ * Escribe el valor y su entrada de índice en una sola operación; `score` fija el orden
51
+ * de `list` (por defecto, la hora de escritura).
52
+ * Writes the value and its index entry in a single operation; `score` drives `list`
53
+ * ordering (write time by default).
61
54
  */
62
- async set(path, value) {
63
- const { parent, full } = this._split(path);
64
- await this._client.set(this._doc_key(full), value);
65
- await this._client.zadd(this._idx_key(parent), Date.now(), full);
55
+ async set(path, value, score) {
56
+ const { parent } = (0, lib_1.split_path)(path);
57
+ const full = (0, lib_1.normalize_path)(path);
58
+ const doc_key = this._doc_key(full);
59
+ const idx_key = this._idx_key(parent);
60
+ const rank = score ?? Date.now();
61
+ const pipeline = this._client.pipeline?.();
62
+ if (pipeline) {
63
+ pipeline.set(doc_key, value);
64
+ pipeline.zadd(idx_key, rank, full);
65
+ await pipeline.exec();
66
+ }
67
+ else {
68
+ await this._client.set(doc_key, value);
69
+ await this._client.zadd(idx_key, rank, full);
70
+ }
66
71
  }
67
72
  /**
68
- * Elimina el doc, su índice y todo el sub-árbol.
69
- * Deletes the doc, its index, and the entire subtree.
73
+ * Elimina el doc, su entrada de índice y todo el sub-árbol.
74
+ * Deletes the doc, its index entry, and the entire subtree.
70
75
  */
71
76
  async unset(path) {
72
- const { parent, full } = this._split(path);
73
- await this._client.del(this._doc_key(full));
74
- await this._client.zrem(this._idx_key(parent), full);
75
- await this._delete_pattern(`${this._prefix}:doc:${full}/*`);
76
- await this._delete_pattern(`${this._prefix}:idx:${full}`);
77
- await this._delete_pattern(`${this._prefix}:idx:${full}/*`);
77
+ const { parent } = (0, lib_1.split_path)(path);
78
+ const full = (0, lib_1.normalize_path)(path);
79
+ const pipeline = this._client.pipeline?.();
80
+ if (pipeline) {
81
+ pipeline.del([this._doc_key(full), `${this._doc_key(full)}:bin`]);
82
+ pipeline.zrem(this._idx_key(parent), full);
83
+ await pipeline.exec();
84
+ }
85
+ else {
86
+ await this._client.del([this._doc_key(full), `${this._doc_key(full)}:bin`]);
87
+ await this._client.zrem(this._idx_key(parent), full);
88
+ }
89
+ await Promise.all([
90
+ this._delete_pattern(`${this._prefix}:doc:${full}/*`),
91
+ this._delete_pattern(`${this._prefix}:idx:${full}`),
92
+ this._delete_pattern(`${this._prefix}:idx:${full}/*`),
93
+ ]);
78
94
  return true;
79
95
  }
80
96
  /**
81
- * Lista valores de los hijos directos, ordenados por mtime DESC en una round-trip.
82
- * Lists direct children values ordered by mtime DESC in a single round-trip.
97
+ * Lista valores de los hijos directos, ordenados por score DESC en dos round-trips.
98
+ * Lists direct children values ordered by score DESC in two round-trips.
83
99
  */
84
100
  async list(path, offset = 0, limit = 50) {
85
- const { full } = this._split(path);
86
- const members = await this._client.zrevrange(this._idx_key(full), offset, offset + limit - 1);
101
+ const members = await this._client.zrevrange(this._idx_key(path), offset, offset + limit - 1);
87
102
  if (members.length === 0) {
88
103
  return [];
89
104
  }
90
- const raws = await this._client.mget(members.map((m) => this._doc_key(m)));
105
+ const raws = await this._client.mget(members.map((member) => this._doc_key(member)));
91
106
  return raws.filter((raw) => raw !== null);
92
107
  }
93
108
  /**
@@ -95,8 +110,26 @@ class RedisEngine {
95
110
  * Counts direct children in O(1) via ZCARD.
96
111
  */
97
112
  async count(path) {
98
- const { full } = this._split(path);
99
- return this._client.zcard(this._idx_key(full));
113
+ return this._client.zcard(this._idx_key(path));
114
+ }
115
+ /**
116
+ * Lee el binario del documento. Requiere un cliente con soporte de buffers (ioredis lo
117
+ * trae con `getBuffer`); sin él la librería cae al documento serializado.
118
+ * Reads the document binary. Requires a buffer-capable client (ioredis ships `getBuffer`);
119
+ * without it the library falls back to the serialized document.
120
+ */
121
+ async get_buffer(path) {
122
+ return (await this._client.getBuffer?.(`${this._doc_key(path)}:bin`)) ?? null;
123
+ }
124
+ /**
125
+ * Escribe el binario del documento en su propia key, sin JSON ni base64.
126
+ * Writes the document binary in its own key, with no JSON nor base64.
127
+ */
128
+ async set_buffer(path, data, score) {
129
+ const { parent } = (0, lib_1.split_path)(path);
130
+ const full = (0, lib_1.normalize_path)(path);
131
+ await this._client.setBuffer?.(`${this._doc_key(full)}:bin`, data);
132
+ await this._client.zadd(this._idx_key(parent), score ?? Date.now(), full);
100
133
  }
101
134
  /**
102
135
  * Vacía todo el prefix del cliente.
@@ -114,7 +147,7 @@ class RedisEngine {
114
147
  async _delete_pattern(pattern) {
115
148
  let cursor = '0';
116
149
  do {
117
- const [next, batch] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
150
+ const [next, batch] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', 500);
118
151
  cursor = next;
119
152
  if (batch.length > 0) {
120
153
  await this._client.del(batch);
@@ -123,4 +156,3 @@ class RedisEngine {
123
156
  }
124
157
  }
125
158
  exports.RedisEngine = RedisEngine;
126
- //# sourceMappingURL=index.js.map
@@ -33,7 +33,26 @@ interface S3EngineOptions {
33
33
  * Default: `false` (no cache).
34
34
  */
35
35
  cache?: false | CacheOptions;
36
+ /** Prefijos indexados simultáneamente en memoria. / Simultaneously in-memory indexed prefixes. */
37
+ cached?: number;
36
38
  }
39
+ /**
40
+ * Driver de persistencia con AWS S3.
41
+ *
42
+ * Para que `list`/`count` no recorran todo el prefijo en cada página mantiene un índice
43
+ * ordenado por prefijo (`SortedIndex`), acotado por LRU y respaldado en el objeto `.order`:
44
+ * ahí viven los scores explícitos que S3 no puede representar (`LastModified` es de sólo
45
+ * lectura), de modo que el orden cronológico sobrevive a los re-syncs igual que en los
46
+ * demás drivers. Si el objeto `.order` falta, el índice se reconstruye listando el prefijo
47
+ * una única vez y ordenando por `LastModified`.
48
+ *
49
+ * AWS S3 persistence driver. To keep `list`/`count` from walking the whole prefix on every
50
+ * page it maintains a per-prefix sorted index (`SortedIndex`), LRU-bounded and backed by the
51
+ * `.order` object: it holds the explicit scores S3 cannot represent (`LastModified` is
52
+ * read-only), so chronological order survives re-syncs just like on the other drivers. When
53
+ * `.order` is missing the index is rebuilt listing the prefix once and ordering by
54
+ * `LastModified`.
55
+ */
37
56
  export declare class S3Engine implements Engine {
38
57
  private readonly _client;
39
58
  private readonly _bucket;
@@ -41,6 +60,8 @@ export declare class S3Engine implements Engine {
41
60
  private readonly _cache_opts;
42
61
  /** @internal Caché local de documentos, con su timer de expiración. / Local cache of documents, with its expiration timer. */
43
62
  private readonly _cache;
63
+ /** @internal Índices por prefijo, acotados por LRU. / Per-prefix indexes, LRU-bounded. */
64
+ private readonly _indexes;
44
65
  constructor(options: S3EngineOptions);
45
66
  private _key;
46
67
  /**
@@ -55,11 +76,33 @@ export declare class S3Engine implements Engine {
55
76
  * Replaces the previous timer when the key was already cached so timers don't pile up.
56
77
  */
57
78
  private _cache_set;
79
+ /**
80
+ * @internal
81
+ * Índice del prefijo: de la caché, del objeto `.order` o reconstruido listando el prefijo
82
+ * una sola vez y ordenando por `LastModified`.
83
+ * Prefix index: from the cache, from the `.order` object or rebuilt listing the prefix
84
+ * once and ordering by `LastModified`.
85
+ */
86
+ private _index;
58
87
  get(key: string): Promise<string | null>;
59
- set(key: string, value: string): Promise<void>;
88
+ /**
89
+ * Escribe el valor y registra su score en el índice del prefijo, que S3 no puede
90
+ * derivar por sí solo (`LastModified` es de sólo lectura).
91
+ * Writes the value and records its score in the prefix index, which S3 cannot derive
92
+ * on its own (`LastModified` is read-only).
93
+ */
94
+ set(key: string, value: string, score?: number): Promise<void>;
95
+ /**
96
+ * Lista los valores de los hijos directos, ordenados por score DESC.
97
+ * Lists direct children values ordered by score DESC.
98
+ */
60
99
  list(path: string, offset?: number, limit?: number): Promise<string[]>;
61
100
  delete_prefix(prefix: string): Promise<number>;
62
101
  unset(path: string): Promise<boolean>;
102
+ /**
103
+ * Cuenta hijos directos desde el índice del prefijo.
104
+ * Counts direct children from the prefix index.
105
+ */
63
106
  count(path: string): Promise<number>;
64
107
  clear(): Promise<void>;
65
108
  }
@@ -7,13 +7,26 @@
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.S3Engine = void 0;
9
9
  const client_s3_1 = require("@aws-sdk/client-s3");
10
+ const lib_1 = require("../../../../../lib/store/engine/lib");
11
+ /** Objeto que guarda el orden de los hijos de un prefijo. / Object holding the ordering of a prefix children. */
12
+ const ORDER_KEY = '.order';
10
13
  /**
11
- * Normaliza un path colapsando slashes redundantes.
12
- * Normalizes a path by collapsing redundant slashes.
14
+ * Driver de persistencia con AWS S3.
15
+ *
16
+ * Para que `list`/`count` no recorran todo el prefijo en cada página mantiene un índice
17
+ * ordenado por prefijo (`SortedIndex`), acotado por LRU y respaldado en el objeto `.order`:
18
+ * ahí viven los scores explícitos que S3 no puede representar (`LastModified` es de sólo
19
+ * lectura), de modo que el orden cronológico sobrevive a los re-syncs igual que en los
20
+ * demás drivers. Si el objeto `.order` falta, el índice se reconstruye listando el prefijo
21
+ * una única vez y ordenando por `LastModified`.
22
+ *
23
+ * AWS S3 persistence driver. To keep `list`/`count` from walking the whole prefix on every
24
+ * page it maintains a per-prefix sorted index (`SortedIndex`), LRU-bounded and backed by the
25
+ * `.order` object: it holds the explicit scores S3 cannot represent (`LastModified` is
26
+ * read-only), so chronological order survives re-syncs just like on the other drivers. When
27
+ * `.order` is missing the index is rebuilt listing the prefix once and ordering by
28
+ * `LastModified`.
13
29
  */
14
- function normalize_path(path) {
15
- return path.replace(/\/+/g, '/').replace(/^\/|\/$/g, '');
16
- }
17
30
  class S3Engine {
18
31
  constructor(options) {
19
32
  /** @internal Caché local de documentos, con su timer de expiración. / Local cache of documents, with its expiration timer. */
@@ -22,9 +35,10 @@ class S3Engine {
22
35
  this._bucket = options.bucket;
23
36
  this._prefix = options.basedir.endsWith('/') ? options.basedir : `${options.basedir}/`;
24
37
  this._cache_opts = options.cache ?? false;
38
+ this._indexes = new lib_1.IndexCache(options.cached ?? 12);
25
39
  }
26
40
  _key(key) {
27
- return `${this._prefix}${normalize_path(key).replace(/@/g, '_at_')}`;
41
+ return `${this._prefix}${(0, lib_1.normalize_path)(key).replace(/@/g, '_at_')}`;
28
42
  }
29
43
  /**
30
44
  * Indica si un path es elegible para caché según la configuración `when`.
@@ -49,69 +63,108 @@ class S3Engine {
49
63
  timer: setTimeout(() => this._cache.delete(path), this._cache_opts.ttl),
50
64
  });
51
65
  }
66
+ /**
67
+ * @internal
68
+ * Índice del prefijo: de la caché, del objeto `.order` o reconstruido listando el prefijo
69
+ * una sola vez y ordenando por `LastModified`.
70
+ * Prefix index: from the cache, from the `.order` object or rebuilt listing the prefix
71
+ * once and ordering by `LastModified`.
72
+ */
73
+ async _index(path) {
74
+ const key = (0, lib_1.normalize_path)(path);
75
+ const cached = this._indexes.get(key);
76
+ if (cached) {
77
+ return cached;
78
+ }
79
+ const parent = `${this._key(key)}/`;
80
+ const index = new lib_1.SortedIndex(async (entries) => {
81
+ await this._client
82
+ .send(new client_s3_1.PutObjectCommand({
83
+ Bucket: this._bucket,
84
+ Key: `${parent}${ORDER_KEY}`,
85
+ Body: entries.map(([name, score]) => `${score}\t${name}`).join('\n'),
86
+ ContentType: 'text/plain',
87
+ }))
88
+ .catch(() => null);
89
+ });
90
+ const persisted = await this._client
91
+ .send(new client_s3_1.GetObjectCommand({ Bucket: this._bucket, Key: `${parent}${ORDER_KEY}` }))
92
+ .then((res) => res.Body?.transformToString('utf-8') ?? null)
93
+ .catch(() => null);
94
+ if (persisted) {
95
+ index.load(persisted
96
+ .split('\n')
97
+ .filter(Boolean)
98
+ .map((line) => {
99
+ const cut = line.indexOf('\t');
100
+ return [line.slice(cut + 1), Number(line.slice(0, cut))];
101
+ }));
102
+ }
103
+ else {
104
+ const children = new Map();
105
+ let token;
106
+ do {
107
+ const res = await this._client.send(new client_s3_1.ListObjectsV2Command({ Bucket: this._bucket, Prefix: parent, ContinuationToken: token, MaxKeys: 1000 }));
108
+ for (const object of res.Contents ?? []) {
109
+ const rest = object.Key?.slice(parent.length);
110
+ const name = rest?.split('/')[0];
111
+ if (name && name !== ORDER_KEY) {
112
+ children.set(name, Math.max(children.get(name) ?? 0, object.LastModified?.getTime() ?? 0));
113
+ }
114
+ }
115
+ token = res.NextContinuationToken;
116
+ } while (token);
117
+ index.load(children);
118
+ }
119
+ this._indexes.set(key, index);
120
+ return index;
121
+ }
52
122
  async get(key) {
53
123
  if (this._cacheable(key) && this._cache.has(key)) {
54
124
  return this._cache.get(key).value;
55
125
  }
56
- const value = await (async () => {
57
- try {
58
- const res = await this._client.send(new client_s3_1.GetObjectCommand({ Bucket: this._bucket, Key: this._key(key) }));
59
- return (await res.Body?.transformToString('utf-8')) ?? null;
60
- }
61
- catch {
62
- return null;
63
- }
64
- })();
126
+ const value = await this._client
127
+ .send(new client_s3_1.GetObjectCommand({ Bucket: this._bucket, Key: this._key(key) }))
128
+ .then((res) => res.Body?.transformToString('utf-8') ?? null)
129
+ .catch(() => null);
65
130
  if (this._cacheable(key)) {
66
131
  this._cache_set(key, value);
67
132
  }
68
133
  return value;
69
134
  }
70
- async set(key, value) {
135
+ /**
136
+ * Escribe el valor y registra su score en el índice del prefijo, que S3 no puede
137
+ * derivar por sí solo (`LastModified` es de sólo lectura).
138
+ * Writes the value and records its score in the prefix index, which S3 cannot derive
139
+ * on its own (`LastModified` is read-only).
140
+ */
141
+ async set(key, value, score) {
71
142
  const remote = this._client.send(new client_s3_1.PutObjectCommand({ Bucket: this._bucket, Key: this._key(key), Body: value, ContentType: 'application/json' }));
72
143
  if (this._cacheable(key)) {
73
144
  this._cache_set(key, value);
74
145
  }
146
+ const { parent, name } = (0, lib_1.split_path)(key);
147
+ // A diferencia del filesystem, S3 no tiene dónde guardar el score fuera del índice
148
+ // (`LastModified` es de sólo lectura), así que el índice se carga aunque nadie haya
149
+ // paginado todavía; si no, el orden cronológico se perdería en la primera escritura.
150
+ // Unlike the filesystem, S3 has nowhere to keep the score outside the index
151
+ // (`LastModified` is read-only), so the index is loaded even when nobody paginated
152
+ // yet; otherwise chronological order would be lost on the first write.
153
+ (await this._index(parent)).set(name, score ?? Date.now());
75
154
  await remote;
76
155
  }
156
+ /**
157
+ * Lista los valores de los hijos directos, ordenados por score DESC.
158
+ * Lists direct children values ordered by score DESC.
159
+ */
77
160
  async list(path, offset = 0, limit = 50) {
78
- const parent = `${this._prefix}${normalize_path(path).replace(/@/g, '_at_')}/`;
79
- const children = new Map();
80
- let token;
81
- do {
82
- const res = await this._client.send(new client_s3_1.ListObjectsV2Command({
83
- Bucket: this._bucket,
84
- Prefix: parent,
85
- ContinuationToken: token,
86
- MaxKeys: 1000,
87
- }));
88
- for (const obj of res.Contents ?? []) {
89
- if (!obj.Key)
90
- continue;
91
- const rest = obj.Key.slice(parent.length);
92
- const child_key = `${parent}${rest.split('/')[0]}`;
93
- const mtime = obj.LastModified?.getTime() ?? 0;
94
- children.set(child_key, Math.max(children.get(child_key) ?? 0, mtime));
95
- }
96
- token = res.NextContinuationToken;
97
- } while (token);
98
- const ordered = [...children.entries()]
99
- .sort((a, b) => b[1] - a[1])
100
- .slice(offset, offset + limit)
101
- .map(([key]) => key);
102
- const values = await Promise.all(ordered.map(async (key) => {
103
- try {
104
- const res = await this._client.send(new client_s3_1.GetObjectCommand({ Bucket: this._bucket, Key: key }));
105
- return (await res.Body?.transformToString('utf-8')) ?? null;
106
- }
107
- catch {
108
- return null;
109
- }
110
- }));
161
+ const parent = (0, lib_1.normalize_path)(path);
162
+ const page = (await this._index(parent)).page(offset, limit);
163
+ const values = await Promise.all(page.map((name) => this.get(`${parent}/${name}`)));
111
164
  return values.filter((value) => value !== null);
112
165
  }
113
166
  async delete_prefix(prefix) {
114
- const full_prefix = `${this._prefix}${normalize_path(prefix).replace(/@/g, '_at_')}`;
167
+ const full_prefix = this._key(prefix);
115
168
  let deleted = 0;
116
169
  let token;
117
170
  do {
@@ -139,31 +192,25 @@ class S3Engine {
139
192
  }
140
193
  }
141
194
  }
195
+ const { parent, name } = (0, lib_1.split_path)(path);
196
+ (await this._index(parent)).delete(name);
197
+ this._indexes.drop((0, lib_1.normalize_path)(path));
142
198
  return (await this.delete_prefix(path)) > 0;
143
199
  }
200
+ /**
201
+ * Cuenta hijos directos desde el índice del prefijo.
202
+ * Counts direct children from the prefix index.
203
+ */
144
204
  async count(path) {
145
- const full_prefix = `${this._prefix}${normalize_path(path).replace(/@/g, '_at_')}`;
146
- let total = 0;
147
- let token;
148
- do {
149
- const res = await this._client.send(new client_s3_1.ListObjectsV2Command({
150
- Bucket: this._bucket,
151
- Prefix: full_prefix,
152
- ContinuationToken: token,
153
- MaxKeys: 1000,
154
- }));
155
- total += res.Contents?.length ?? 0;
156
- token = res.NextContinuationToken;
157
- } while (token);
158
- return total;
205
+ return (await this._index(path)).size;
159
206
  }
160
207
  async clear() {
161
208
  for (const { timer } of this._cache.values()) {
162
209
  clearTimeout(timer);
163
210
  }
164
211
  this._cache.clear();
212
+ this._indexes.clear();
165
213
  await this.delete_prefix('');
166
214
  }
167
215
  }
168
216
  exports.S3Engine = S3Engine;
169
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,110 @@
1
+ /**
2
+ * @file store/engine/lib/sqlite/index.ts
3
+ * @description Driver de persistencia con SQLite.
4
+ * SQLite persistence driver.
5
+ */
6
+ import type { Engine } from '../../../../../lib/store/engine';
7
+ /**
8
+ * Sentencia preparada, con la forma que exponen `better-sqlite3` y `node:sqlite`.
9
+ * Prepared statement, shaped as `better-sqlite3` and `node:sqlite` expose it.
10
+ */
11
+ interface SQLiteStatement {
12
+ run(...params: unknown[]): unknown;
13
+ get(...params: unknown[]): unknown;
14
+ all(...params: unknown[]): unknown[];
15
+ }
16
+ /**
17
+ * Interface mínima de la base SQLite. La cumplen `better-sqlite3` (`new Database(file)`) y
18
+ * el `node:sqlite` nativo (`new DatabaseSync(file)`), así que el driver no agrega ninguna
19
+ * dependencia: la base se inyecta ya abierta, igual que el cliente de `RedisEngine`.
20
+ * Minimal SQLite database interface. Both `better-sqlite3` (`new Database(file)`) and the
21
+ * native `node:sqlite` (`new DatabaseSync(file)`) satisfy it, so this driver adds no
22
+ * dependency: the database is injected already open, just like `RedisEngine`'s client.
23
+ */
24
+ export interface SQLiteDatabase {
25
+ exec(sql: string): unknown;
26
+ prepare(sql: string): SQLiteStatement;
27
+ }
28
+ /**
29
+ * Driver de persistencia con SQLite: una tabla `(path, parent, score, value)` con índice
30
+ * `(parent, score DESC)`.
31
+ *
32
+ * Es el driver más eficiente de los integrados porque delega en el motor lo que los demás
33
+ * resuelven a mano: `list` es un `ORDER BY score DESC LIMIT/OFFSET` sobre el índice (sin
34
+ * índice en memoria ni archivo de orden), `count` un `COUNT(*)` y el `unset` en cascada una
35
+ * sola sentencia por rango de `path`. Medido sobre un chat real de 55.146 mensajes frente al
36
+ * filesystem: 220 MB → 64 MB en disco, primer `list` 115 ms → 0,6 ms y dos archivos en total.
37
+ *
38
+ * SQLite persistence driver: a single `(path, parent, score, value)` table with a
39
+ * `(parent, score DESC)` index. The most efficient built-in driver, since it delegates to the
40
+ * engine what the others hand-roll: `list` is an indexed `ORDER BY score DESC LIMIT/OFFSET`
41
+ * (no in-memory index, no order file), `count` a `COUNT(*)` and cascading `unset` a single
42
+ * range statement. Measured on a real 55,146-message chat against the filesystem: 220 MB →
43
+ * 64 MB on disk, first `list` 115 ms → 0.6 ms and two files in total.
44
+ *
45
+ * @example
46
+ * import Database from 'better-sqlite3';
47
+ * const engine = new SQLiteEngine(new Database('.sessions/584144709840.db'));
48
+ *
49
+ * @example
50
+ * import { DatabaseSync } from 'node:sqlite';
51
+ * const engine = new SQLiteEngine(new DatabaseSync('.sessions/584144709840.db'));
52
+ */
53
+ export declare class SQLiteEngine implements Engine {
54
+ private readonly _db;
55
+ private readonly _read;
56
+ private readonly _write;
57
+ private readonly _remove;
58
+ private readonly _page;
59
+ private readonly _total;
60
+ private readonly _wipe;
61
+ private readonly _read_blob;
62
+ private readonly _write_blob;
63
+ /**
64
+ * @param _db - Base SQLite ya abierta / Already open SQLite database
65
+ * @param table - Tabla donde viven los documentos / Table holding the documents
66
+ */
67
+ constructor(_db: SQLiteDatabase, table?: string);
68
+ /**
69
+ * Lee el valor de un documento.
70
+ * Reads a document's value.
71
+ */
72
+ get(path: string): Promise<string | null>;
73
+ /**
74
+ * Escribe el valor del documento; `score` fija el orden de `list` (por defecto, la hora
75
+ * de escritura).
76
+ * Writes the document value; `score` drives `list` ordering (write time by default).
77
+ */
78
+ set(path: string, value: string, score?: number): Promise<void>;
79
+ /**
80
+ * Elimina el documento y todos sus descendientes. Idempotente.
81
+ * Deletes the document and every descendant. Idempotent.
82
+ */
83
+ unset(path: string): Promise<boolean>;
84
+ /**
85
+ * Lista los valores de los hijos directos, ordenados por score DESC.
86
+ * Lists direct children values ordered by score DESC.
87
+ */
88
+ list(path: string, offset?: number, limit?: number): Promise<string[]>;
89
+ /**
90
+ * Cuenta los hijos directos.
91
+ * Counts direct children.
92
+ */
93
+ count(path: string): Promise<number>;
94
+ /**
95
+ * Lee el binario del documento, o null si la fila no lo tiene.
96
+ * Reads the document binary, or null when the row has none.
97
+ */
98
+ get_buffer(path: string): Promise<Buffer | null>;
99
+ /**
100
+ * Escribe el binario del documento como BLOB, sin JSON ni base64.
101
+ * Writes the document binary as a BLOB, with no JSON nor base64.
102
+ */
103
+ set_buffer(path: string, data: Buffer, score?: number): Promise<void>;
104
+ /**
105
+ * Vacía la tabla completa.
106
+ * Clears the entire table.
107
+ */
108
+ clear(): Promise<void>;
109
+ }
110
+ export {};