zapind 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,2520 @@
1
+ import { readFile, mkdir, writeFile, rename, chmod, unlink } from 'fs/promises';
2
+ import { dirname } from 'path';
3
+ import { randomBytes, scryptSync, createDecipheriv, createCipheriv } from 'crypto';
4
+ import { Zalo, MuteAction, UpdateLangAvailableLanguages, ThreadType as ThreadType$1, LoginQRCallbackEventType } from 'zca-js';
5
+
6
+ // src/core/cache.ts
7
+ var TTLCache = class {
8
+ store = /* @__PURE__ */ new Map();
9
+ maxEntries;
10
+ defaultTtlMs;
11
+ constructor(options = {}) {
12
+ this.maxEntries = Math.max(1, options.maxEntries ?? 500);
13
+ this.defaultTtlMs = Math.max(1, options.defaultTtlMs ?? 6e4);
14
+ }
15
+ get(key) {
16
+ const entry = this.store.get(key);
17
+ if (!entry) return void 0;
18
+ if (Date.now() >= entry.expiresAt) {
19
+ this.store.delete(key);
20
+ return void 0;
21
+ }
22
+ this.store.delete(key);
23
+ this.store.set(key, entry);
24
+ return entry.value;
25
+ }
26
+ set(key, value, ttlMs = this.defaultTtlMs) {
27
+ if (this.store.has(key)) {
28
+ this.store.delete(key);
29
+ } else if (this.store.size >= this.maxEntries) {
30
+ const oldestKey = this.store.keys().next().value;
31
+ if (oldestKey !== void 0) {
32
+ this.store.delete(oldestKey);
33
+ }
34
+ }
35
+ this.store.set(key, { value, expiresAt: Date.now() + ttlMs });
36
+ }
37
+ has(key) {
38
+ return this.get(key) !== void 0;
39
+ }
40
+ delete(key) {
41
+ return this.store.delete(key);
42
+ }
43
+ clear() {
44
+ this.store.clear();
45
+ }
46
+ get size() {
47
+ return this.store.size;
48
+ }
49
+ };
50
+ var InFlightDeduplicator = class {
51
+ pending = /* @__PURE__ */ new Map();
52
+ run(key, fn) {
53
+ const existing = this.pending.get(key);
54
+ if (existing) {
55
+ return existing;
56
+ }
57
+ const promise = fn().finally(() => {
58
+ this.pending.delete(key);
59
+ });
60
+ this.pending.set(key, promise);
61
+ return promise;
62
+ }
63
+ clear() {
64
+ this.pending.clear();
65
+ }
66
+ };
67
+
68
+ // src/core/event-bus.ts
69
+ var EventBus = class {
70
+ constructor(logger) {
71
+ this.logger = logger;
72
+ }
73
+ logger;
74
+ listeners = /* @__PURE__ */ new Map();
75
+ on(event, handler) {
76
+ let set = this.listeners.get(event);
77
+ if (!set) {
78
+ set = /* @__PURE__ */ new Set();
79
+ this.listeners.set(event, set);
80
+ }
81
+ set.add(handler);
82
+ return () => this.off(event, handler);
83
+ }
84
+ once(event, handler) {
85
+ const wrapped = async (payload) => {
86
+ this.off(event, wrapped);
87
+ await handler(payload);
88
+ };
89
+ return this.on(event, wrapped);
90
+ }
91
+ off(event, handler) {
92
+ const set = this.listeners.get(event);
93
+ if (!set) return;
94
+ set.delete(handler);
95
+ if (set.size === 0) this.listeners.delete(event);
96
+ }
97
+ emit(event, payload) {
98
+ const set = this.listeners.get(event);
99
+ if (!set || set.size === 0) return;
100
+ for (const handler of [...set]) {
101
+ Promise.resolve().then(() => handler(payload)).catch((err) => {
102
+ this.logger.error("Event handler threw an error", {
103
+ event,
104
+ error: err instanceof Error ? err.message : String(err)
105
+ });
106
+ });
107
+ }
108
+ }
109
+ listenerCount(event) {
110
+ if (event) return this.listeners.get(event)?.size ?? 0;
111
+ let total = 0;
112
+ for (const set of this.listeners.values()) total += set.size;
113
+ return total;
114
+ }
115
+ removeAllListeners(event) {
116
+ if (event) this.listeners.delete(event);
117
+ else this.listeners.clear();
118
+ }
119
+ };
120
+
121
+ // src/errors/index.ts
122
+ var ZapindError = class extends Error {
123
+ code;
124
+ retryable;
125
+ rawCode;
126
+ cause;
127
+ constructor(message, options = {}) {
128
+ super(message);
129
+ this.name = new.target.name;
130
+ this.code = options.code ?? "ZAPIND_ERROR";
131
+ this.retryable = options.retryable ?? false;
132
+ this.rawCode = options.rawCode ?? null;
133
+ if (options.cause !== void 0) {
134
+ this.cause = options.cause;
135
+ }
136
+ Object.setPrototypeOf(this, new.target.prototype);
137
+ }
138
+ };
139
+ var AuthenticationError = class extends ZapindError {
140
+ constructor(message = "Not authenticated with Zalo", cause, rawCode = null) {
141
+ super(message, { code: "AUTHENTICATION_ERROR", retryable: false, cause, rawCode });
142
+ }
143
+ };
144
+ var SessionError = class extends ZapindError {
145
+ constructor(message = "Session is invalid, expired, or could not be accessed", cause, rawCode = null) {
146
+ super(message, { code: "SESSION_ERROR", retryable: false, cause, rawCode });
147
+ }
148
+ };
149
+ var NetworkError = class extends ZapindError {
150
+ constructor(message = "Network error communicating with Zalo", cause) {
151
+ super(message, { code: "NETWORK_ERROR", retryable: true, cause });
152
+ }
153
+ };
154
+ var RateLimitError = class extends ZapindError {
155
+ retryAfterMs;
156
+ constructor(message = "Rate limit exceeded", retryAfterMs = null, cause) {
157
+ super(message, { code: "RATE_LIMIT_ERROR", retryable: true, cause });
158
+ this.retryAfterMs = retryAfterMs;
159
+ }
160
+ };
161
+ var ValidationError = class extends ZapindError {
162
+ constructor(message, cause) {
163
+ super(message, { code: "VALIDATION_ERROR", retryable: false, cause });
164
+ }
165
+ };
166
+ var PermissionError = class extends ZapindError {
167
+ constructor(message = "Insufficient permissions for this operation", cause, rawCode = null) {
168
+ super(message, { code: "PERMISSION_ERROR", retryable: false, cause, rawCode });
169
+ }
170
+ };
171
+ var NotFoundError = class extends ZapindError {
172
+ constructor(message = "Requested resource was not found", cause, rawCode = null) {
173
+ super(message, { code: "NOT_FOUND_ERROR", retryable: false, cause, rawCode });
174
+ }
175
+ };
176
+ var APIError = class extends ZapindError {
177
+ constructor(message, rawCode = null, cause, retryable = false) {
178
+ super(message, { code: "API_ERROR", retryable, rawCode, cause });
179
+ }
180
+ };
181
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
182
+ "ECONNRESET",
183
+ "ECONNREFUSED",
184
+ "ETIMEDOUT",
185
+ "ENOTFOUND",
186
+ "EAI_AGAIN",
187
+ "EPIPE",
188
+ "UND_ERR_CONNECT_TIMEOUT",
189
+ "UND_ERR_HEADERS_TIMEOUT",
190
+ "UND_ERR_SOCKET"
191
+ ]);
192
+ function normalizeError(err, fallbackMessage = "Unexpected Zalo API error") {
193
+ if (err instanceof ZapindError) return err;
194
+ const e = typeof err === "object" && err !== null ? err : {};
195
+ const name = typeof e.name === "string" ? e.name : "";
196
+ const message = typeof e.message === "string" && e.message.trim().length > 0 ? e.message : typeof err === "string" && err.trim().length > 0 ? err : fallbackMessage;
197
+ const rawNumericCode = typeof e.code === "number" ? e.code : null;
198
+ const rawStringCode = typeof e.code === "string" ? e.code : "";
199
+ const lower = message.toLowerCase();
200
+ if (name === "ZaloApiLoginQRDeclined" || name === "ZaloApiLoginQRAborted") {
201
+ return new AuthenticationError(message, err, rawNumericCode);
202
+ }
203
+ if (name === "ZaloApiMissingImageMetadataGetter") {
204
+ return new ValidationError(
205
+ "Uploading local image files requires an imageMetadataGetter in Zapind options (or pass Buffer with width/height).",
206
+ err
207
+ );
208
+ }
209
+ if (e.status === 429 || lower.includes("rate limit") || lower.includes("too many requests")) {
210
+ return new RateLimitError(message, typeof e.retryAfterMs === "number" ? e.retryAfterMs : null, err);
211
+ }
212
+ if (e.status === 401 || lower.includes("session expired") || lower.includes("invalid cookie") || lower.includes("not logged in") || lower.includes("unauthorized")) {
213
+ return new SessionError(message, err, rawNumericCode);
214
+ }
215
+ if (e.status === 403 || lower.includes("permission") || lower.includes("forbidden")) {
216
+ return new PermissionError(message, err, rawNumericCode);
217
+ }
218
+ if (e.status === 404 || lower.includes("not found")) {
219
+ return new NotFoundError(message, err, rawNumericCode);
220
+ }
221
+ if (NETWORK_CODES.has(rawStringCode) || lower.includes("fetch failed") || lower.includes("network") || lower.includes("socket hang up") || lower.includes("timed out")) {
222
+ return new NetworkError(message, err);
223
+ }
224
+ const retryable = typeof e.status === "number" && e.status >= 500;
225
+ return new APIError(message, rawNumericCode, err, retryable);
226
+ }
227
+
228
+ // src/core/policies.ts
229
+ var SENSITIVE_KEY_PATTERN = /token|secret|password|cookie|refresh|credential|auth|imei|cipher|zpw_sek|qr|imagebase64|imagedataurl|content|message|msg|text/i;
230
+ function redactSensitive(value, depth = 0) {
231
+ if (depth > 8) return "[TRUNCATED]";
232
+ if (value === null || value === void 0 || typeof value !== "object") return value;
233
+ if (Buffer.isBuffer(value)) return `[Buffer(${value.length})]`;
234
+ if (Array.isArray(value)) return value.map((item) => redactSensitive(item, depth + 1));
235
+ const out = {};
236
+ for (const [k, v] of Object.entries(value)) {
237
+ if (SENSITIVE_KEY_PATTERN.test(k)) {
238
+ out[k] = "[REDACTED]";
239
+ } else if (v !== null && typeof v === "object") {
240
+ out[k] = redactSensitive(v, depth + 1);
241
+ } else {
242
+ out[k] = v;
243
+ }
244
+ }
245
+ return out;
246
+ }
247
+ function formatLine(level, message, meta) {
248
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
249
+ if (!meta) return `[${ts}] [${level}] ${message}`;
250
+ try {
251
+ return `[${ts}] [${level}] ${message} ${JSON.stringify(meta)}`;
252
+ } catch {
253
+ return `[${ts}] [${level}] ${message} [Unserializable meta]`;
254
+ }
255
+ }
256
+ var RedactingLogger = class {
257
+ sink;
258
+ debugEnabled;
259
+ constructor(options = {}) {
260
+ this.debugEnabled = options.debug ?? false;
261
+ this.sink = options.sink ?? {
262
+ debug: (msg, meta) => console.debug(formatLine("DEBUG", msg, meta)),
263
+ info: (msg, meta) => console.info(formatLine("INFO", msg, meta)),
264
+ warn: (msg, meta) => console.warn(formatLine("WARN", msg, meta)),
265
+ error: (msg, meta) => console.error(formatLine("ERROR", msg, meta))
266
+ };
267
+ }
268
+ sanitize(meta) {
269
+ return meta ? redactSensitive(meta) : void 0;
270
+ }
271
+ debug(message, meta) {
272
+ if (!this.debugEnabled) return;
273
+ this.sink.debug(message, this.sanitize(meta));
274
+ }
275
+ info(message, meta) {
276
+ this.sink.info(message, this.sanitize(meta));
277
+ }
278
+ warn(message, meta) {
279
+ this.sink.warn(message, this.sanitize(meta));
280
+ }
281
+ error(message, meta) {
282
+ this.sink.error(message, this.sanitize(meta));
283
+ }
284
+ };
285
+ var noopLogger = {
286
+ debug() {
287
+ },
288
+ info() {
289
+ },
290
+ warn() {
291
+ },
292
+ error() {
293
+ }
294
+ };
295
+ async function withTimeout(operation, timeoutMs, label) {
296
+ if (timeoutMs <= 0 || !Number.isFinite(timeoutMs)) return operation();
297
+ let timer;
298
+ const timeoutPromise = new Promise((_, reject) => {
299
+ timer = setTimeout(() => {
300
+ reject(new NetworkError(`${label ?? "Request"} timed out after ${timeoutMs}ms`));
301
+ }, timeoutMs);
302
+ timer.unref?.();
303
+ });
304
+ try {
305
+ return await Promise.race([operation(), timeoutPromise]);
306
+ } finally {
307
+ if (timer !== void 0) clearTimeout(timer);
308
+ }
309
+ }
310
+ async function withRetry(operation, options, allowRetry = true) {
311
+ const attempts = allowRetry ? Math.max(1, options.maxAttempts) : 1;
312
+ let lastError;
313
+ for (let attempt = 1; attempt <= attempts; attempt++) {
314
+ try {
315
+ return await operation();
316
+ } catch (err) {
317
+ lastError = err;
318
+ const isRetryable = err instanceof ZapindError && err.retryable;
319
+ if (!allowRetry || !isRetryable || attempt >= attempts) throw err;
320
+ const delayMs = err instanceof RateLimitError && err.retryAfterMs !== null && err.retryAfterMs > 0 ? Math.min(err.retryAfterMs, options.maxDelayMs) : Math.min(
321
+ options.baseDelayMs * Math.pow(2, attempt - 1) + Math.floor(Math.random() * Math.max(1, options.baseDelayMs / 2)),
322
+ options.maxDelayMs
323
+ );
324
+ await new Promise((resolve) => {
325
+ const t = setTimeout(resolve, delayMs);
326
+ t.unref?.();
327
+ });
328
+ }
329
+ }
330
+ throw lastError;
331
+ }
332
+ var RateLimiter = class {
333
+ ratePerMs;
334
+ capacity;
335
+ tokens;
336
+ lastRefillAt;
337
+ queue = Promise.resolve();
338
+ constructor(options) {
339
+ const rps = Math.max(0.1, options.maxRequestsPerSecond);
340
+ this.ratePerMs = rps / 1e3;
341
+ this.capacity = Math.max(1, options.burst ?? Math.ceil(rps));
342
+ this.tokens = this.capacity;
343
+ this.lastRefillAt = Date.now();
344
+ }
345
+ refill() {
346
+ const now = Date.now();
347
+ const elapsed = Math.max(0, now - this.lastRefillAt);
348
+ if (elapsed > 0) {
349
+ this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.ratePerMs);
350
+ this.lastRefillAt = now;
351
+ }
352
+ }
353
+ acquire() {
354
+ const next = this.queue.then(async () => {
355
+ this.refill();
356
+ if (this.tokens >= 1) {
357
+ this.tokens -= 1;
358
+ return;
359
+ }
360
+ const waitMs = Math.ceil((1 - this.tokens) / this.ratePerMs);
361
+ await new Promise((resolve) => {
362
+ const t = setTimeout(resolve, waitMs);
363
+ t.unref?.();
364
+ });
365
+ this.refill();
366
+ this.tokens = Math.max(0, this.tokens - 1);
367
+ });
368
+ this.queue = next.catch(() => {
369
+ });
370
+ return next;
371
+ }
372
+ };
373
+ var PolicyExecutor = class {
374
+ constructor(defaultTimeoutMs, retryOptions, rateLimiter, logger) {
375
+ this.defaultTimeoutMs = defaultTimeoutMs;
376
+ this.retryOptions = retryOptions;
377
+ this.rateLimiter = rateLimiter;
378
+ this.logger = logger;
379
+ }
380
+ defaultTimeoutMs;
381
+ retryOptions;
382
+ rateLimiter;
383
+ logger;
384
+ async execute(fn, options) {
385
+ const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;
386
+ const allowRetry = options.idempotent ?? true;
387
+ return withRetry(
388
+ async () => {
389
+ if (this.rateLimiter) await this.rateLimiter.acquire();
390
+ try {
391
+ return await withTimeout(fn, timeoutMs, options.operation);
392
+ } catch (err) {
393
+ const normalized = normalizeError(err, `Failed during ${options.operation}`);
394
+ this.logger.debug("Operation error", {
395
+ operation: options.operation,
396
+ code: normalized.code,
397
+ retryable: normalized.retryable
398
+ });
399
+ throw normalized;
400
+ }
401
+ },
402
+ this.retryOptions,
403
+ allowRetry
404
+ );
405
+ }
406
+ };
407
+
408
+ // src/models/enums.ts
409
+ var ThreadType = /* @__PURE__ */ ((ThreadType3) => {
410
+ ThreadType3[ThreadType3["User"] = 0] = "User";
411
+ ThreadType3[ThreadType3["Group"] = 1] = "Group";
412
+ return ThreadType3;
413
+ })(ThreadType || {});
414
+ var ClientStatus = /* @__PURE__ */ ((ClientStatus2) => {
415
+ ClientStatus2["Idle"] = "idle";
416
+ ClientStatus2["Starting"] = "starting";
417
+ ClientStatus2["QRPending"] = "qr_pending";
418
+ ClientStatus2["Scanned"] = "scanned";
419
+ ClientStatus2["Connected"] = "connected";
420
+ ClientStatus2["Error"] = "error";
421
+ return ClientStatus2;
422
+ })(ClientStatus || {});
423
+ var Gender = /* @__PURE__ */ ((Gender2) => {
424
+ Gender2["Male"] = "male";
425
+ Gender2["Female"] = "female";
426
+ Gender2["Unknown"] = "unknown";
427
+ return Gender2;
428
+ })(Gender || {});
429
+ var GroupType = /* @__PURE__ */ ((GroupType2) => {
430
+ GroupType2["Group"] = "group";
431
+ GroupType2["Community"] = "community";
432
+ return GroupType2;
433
+ })(GroupType || {});
434
+ var CloseReason = /* @__PURE__ */ ((CloseReason2) => {
435
+ CloseReason2[CloseReason2["ManualClosure"] = 1e3] = "ManualClosure";
436
+ CloseReason2[CloseReason2["AbnormalClosure"] = 1006] = "AbnormalClosure";
437
+ CloseReason2[CloseReason2["DuplicateConnection"] = 3e3] = "DuplicateConnection";
438
+ CloseReason2[CloseReason2["KickConnection"] = 3003] = "KickConnection";
439
+ return CloseReason2;
440
+ })(CloseReason || {});
441
+ var TextStyle = /* @__PURE__ */ ((TextStyle2) => {
442
+ TextStyle2["Bold"] = "b";
443
+ TextStyle2["Italic"] = "i";
444
+ TextStyle2["Underline"] = "u";
445
+ TextStyle2["StrikeThrough"] = "s";
446
+ TextStyle2["Red"] = "c_db342e";
447
+ TextStyle2["Orange"] = "c_f27806";
448
+ TextStyle2["Yellow"] = "c_f7b503";
449
+ TextStyle2["Green"] = "c_15a85f";
450
+ TextStyle2["Small"] = "f_13";
451
+ TextStyle2["Big"] = "f_18";
452
+ TextStyle2["UnorderedList"] = "lst_1";
453
+ TextStyle2["OrderedList"] = "lst_2";
454
+ TextStyle2["Indent"] = "ind_$";
455
+ return TextStyle2;
456
+ })(TextStyle || {});
457
+ var Urgency = /* @__PURE__ */ ((Urgency2) => {
458
+ Urgency2[Urgency2["Default"] = 0] = "Default";
459
+ Urgency2[Urgency2["Important"] = 1] = "Important";
460
+ Urgency2[Urgency2["Urgent"] = 2] = "Urgent";
461
+ return Urgency2;
462
+ })(Urgency || {});
463
+ var Reaction = /* @__PURE__ */ ((Reaction2) => {
464
+ Reaction2["Heart"] = "/-heart";
465
+ Reaction2["Like"] = "/-strong";
466
+ Reaction2["Haha"] = ":>";
467
+ Reaction2["Wow"] = ":o";
468
+ Reaction2["Cry"] = ":-((";
469
+ Reaction2["Angry"] = ":-h";
470
+ Reaction2["None"] = "";
471
+ return Reaction2;
472
+ })(Reaction || {});
473
+
474
+ // src/core/thread-registry.ts
475
+ var ThreadTypeRegistry = class {
476
+ groupIds = /* @__PURE__ */ new Set();
477
+ userIds = /* @__PURE__ */ new Set();
478
+ groupsLoadedAt = 0;
479
+ groupsTtlMs;
480
+ loadingGroups = null;
481
+ constructor(groupsTtlMs = 5 * 6e4) {
482
+ this.groupsTtlMs = groupsTtlMs;
483
+ }
484
+ registerGroup(groupId) {
485
+ if (!groupId) return;
486
+ this.groupIds.add(groupId);
487
+ this.userIds.delete(groupId);
488
+ }
489
+ registerGroups(ids) {
490
+ for (const id of ids) {
491
+ if (id) {
492
+ this.groupIds.add(id);
493
+ this.userIds.delete(id);
494
+ }
495
+ }
496
+ this.groupsLoadedAt = Date.now();
497
+ }
498
+ registerUser(userId) {
499
+ if (!userId) return;
500
+ if (!this.groupIds.has(userId)) {
501
+ this.userIds.add(userId);
502
+ }
503
+ }
504
+ extractId(target) {
505
+ return typeof target === "string" ? target.trim() : target.id.trim();
506
+ }
507
+ async resolve(target, explicitType, fetchAllGroupIds) {
508
+ const threadId = this.extractId(target);
509
+ if (explicitType !== void 0) {
510
+ if (explicitType === 1 /* Group */) this.registerGroup(threadId);
511
+ else this.registerUser(threadId);
512
+ return { threadId, threadType: explicitType };
513
+ }
514
+ if (typeof target !== "string" && target.threadType !== void 0) {
515
+ return { threadId, threadType: target.threadType };
516
+ }
517
+ if (this.groupIds.has(threadId)) {
518
+ return { threadId, threadType: 1 /* Group */ };
519
+ }
520
+ if (this.userIds.has(threadId)) {
521
+ return { threadId, threadType: 0 /* User */ };
522
+ }
523
+ const isStale = Date.now() - this.groupsLoadedAt > this.groupsTtlMs;
524
+ if (fetchAllGroupIds && isStale) {
525
+ if (!this.loadingGroups) {
526
+ this.loadingGroups = fetchAllGroupIds().then((ids) => {
527
+ this.registerGroups(ids);
528
+ }).catch(() => {
529
+ }).finally(() => {
530
+ this.loadingGroups = null;
531
+ });
532
+ }
533
+ await this.loadingGroups;
534
+ if (this.groupIds.has(threadId)) {
535
+ return { threadId, threadType: 1 /* Group */ };
536
+ }
537
+ }
538
+ return { threadId, threadType: 0 /* User */ };
539
+ }
540
+ clear() {
541
+ this.groupIds.clear();
542
+ this.userIds.clear();
543
+ this.groupsLoadedAt = 0;
544
+ this.loadingGroups = null;
545
+ }
546
+ };
547
+
548
+ // src/models/entities.ts
549
+ var User = class {
550
+ constructor(data, actions) {
551
+ this.actions = actions;
552
+ this.id = data.id;
553
+ this.username = data.username;
554
+ this.displayName = data.displayName;
555
+ this.zaloName = data.zaloName;
556
+ this.avatarUrl = data.avatarUrl;
557
+ this.coverUrl = data.coverUrl;
558
+ this.gender = data.gender;
559
+ this.birthday = data.birthday;
560
+ this.statusMessage = data.statusMessage;
561
+ this.phoneNumber = data.phoneNumber;
562
+ this.isFriend = data.isFriend;
563
+ this.isBlocked = data.isBlocked;
564
+ this.lastActiveAt = data.lastActiveAt;
565
+ }
566
+ actions;
567
+ threadType = 0 /* User */;
568
+ id;
569
+ username;
570
+ displayName;
571
+ zaloName;
572
+ avatarUrl;
573
+ coverUrl;
574
+ gender;
575
+ birthday;
576
+ statusMessage;
577
+ phoneNumber;
578
+ isFriend;
579
+ isBlocked;
580
+ lastActiveAt;
581
+ /** Send a direct message to this user without passing threadType. */
582
+ send(content) {
583
+ return this.actions.sendMessage(this.id, content, 0 /* User */);
584
+ }
585
+ sendFriendRequest(message = "Hello!") {
586
+ return this.actions.sendFriendRequest(this.id, message);
587
+ }
588
+ block() {
589
+ return this.actions.blockUser(this.id);
590
+ }
591
+ unblock() {
592
+ return this.actions.unblockUser(this.id);
593
+ }
594
+ };
595
+ var Profile = class extends User {
596
+ globalId;
597
+ isBusiness;
598
+ createdAt;
599
+ constructor(data, actions) {
600
+ super(data, actions);
601
+ this.globalId = data.globalId;
602
+ this.isBusiness = data.isBusiness;
603
+ this.createdAt = data.createdAt;
604
+ }
605
+ };
606
+ var Contact = class extends User {
607
+ alias;
608
+ constructor(data, actions) {
609
+ super(data, actions);
610
+ this.alias = data.alias;
611
+ }
612
+ setAlias(alias) {
613
+ return this.actions.setFriendAlias(this.id, alias);
614
+ }
615
+ remove() {
616
+ return this.actions.removeFriend(this.id);
617
+ }
618
+ };
619
+ var Group = class {
620
+ constructor(data, actions) {
621
+ this.actions = actions;
622
+ this.id = data.id;
623
+ this.name = data.name;
624
+ this.description = data.description;
625
+ this.type = data.type;
626
+ this.creatorId = data.creatorId;
627
+ this.avatarUrl = data.avatarUrl;
628
+ this.fullAvatarUrl = data.fullAvatarUrl;
629
+ this.memberCount = data.memberCount;
630
+ this.maxMembers = data.maxMembers;
631
+ this.memberIds = data.memberIds;
632
+ this.adminIds = data.adminIds;
633
+ this.isE2EE = data.isE2EE;
634
+ this.createdAt = data.createdAt;
635
+ this.settings = data.settings;
636
+ }
637
+ actions;
638
+ threadType = 1 /* Group */;
639
+ id;
640
+ name;
641
+ description;
642
+ type;
643
+ creatorId;
644
+ avatarUrl;
645
+ fullAvatarUrl;
646
+ memberCount;
647
+ maxMembers;
648
+ memberIds;
649
+ adminIds;
650
+ isE2EE;
651
+ createdAt;
652
+ settings;
653
+ /** Send a message to this group without passing threadType. */
654
+ send(content) {
655
+ return this.actions.sendMessage(this.id, content, 1 /* Group */);
656
+ }
657
+ getMessages(count) {
658
+ return this.actions.getGroupMessages(this.id, count);
659
+ }
660
+ addMembers(userIds) {
661
+ return this.actions.addGroupMembers(this.id, userIds);
662
+ }
663
+ removeMembers(userIds) {
664
+ return this.actions.removeGroupMembers(this.id, userIds);
665
+ }
666
+ rename(name) {
667
+ return this.actions.renameGroup(this.id, name);
668
+ }
669
+ leave() {
670
+ return this.actions.leaveGroup(this.id);
671
+ }
672
+ };
673
+ var Conversation = class {
674
+ constructor(id, threadType, actions) {
675
+ this.actions = actions;
676
+ this.id = id;
677
+ this.threadType = threadType;
678
+ }
679
+ actions;
680
+ id;
681
+ threadType;
682
+ get isGroup() {
683
+ return this.threadType === 1 /* Group */;
684
+ }
685
+ send(content) {
686
+ return this.actions.sendMessage(this.id, content, this.threadType);
687
+ }
688
+ getMessages(count) {
689
+ return this.actions.getGroupMessages(this.id, count);
690
+ }
691
+ sendTyping() {
692
+ return this.actions.sendTyping(this.id, this.threadType);
693
+ }
694
+ pin(pinned = true) {
695
+ return this.actions.pinConversation(this.id, pinned, this.threadType);
696
+ }
697
+ mute(durationSeconds) {
698
+ return this.actions.muteConversation(this.id, durationSeconds, this.threadType);
699
+ }
700
+ };
701
+ var Message = class {
702
+ constructor(data, actions) {
703
+ this.actions = actions;
704
+ this.id = data.id;
705
+ this.clientMsgId = data.clientMsgId;
706
+ this.threadId = data.threadId;
707
+ this.threadType = data.threadType;
708
+ this.sender = data.sender;
709
+ this.recipientId = data.recipientId;
710
+ this.isSelf = data.isSelf;
711
+ this.msgType = data.msgType;
712
+ this.text = data.text;
713
+ this.attachments = data.attachments;
714
+ this.mentions = data.mentions;
715
+ this.replyTo = data.replyTo;
716
+ this.timestamp = data.timestamp;
717
+ this.ttlMs = data.ttlMs;
718
+ this.st = data.st;
719
+ this.at = data.at;
720
+ this.cmd = data.cmd;
721
+ this.conversation = new Conversation(data.threadId, data.threadType, actions);
722
+ }
723
+ actions;
724
+ id;
725
+ clientMsgId;
726
+ threadId;
727
+ threadType;
728
+ sender;
729
+ recipientId;
730
+ isSelf;
731
+ msgType;
732
+ text;
733
+ attachments;
734
+ mentions;
735
+ replyTo;
736
+ timestamp;
737
+ ttlMs;
738
+ st;
739
+ at;
740
+ cmd;
741
+ conversation;
742
+ get isGroup() {
743
+ return this.threadType === 1 /* Group */;
744
+ }
745
+ /** Reply directly to this message (automatically sets quote and threadType). */
746
+ reply(content) {
747
+ return this.actions.replyMessage(this, content);
748
+ }
749
+ /** React to this message without passing threadId or threadType. */
750
+ react(reaction) {
751
+ return this.actions.reactMessage(this, reaction);
752
+ }
753
+ undo() {
754
+ return this.actions.undoMessage(this);
755
+ }
756
+ delete(onlyMe = true) {
757
+ return this.actions.deleteMessage(this, onlyMe);
758
+ }
759
+ markSeen() {
760
+ return this.actions.markSeen([this]);
761
+ }
762
+ };
763
+
764
+ // src/mappers/index.ts
765
+ function toDate(ts) {
766
+ const n = typeof ts === "number" ? ts : Number(ts);
767
+ if (!Number.isFinite(n) || n <= 0) return /* @__PURE__ */ new Date(0);
768
+ return new Date(n < 1e12 ? n * 1e3 : n);
769
+ }
770
+ function toOptionalDate(ts) {
771
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) return void 0;
772
+ return new Date(ts < 1e12 ? ts * 1e3 : ts);
773
+ }
774
+ function mapUserData(raw) {
775
+ const id = String(raw.userId ?? raw.uid ?? "");
776
+ const displayName = String(raw.displayName ?? raw.display_name ?? raw.zaloName ?? raw.zalo_name ?? "");
777
+ return {
778
+ id,
779
+ username: raw.username || void 0,
780
+ displayName,
781
+ zaloName: String(raw.zaloName ?? raw.zalo_name ?? displayName),
782
+ avatarUrl: String(raw.avatar ?? ""),
783
+ coverUrl: raw.cover || void 0,
784
+ gender: raw.gender === 0 ? "male" /* Male */ : raw.gender === 1 ? "female" /* Female */ : "unknown" /* Unknown */,
785
+ birthday: raw.sdob || void 0,
786
+ statusMessage: raw.status || void 0,
787
+ phoneNumber: raw.phoneNumber || void 0,
788
+ isFriend: raw.isFr === 1,
789
+ isBlocked: raw.isBlocked === 1 || raw.isBlocked === true,
790
+ lastActiveAt: toOptionalDate(raw.lastActionTime)
791
+ };
792
+ }
793
+ function mapProfileData(raw) {
794
+ return {
795
+ ...mapUserData(raw),
796
+ globalId: raw.globalId || void 0,
797
+ isBusiness: Boolean(raw.bizPkg && typeof raw.bizPkg.pkgId === "number" && raw.bizPkg.pkgId > 0),
798
+ createdAt: toOptionalDate(raw.createdTs)
799
+ };
800
+ }
801
+ function mapContactData(raw, alias) {
802
+ return {
803
+ ...mapUserData(raw),
804
+ isFriend: true,
805
+ alias: alias || void 0
806
+ };
807
+ }
808
+ function mapGroupData(raw, fallbackId) {
809
+ const memberIds = Array.isArray(raw.memberIds) ? raw.memberIds.map(String) : [];
810
+ const adminIds = Array.isArray(raw.adminIds) ? raw.adminIds.map(String) : [];
811
+ const settings = raw.setting ? {
812
+ blockName: raw.setting.blockName === 1,
813
+ signAdminMsg: raw.setting.signAdminMsg === 1,
814
+ addMemberOnly: raw.setting.addMemberOnly === 1,
815
+ setTopicOnly: raw.setting.setTopicOnly === 1,
816
+ enableMsgHistory: raw.setting.enableMsgHistory === 1,
817
+ joinApprovalRequired: raw.setting.joinAppr === 1,
818
+ lockCreatePost: raw.setting.lockCreatePost === 1,
819
+ lockCreatePoll: raw.setting.lockCreatePoll === 1,
820
+ lockSendMsg: raw.setting.lockSendMsg === 1,
821
+ lockViewMember: raw.setting.lockViewMember === 1
822
+ } : void 0;
823
+ return {
824
+ id: String(raw.groupId ?? fallbackId ?? ""),
825
+ name: String(raw.name ?? ""),
826
+ description: String(raw.desc ?? ""),
827
+ type: raw.type === 2 ? "community" /* Community */ : "group" /* Group */,
828
+ creatorId: String(raw.creatorId ?? ""),
829
+ avatarUrl: String(raw.avt ?? ""),
830
+ fullAvatarUrl: raw.fullAvt || void 0,
831
+ memberCount: typeof raw.totalMember === "number" ? raw.totalMember : memberIds.length,
832
+ maxMembers: typeof raw.maxMember === "number" ? raw.maxMember : 0,
833
+ memberIds,
834
+ adminIds,
835
+ isE2EE: raw.e2ee === 1,
836
+ createdAt: toOptionalDate(raw.createdTime),
837
+ settings
838
+ };
839
+ }
840
+ function mapGroupSummaries(gridVerMap) {
841
+ if (!gridVerMap || typeof gridVerMap !== "object") return [];
842
+ return Object.entries(gridVerMap).map(([id, version]) => ({
843
+ id: String(id),
844
+ version: String(version ?? "")
845
+ }));
846
+ }
847
+ function mapGroupMember(raw) {
848
+ return {
849
+ id: String(raw.id ?? ""),
850
+ displayName: String(raw.displayName ?? raw.zaloName ?? ""),
851
+ zaloName: String(raw.zaloName ?? raw.displayName ?? ""),
852
+ avatarUrl: String(raw.avatar ?? ""),
853
+ globalId: raw.globalId || void 0,
854
+ accountStatus: typeof raw.accountStatus === "number" ? raw.accountStatus : 0
855
+ };
856
+ }
857
+ function inferKind(msgType, rawType) {
858
+ const s = `${msgType} ${rawType ?? ""}`.toLowerCase();
859
+ if (s.includes("photo") || s.includes("image")) return "image";
860
+ if (s.includes("video")) return "video";
861
+ if (s.includes("voice") || s.includes("audio")) return "audio";
862
+ if (s.includes("sticker")) return "sticker";
863
+ if (s.includes("link") || s.includes("url")) return "link";
864
+ if (s.includes("file") || s.includes("share.file")) return "file";
865
+ return "other";
866
+ }
867
+ function mapMessageData(raw) {
868
+ const data = raw.data ?? {};
869
+ const msgType = String(data.msgType ?? "webchat");
870
+ let text = "";
871
+ const attachments = [];
872
+ if (typeof data.content === "string") {
873
+ text = data.content;
874
+ } else if (data.content && typeof data.content === "object") {
875
+ const obj = data.content;
876
+ text = typeof obj.title === "string" ? obj.title : "";
877
+ attachments.push({
878
+ kind: inferKind(msgType, typeof obj.type === "string" ? obj.type : void 0),
879
+ url: typeof obj.href === "string" ? obj.href : void 0,
880
+ thumbnailUrl: typeof obj.thumb === "string" ? obj.thumb : void 0,
881
+ title: text || void 0,
882
+ description: typeof obj.description === "string" ? obj.description : void 0
883
+ });
884
+ }
885
+ const mentions = Array.isArray(data.mentions) ? data.mentions.map((m) => ({
886
+ userId: String(m.uid ?? ""),
887
+ pos: typeof m.pos === "number" ? m.pos : 0,
888
+ len: typeof m.len === "number" ? m.len : 0
889
+ })) : [];
890
+ let replyTo;
891
+ if (data.quote && typeof data.quote === "object") {
892
+ replyTo = {
893
+ ownerId: String(data.quote.ownerId ?? ""),
894
+ clientMsgId: String(data.quote.cliMsgId ?? ""),
895
+ globalMsgId: String(data.quote.globalMsgId ?? ""),
896
+ text: String(data.quote.msg ?? ""),
897
+ timestamp: toDate(data.quote.ts)
898
+ };
899
+ }
900
+ return {
901
+ id: String(data.msgId ?? ""),
902
+ clientMsgId: String(data.cliMsgId ?? ""),
903
+ threadId: String(raw.threadId ?? data.idTo ?? ""),
904
+ threadType: raw.type === 1 /* Group */ ? 1 /* Group */ : 0 /* User */,
905
+ sender: {
906
+ id: String(data.uidFrom ?? ""),
907
+ name: data.dName || void 0
908
+ },
909
+ recipientId: String(data.idTo ?? ""),
910
+ isSelf: Boolean(raw.isSelf),
911
+ msgType,
912
+ text,
913
+ attachments,
914
+ mentions,
915
+ replyTo,
916
+ timestamp: toDate(data.ts),
917
+ ttlMs: typeof data.ttl === "number" ? data.ttl : 0,
918
+ st: typeof data.st === "number" ? data.st : 0,
919
+ at: typeof data.at === "number" ? data.at : 0,
920
+ cmd: typeof data.cmd === "number" ? data.cmd : 0
921
+ };
922
+ }
923
+ function mapUploadedMedia(raw) {
924
+ if (raw.fileType === "image") {
925
+ return {
926
+ id: String(raw.photoId ?? ""),
927
+ kind: "image",
928
+ url: String(raw.normalUrl ?? raw.hdUrl ?? ""),
929
+ hdUrl: raw.hdUrl || void 0,
930
+ thumbnailUrl: raw.thumbUrl || void 0,
931
+ totalSize: typeof raw.totalSize === "number" ? raw.totalSize : 0,
932
+ width: typeof raw.width === "number" ? raw.width : void 0,
933
+ height: typeof raw.height === "number" ? raw.height : void 0
934
+ };
935
+ }
936
+ return {
937
+ id: String(raw.fileId ?? ""),
938
+ kind: raw.fileType === "video" ? "video" : "file",
939
+ url: String(raw.fileUrl ?? ""),
940
+ fileName: raw.fileName || void 0,
941
+ totalSize: typeof raw.totalSize === "number" ? raw.totalSize : 0,
942
+ checksum: raw.checksum || void 0
943
+ };
944
+ }
945
+ function mapOnlineFriends(entries) {
946
+ if (!Array.isArray(entries)) return [];
947
+ return entries.map((e) => ({
948
+ userId: String(e.userId ?? ""),
949
+ status: String(e.status ?? "")
950
+ }));
951
+ }
952
+ function mapLastOnline(userId, raw) {
953
+ const ts = typeof raw.lastOnline === "number" && raw.lastOnline > 0 ? raw.lastOnline : null;
954
+ return {
955
+ userId,
956
+ lastOnlineAt: ts !== null ? toDate(ts) : null,
957
+ showOnlineStatus: Boolean(raw.settings?.show_online_status)
958
+ };
959
+ }
960
+ function mapAccountSettings(raw) {
961
+ return {
962
+ showOnlineStatus: Boolean(raw.show_online_status),
963
+ displaySeenStatus: raw.display_seen_status === 1,
964
+ addFriendViaPhone: raw.add_friend_via_phone === 1,
965
+ addFriendViaContact: raw.add_friend_via_contact === 1,
966
+ addFriendViaGroup: raw.add_friend_via_group === 1,
967
+ addFriendViaQR: raw.add_friend_via_qr === 1,
968
+ acceptStrangerCall: raw.accept_stranger_call === 1,
969
+ twoFactorEnabled: raw.setting_2FA_status === 1
970
+ };
971
+ }
972
+
973
+ // src/services/index.ts
974
+ function ensureConnected(transport) {
975
+ if (!transport.isConnected()) {
976
+ throw new AuthenticationError();
977
+ }
978
+ }
979
+ var AccountService = class {
980
+ constructor(deps) {
981
+ this.deps = deps;
982
+ }
983
+ deps;
984
+ getOwnId() {
985
+ ensureConnected(this.deps.transport);
986
+ return this.deps.transport.getOwnId();
987
+ }
988
+ async getMe() {
989
+ ensureConnected(this.deps.transport);
990
+ const raw = await this.deps.executor.execute(() => this.deps.transport.fetchAccountInfo(), {
991
+ operation: "account.getMe",
992
+ idempotent: true
993
+ });
994
+ const data = mapProfileData(raw ?? { userId: this.deps.transport.getOwnId() });
995
+ this.deps.registry.registerUser(data.id);
996
+ return new Profile(data, this.deps.actions);
997
+ }
998
+ async updateProfile(patch) {
999
+ ensureConnected(this.deps.transport);
1000
+ if (!patch.name.trim()) throw new ValidationError("name must not be empty");
1001
+ await this.deps.executor.execute(
1002
+ () => this.deps.transport.updateProfile({
1003
+ name: patch.name.trim(),
1004
+ dob: patch.dob,
1005
+ gender: patch.gender === "male" ? 0 : 1
1006
+ }),
1007
+ { operation: "account.updateProfile", idempotent: true }
1008
+ );
1009
+ }
1010
+ async updateBio(bio) {
1011
+ ensureConnected(this.deps.transport);
1012
+ await this.deps.executor.execute(() => this.deps.transport.updateBio(bio), {
1013
+ operation: "account.updateBio",
1014
+ idempotent: true
1015
+ });
1016
+ }
1017
+ async keepAlive() {
1018
+ ensureConnected(this.deps.transport);
1019
+ return this.deps.executor.execute(() => this.deps.transport.keepAlive(), {
1020
+ operation: "account.keepAlive",
1021
+ idempotent: true
1022
+ });
1023
+ }
1024
+ };
1025
+ var UsersService = class {
1026
+ constructor(deps) {
1027
+ this.deps = deps;
1028
+ }
1029
+ deps;
1030
+ async get(userId, options) {
1031
+ ensureConnected(this.deps.transport);
1032
+ const id = userId.trim();
1033
+ if (!id) throw new ValidationError("userId must be a non-empty string");
1034
+ if (!options?.skipCache) {
1035
+ const cached = this.deps.userCache.get(id);
1036
+ if (cached) return cached;
1037
+ }
1038
+ return this.deps.dedup.run(`user:${id}`, async () => {
1039
+ const profiles = await this.deps.executor.execute(() => this.deps.transport.getUserInfo(id), {
1040
+ operation: "users.get",
1041
+ idempotent: true
1042
+ });
1043
+ const raw = profiles[id] ?? Object.values(profiles)[0];
1044
+ if (!raw) return null;
1045
+ const user = new User(mapUserData(raw), this.deps.actions);
1046
+ this.deps.registry.registerUser(user.id);
1047
+ this.deps.userCache.set(user.id, user);
1048
+ return user;
1049
+ });
1050
+ }
1051
+ async getMany(userIds) {
1052
+ ensureConnected(this.deps.transport);
1053
+ const ids = userIds.map((u) => u.trim()).filter(Boolean);
1054
+ if (ids.length === 0) throw new ValidationError("userIds must not be empty");
1055
+ const rawMap = await this.deps.executor.execute(() => this.deps.transport.getUserInfo(ids), {
1056
+ operation: "users.getMany",
1057
+ idempotent: true
1058
+ });
1059
+ const out = {};
1060
+ for (const [id, raw] of Object.entries(rawMap)) {
1061
+ const user = new User(mapUserData(raw), this.deps.actions);
1062
+ this.deps.registry.registerUser(user.id);
1063
+ this.deps.userCache.set(user.id, user);
1064
+ out[id] = user;
1065
+ }
1066
+ return out;
1067
+ }
1068
+ async findByPhone(phoneNumber) {
1069
+ ensureConnected(this.deps.transport);
1070
+ const phone = phoneNumber.trim();
1071
+ if (!phone) throw new ValidationError("phoneNumber must be a non-empty string");
1072
+ const raw = await this.deps.executor.execute(() => this.deps.transport.findUserByPhone(phone), {
1073
+ operation: "users.findByPhone",
1074
+ idempotent: true
1075
+ });
1076
+ if (!raw) return null;
1077
+ const user = new User(mapUserData(raw), this.deps.actions);
1078
+ this.deps.registry.registerUser(user.id);
1079
+ this.deps.userCache.set(user.id, user);
1080
+ return user;
1081
+ }
1082
+ async findByUsername(username) {
1083
+ ensureConnected(this.deps.transport);
1084
+ const cleaned = username.trim();
1085
+ if (!cleaned) throw new ValidationError("username must be a non-empty string");
1086
+ const raw = await this.deps.executor.execute(
1087
+ () => this.deps.transport.findUserByUsername(cleaned),
1088
+ { operation: "users.findByUsername", idempotent: true }
1089
+ );
1090
+ if (!raw) return null;
1091
+ const user = new User(mapUserData(raw), this.deps.actions);
1092
+ this.deps.registry.registerUser(user.id);
1093
+ this.deps.userCache.set(user.id, user);
1094
+ return user;
1095
+ }
1096
+ async getLastOnline(userId) {
1097
+ ensureConnected(this.deps.transport);
1098
+ const id = userId.trim();
1099
+ if (!id) throw new ValidationError("userId must be a non-empty string");
1100
+ const raw = await this.deps.executor.execute(() => this.deps.transport.getLastOnline(id), {
1101
+ operation: "users.getLastOnline",
1102
+ idempotent: true
1103
+ });
1104
+ return mapLastOnline(id, raw);
1105
+ }
1106
+ };
1107
+ var ContactsService = class {
1108
+ constructor(deps) {
1109
+ this.deps = deps;
1110
+ }
1111
+ deps;
1112
+ async list(options = {}) {
1113
+ ensureConnected(this.deps.transport);
1114
+ const rawList = await this.deps.executor.execute(
1115
+ () => this.deps.transport.getAllFriends(options.count, options.page),
1116
+ { operation: "contacts.list", idempotent: true }
1117
+ );
1118
+ return rawList.map((raw) => {
1119
+ const contact = new Contact(mapContactData(raw), this.deps.actions);
1120
+ this.deps.registry.registerUser(contact.id);
1121
+ this.deps.userCache.set(contact.id, contact);
1122
+ return contact;
1123
+ });
1124
+ }
1125
+ async sendRequest(userId, message = "Hello!") {
1126
+ ensureConnected(this.deps.transport);
1127
+ if (!userId.trim()) throw new ValidationError("userId must not be empty");
1128
+ await this.deps.executor.execute(
1129
+ () => this.deps.transport.sendFriendRequest(userId.trim(), message),
1130
+ { operation: "contacts.sendRequest", idempotent: false }
1131
+ );
1132
+ }
1133
+ async acceptRequest(userId) {
1134
+ ensureConnected(this.deps.transport);
1135
+ await this.deps.executor.execute(() => this.deps.transport.acceptFriendRequest(userId.trim()), {
1136
+ operation: "contacts.acceptRequest",
1137
+ idempotent: true
1138
+ });
1139
+ }
1140
+ async rejectRequest(userId) {
1141
+ ensureConnected(this.deps.transport);
1142
+ await this.deps.executor.execute(() => this.deps.transport.rejectFriendRequest(userId.trim()), {
1143
+ operation: "contacts.rejectRequest",
1144
+ idempotent: true
1145
+ });
1146
+ }
1147
+ async remove(userId) {
1148
+ ensureConnected(this.deps.transport);
1149
+ await this.deps.executor.execute(() => this.deps.transport.removeFriend(userId.trim()), {
1150
+ operation: "contacts.remove",
1151
+ idempotent: true
1152
+ });
1153
+ }
1154
+ async block(userId) {
1155
+ ensureConnected(this.deps.transport);
1156
+ await this.deps.executor.execute(() => this.deps.transport.blockUser(userId.trim()), {
1157
+ operation: "contacts.block",
1158
+ idempotent: true
1159
+ });
1160
+ }
1161
+ async unblock(userId) {
1162
+ ensureConnected(this.deps.transport);
1163
+ await this.deps.executor.execute(() => this.deps.transport.unblockUser(userId.trim()), {
1164
+ operation: "contacts.unblock",
1165
+ idempotent: true
1166
+ });
1167
+ }
1168
+ async setAlias(userId, alias) {
1169
+ ensureConnected(this.deps.transport);
1170
+ await this.deps.executor.execute(
1171
+ () => this.deps.transport.setFriendAlias(userId.trim(), alias),
1172
+ { operation: "contacts.setAlias", idempotent: true }
1173
+ );
1174
+ }
1175
+ async getOnline() {
1176
+ ensureConnected(this.deps.transport);
1177
+ const raw = await this.deps.executor.execute(() => this.deps.transport.getOnlineFriends(), {
1178
+ operation: "contacts.getOnline",
1179
+ idempotent: true
1180
+ });
1181
+ return mapOnlineFriends(raw);
1182
+ }
1183
+ };
1184
+ var GroupsService = class {
1185
+ constructor(deps) {
1186
+ this.deps = deps;
1187
+ }
1188
+ deps;
1189
+ async list() {
1190
+ ensureConnected(this.deps.transport);
1191
+ const map = await this.deps.executor.execute(() => this.deps.transport.getAllGroups(), {
1192
+ operation: "groups.list",
1193
+ idempotent: true
1194
+ });
1195
+ const summaries = mapGroupSummaries(map);
1196
+ this.deps.registry.registerGroups(summaries.map((g) => g.id));
1197
+ return summaries;
1198
+ }
1199
+ async get(groupId, options) {
1200
+ ensureConnected(this.deps.transport);
1201
+ const id = groupId.trim();
1202
+ if (!id) throw new ValidationError("groupId must be a non-empty string");
1203
+ if (!options?.skipCache) {
1204
+ const cached = this.deps.groupCache.get(id);
1205
+ if (cached) return cached;
1206
+ }
1207
+ return this.deps.dedup.run(`group:${id}`, async () => {
1208
+ const map = await this.deps.executor.execute(() => this.deps.transport.getGroupInfo(id), {
1209
+ operation: "groups.get",
1210
+ idempotent: true
1211
+ });
1212
+ const raw = map[id];
1213
+ if (!raw) throw new NotFoundError(`Group "${id}" was not found`);
1214
+ const group = new Group(mapGroupData(raw, id), this.deps.actions);
1215
+ this.deps.registry.registerGroup(group.id);
1216
+ this.deps.groupCache.set(group.id, group);
1217
+ return group;
1218
+ });
1219
+ }
1220
+ async getMany(groupIds) {
1221
+ ensureConnected(this.deps.transport);
1222
+ const ids = groupIds.map((g) => g.trim()).filter(Boolean);
1223
+ if (ids.length === 0) throw new ValidationError("groupIds must not be empty");
1224
+ const map = await this.deps.executor.execute(() => this.deps.transport.getGroupInfo(ids), {
1225
+ operation: "groups.getMany",
1226
+ idempotent: true
1227
+ });
1228
+ const out = {};
1229
+ for (const [id, raw] of Object.entries(map)) {
1230
+ const group = new Group(mapGroupData(raw, id), this.deps.actions);
1231
+ this.deps.registry.registerGroup(group.id);
1232
+ this.deps.groupCache.set(group.id, group);
1233
+ out[id] = group;
1234
+ }
1235
+ return out;
1236
+ }
1237
+ async create(options) {
1238
+ ensureConnected(this.deps.transport);
1239
+ const members = options.members.map((m) => m.trim()).filter(Boolean);
1240
+ if (members.length === 0) throw new ValidationError("members must contain at least one userId");
1241
+ const created = await this.deps.executor.execute(
1242
+ () => this.deps.transport.createGroup({ name: options.name, members }),
1243
+ { operation: "groups.create", idempotent: false }
1244
+ );
1245
+ this.deps.registry.registerGroup(created.groupId);
1246
+ return this.get(created.groupId, { skipCache: true });
1247
+ }
1248
+ async getMembers(memberIds) {
1249
+ ensureConnected(this.deps.transport);
1250
+ const ids = memberIds.map((m) => m.trim()).filter(Boolean);
1251
+ if (ids.length === 0) throw new ValidationError("memberIds must not be empty");
1252
+ const profiles = await this.deps.executor.execute(
1253
+ () => this.deps.transport.getGroupMembersInfo(ids),
1254
+ { operation: "groups.getMembers", idempotent: true }
1255
+ );
1256
+ return Object.values(profiles).map(mapGroupMember);
1257
+ }
1258
+ async addMembers(groupId, userIds) {
1259
+ ensureConnected(this.deps.transport);
1260
+ const id = groupId.trim();
1261
+ const ids = userIds.map((u) => u.trim()).filter(Boolean);
1262
+ if (!id || ids.length === 0) throw new ValidationError("groupId and userIds are required");
1263
+ await this.deps.executor.execute(() => this.deps.transport.addGroupMembers(id, ids), {
1264
+ operation: "groups.addMembers",
1265
+ idempotent: true
1266
+ });
1267
+ this.deps.groupCache.delete(id);
1268
+ }
1269
+ async removeMembers(groupId, userIds) {
1270
+ ensureConnected(this.deps.transport);
1271
+ const id = groupId.trim();
1272
+ const ids = userIds.map((u) => u.trim()).filter(Boolean);
1273
+ if (!id || ids.length === 0) throw new ValidationError("groupId and userIds are required");
1274
+ await this.deps.executor.execute(() => this.deps.transport.removeGroupMembers(id, ids), {
1275
+ operation: "groups.removeMembers",
1276
+ idempotent: true
1277
+ });
1278
+ this.deps.groupCache.delete(id);
1279
+ }
1280
+ async rename(groupId, name) {
1281
+ ensureConnected(this.deps.transport);
1282
+ const id = groupId.trim();
1283
+ if (!id || !name.trim()) throw new ValidationError("groupId and name are required");
1284
+ await this.deps.executor.execute(() => this.deps.transport.renameGroup(id, name.trim()), {
1285
+ operation: "groups.rename",
1286
+ idempotent: true
1287
+ });
1288
+ this.deps.groupCache.delete(id);
1289
+ }
1290
+ async leave(groupId) {
1291
+ ensureConnected(this.deps.transport);
1292
+ const id = groupId.trim();
1293
+ if (!id) throw new ValidationError("groupId is required");
1294
+ await this.deps.executor.execute(() => this.deps.transport.leaveGroup(id), {
1295
+ operation: "groups.leave",
1296
+ idempotent: false
1297
+ });
1298
+ this.deps.groupCache.delete(id);
1299
+ }
1300
+ };
1301
+ var ConversationsService = class {
1302
+ constructor(deps) {
1303
+ this.deps = deps;
1304
+ }
1305
+ deps;
1306
+ fetchGroupIds = async () => {
1307
+ const map = await this.deps.transport.getAllGroups();
1308
+ return Object.keys(map);
1309
+ };
1310
+ async get(id, threadType) {
1311
+ ensureConnected(this.deps.transport);
1312
+ if (!id.trim()) throw new ValidationError("conversation id must not be empty");
1313
+ const resolved = await this.deps.registry.resolve(id, threadType, this.fetchGroupIds);
1314
+ return new Conversation(resolved.threadId, resolved.threadType, this.deps.actions);
1315
+ }
1316
+ async getMessages(conversationId, count) {
1317
+ ensureConnected(this.deps.transport);
1318
+ const id = conversationId.trim();
1319
+ if (!id) throw new ValidationError("conversationId must not be empty");
1320
+ const res = await this.deps.executor.execute(
1321
+ () => this.deps.transport.getGroupChatHistory(id, count),
1322
+ { operation: "conversations.getMessages", idempotent: true }
1323
+ );
1324
+ return {
1325
+ items: res.messages.map((raw) => new Message(mapMessageData(raw), this.deps.actions)),
1326
+ hasMore: res.hasMore,
1327
+ nextCursor: res.nextCursor
1328
+ };
1329
+ }
1330
+ async getPinned() {
1331
+ ensureConnected(this.deps.transport);
1332
+ return this.deps.executor.execute(() => this.deps.transport.getPinnedConversations(), {
1333
+ operation: "conversations.getPinned",
1334
+ idempotent: true
1335
+ });
1336
+ }
1337
+ async getUnread() {
1338
+ ensureConnected(this.deps.transport);
1339
+ return this.deps.executor.execute(() => this.deps.transport.getUnreadMarks(), {
1340
+ operation: "conversations.getUnread",
1341
+ idempotent: true
1342
+ });
1343
+ }
1344
+ async pin(target, pinned = true) {
1345
+ ensureConnected(this.deps.transport);
1346
+ const { threadId, threadType } = await this.deps.registry.resolve(
1347
+ target,
1348
+ void 0,
1349
+ this.fetchGroupIds
1350
+ );
1351
+ await this.deps.executor.execute(
1352
+ () => this.deps.transport.setPinnedConversations([threadId], pinned, threadType),
1353
+ { operation: "conversations.pin", idempotent: true }
1354
+ );
1355
+ }
1356
+ async mute(target, durationSeconds) {
1357
+ ensureConnected(this.deps.transport);
1358
+ const { threadId, threadType } = await this.deps.registry.resolve(
1359
+ target,
1360
+ void 0,
1361
+ this.fetchGroupIds
1362
+ );
1363
+ await this.deps.executor.execute(
1364
+ () => this.deps.transport.setMute(threadId, durationSeconds, threadType),
1365
+ { operation: "conversations.mute", idempotent: true }
1366
+ );
1367
+ }
1368
+ async sendTyping(target) {
1369
+ ensureConnected(this.deps.transport);
1370
+ const { threadId, threadType } = await this.deps.registry.resolve(
1371
+ target,
1372
+ void 0,
1373
+ this.fetchGroupIds
1374
+ );
1375
+ await this.deps.executor.execute(() => this.deps.transport.sendTyping(threadId, threadType), {
1376
+ operation: "conversations.sendTyping",
1377
+ idempotent: true
1378
+ });
1379
+ }
1380
+ };
1381
+ var MessagesService = class {
1382
+ constructor(deps) {
1383
+ this.deps = deps;
1384
+ }
1385
+ deps;
1386
+ fetchGroupIds = async () => {
1387
+ const map = await this.deps.transport.getAllGroups();
1388
+ return Object.keys(map);
1389
+ };
1390
+ /**
1391
+ * Unified message sender. Automatically resolves threadType from target or Group ID cache.
1392
+ */
1393
+ async send(target, content, explicitType) {
1394
+ ensureConnected(this.deps.transport);
1395
+ const payload = typeof content === "string" ? { text: content } : content;
1396
+ const hasMedia = Boolean(
1397
+ payload.attachment || payload.attachments && payload.attachments.length > 0 || payload.link || payload.sticker || payload.voice || payload.video
1398
+ );
1399
+ if (!payload.text && !hasMedia) {
1400
+ throw new ValidationError("Message payload must contain text or media/link/sticker");
1401
+ }
1402
+ const targetLike = target instanceof Message ? { id: target.threadId, threadType: target.threadType } : target;
1403
+ const resolved = await this.deps.registry.resolve(
1404
+ targetLike,
1405
+ explicitType ?? payload.threadType,
1406
+ this.fetchGroupIds
1407
+ );
1408
+ if (!resolved.threadId) {
1409
+ throw new ValidationError("Target threadId must be a non-empty string");
1410
+ }
1411
+ return this.deps.executor.execute(
1412
+ () => this.deps.transport.sendMessage(resolved.threadId, payload, resolved.threadType),
1413
+ { operation: "messages.send", idempotent: false }
1414
+ );
1415
+ }
1416
+ async reply(message, content) {
1417
+ const payload = typeof content === "string" ? { text: content, replyTo: message } : { ...content, replyTo: message };
1418
+ return this.send(message, payload, message.threadType);
1419
+ }
1420
+ async react(message, reaction) {
1421
+ ensureConnected(this.deps.transport);
1422
+ await this.deps.executor.execute(() => this.deps.transport.addReaction(message, reaction), {
1423
+ operation: "messages.react",
1424
+ idempotent: true
1425
+ });
1426
+ }
1427
+ async undo(message) {
1428
+ ensureConnected(this.deps.transport);
1429
+ await this.deps.executor.execute(() => this.deps.transport.undoMessage(message), {
1430
+ operation: "messages.undo",
1431
+ idempotent: true
1432
+ });
1433
+ }
1434
+ async delete(message, onlyMe = true) {
1435
+ ensureConnected(this.deps.transport);
1436
+ await this.deps.executor.execute(() => this.deps.transport.deleteMessage(message, onlyMe), {
1437
+ operation: "messages.delete",
1438
+ idempotent: true
1439
+ });
1440
+ }
1441
+ async markSeen(messages) {
1442
+ ensureConnected(this.deps.transport);
1443
+ if (messages.length === 0) throw new ValidationError("markSeen requires at least one message");
1444
+ const threadType = messages[0].threadType;
1445
+ await this.deps.executor.execute(() => this.deps.transport.markSeen(messages, threadType), {
1446
+ operation: "messages.markSeen",
1447
+ idempotent: true
1448
+ });
1449
+ }
1450
+ };
1451
+ var MediaService = class {
1452
+ constructor(deps, messages) {
1453
+ this.deps = deps;
1454
+ this.messages = messages;
1455
+ }
1456
+ deps;
1457
+ messages;
1458
+ fetchGroupIds = async () => {
1459
+ const map = await this.deps.transport.getAllGroups();
1460
+ return Object.keys(map);
1461
+ };
1462
+ async upload(target, sources, explicitType) {
1463
+ ensureConnected(this.deps.transport);
1464
+ const list = Array.isArray(sources) ? sources : [sources];
1465
+ if (list.length === 0) throw new ValidationError("upload requires at least one media item");
1466
+ const targetLike = target instanceof Message ? { id: target.threadId, threadType: target.threadType } : target;
1467
+ const { threadId, threadType } = await this.deps.registry.resolve(
1468
+ targetLike,
1469
+ explicitType,
1470
+ this.fetchGroupIds
1471
+ );
1472
+ const raw = await this.deps.executor.execute(
1473
+ () => this.deps.transport.uploadAttachment(list, threadId, threadType),
1474
+ { operation: "media.upload", idempotent: false }
1475
+ );
1476
+ return raw.map(mapUploadedMedia);
1477
+ }
1478
+ send(target, media, caption) {
1479
+ const attachments = Array.isArray(media) ? media : [media];
1480
+ return this.messages.send(target, { text: caption, attachments });
1481
+ }
1482
+ };
1483
+ var SettingsService = class {
1484
+ constructor(deps) {
1485
+ this.deps = deps;
1486
+ }
1487
+ deps;
1488
+ async get() {
1489
+ ensureConnected(this.deps.transport);
1490
+ const raw = await this.deps.executor.execute(() => this.deps.transport.getAccountSettings(), {
1491
+ operation: "settings.get",
1492
+ idempotent: true
1493
+ });
1494
+ return mapAccountSettings(raw);
1495
+ }
1496
+ async updateLanguage(lang) {
1497
+ ensureConnected(this.deps.transport);
1498
+ await this.deps.executor.execute(() => this.deps.transport.updateLanguage(lang), {
1499
+ operation: "settings.updateLanguage",
1500
+ idempotent: true
1501
+ });
1502
+ }
1503
+ };
1504
+ function isNotFound(err) {
1505
+ return typeof err === "object" && err !== null && err.code === "ENOENT";
1506
+ }
1507
+ var MemorySessionStore = class {
1508
+ record = null;
1509
+ async load() {
1510
+ return this.record ? structuredClone(this.record) : null;
1511
+ }
1512
+ async save(record) {
1513
+ this.record = structuredClone(record);
1514
+ }
1515
+ async clear() {
1516
+ this.record = null;
1517
+ }
1518
+ };
1519
+ var FileSessionStore = class {
1520
+ constructor(filePath) {
1521
+ this.filePath = filePath;
1522
+ if (!filePath || typeof filePath !== "string") {
1523
+ throw new SessionError("FileSessionStore requires a non-empty filePath");
1524
+ }
1525
+ }
1526
+ filePath;
1527
+ async load() {
1528
+ try {
1529
+ const raw = await readFile(this.filePath, "utf8");
1530
+ const parsed = JSON.parse(raw);
1531
+ return parsed && typeof parsed === "object" && parsed.credentials ? parsed : null;
1532
+ } catch (err) {
1533
+ if (isNotFound(err)) return null;
1534
+ throw new SessionError(`Failed to read session file "${this.filePath}"`, err);
1535
+ }
1536
+ }
1537
+ async save(record) {
1538
+ const dir = dirname(this.filePath);
1539
+ const tmp = `${this.filePath}.tmp.${Date.now()}.${randomBytes(4).toString("hex")}`;
1540
+ try {
1541
+ await mkdir(dir, { recursive: true });
1542
+ await writeFile(tmp, JSON.stringify(record, null, 2), { encoding: "utf8", mode: 384 });
1543
+ await rename(tmp, this.filePath);
1544
+ if (process.platform !== "win32") {
1545
+ await chmod(this.filePath, 384).catch(() => {
1546
+ });
1547
+ }
1548
+ } catch (err) {
1549
+ await unlink(tmp).catch(() => {
1550
+ });
1551
+ throw new SessionError(`Failed to save session file "${this.filePath}"`, err);
1552
+ }
1553
+ }
1554
+ async clear() {
1555
+ try {
1556
+ await unlink(this.filePath);
1557
+ } catch (err) {
1558
+ if (isNotFound(err)) return;
1559
+ throw new SessionError(`Failed to remove session file "${this.filePath}"`, err);
1560
+ }
1561
+ }
1562
+ };
1563
+ var EncryptedFileSessionStore = class {
1564
+ constructor(filePath, secret) {
1565
+ this.filePath = filePath;
1566
+ this.secret = secret;
1567
+ if (!filePath) throw new SessionError("EncryptedFileSessionStore requires a non-empty filePath");
1568
+ const len = typeof secret === "string" ? Buffer.byteLength(secret, "utf8") : secret.length;
1569
+ if (len < 16) throw new SessionError("Encryption secret must be at least 16 bytes");
1570
+ }
1571
+ filePath;
1572
+ secret;
1573
+ deriveKey(salt) {
1574
+ return scryptSync(this.secret, salt, 32);
1575
+ }
1576
+ async load() {
1577
+ try {
1578
+ const raw = await readFile(this.filePath, "utf8");
1579
+ const env = JSON.parse(raw);
1580
+ if (env?.v !== 1 || env.alg !== "aes-256-gcm") {
1581
+ throw new SessionError("Unsupported encrypted session format");
1582
+ }
1583
+ const key = this.deriveKey(Buffer.from(env.salt, "base64"));
1584
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
1585
+ decipher.setAuthTag(Buffer.from(env.tag, "base64"));
1586
+ const plain = Buffer.concat([
1587
+ decipher.update(Buffer.from(env.data, "base64")),
1588
+ decipher.final()
1589
+ ]).toString("utf8");
1590
+ return JSON.parse(plain);
1591
+ } catch (err) {
1592
+ if (isNotFound(err)) return null;
1593
+ if (err instanceof SessionError) throw err;
1594
+ throw new SessionError(`Failed to decrypt session file "${this.filePath}"`, err);
1595
+ }
1596
+ }
1597
+ async save(record) {
1598
+ const dir = dirname(this.filePath);
1599
+ const tmp = `${this.filePath}.tmp.${Date.now()}.${randomBytes(4).toString("hex")}`;
1600
+ try {
1601
+ const salt = randomBytes(16);
1602
+ const iv = randomBytes(12);
1603
+ const key = this.deriveKey(salt);
1604
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
1605
+ const encrypted = Buffer.concat([
1606
+ cipher.update(Buffer.from(JSON.stringify(record), "utf8")),
1607
+ cipher.final()
1608
+ ]);
1609
+ const envelope = {
1610
+ v: 1,
1611
+ alg: "aes-256-gcm",
1612
+ salt: salt.toString("base64"),
1613
+ iv: iv.toString("base64"),
1614
+ tag: cipher.getAuthTag().toString("base64"),
1615
+ data: encrypted.toString("base64")
1616
+ };
1617
+ await mkdir(dir, { recursive: true });
1618
+ await writeFile(tmp, JSON.stringify(envelope), { encoding: "utf8", mode: 384 });
1619
+ await rename(tmp, this.filePath);
1620
+ if (process.platform !== "win32") {
1621
+ await chmod(this.filePath, 384).catch(() => {
1622
+ });
1623
+ }
1624
+ } catch (err) {
1625
+ await unlink(tmp).catch(() => {
1626
+ });
1627
+ throw new SessionError(`Failed to save encrypted session "${this.filePath}"`, err);
1628
+ }
1629
+ }
1630
+ async clear() {
1631
+ try {
1632
+ await unlink(this.filePath);
1633
+ } catch (err) {
1634
+ if (isNotFound(err)) return;
1635
+ throw new SessionError(`Failed to remove encrypted session "${this.filePath}"`, err);
1636
+ }
1637
+ }
1638
+ };
1639
+ function toZcaType(t) {
1640
+ return t === 1 /* Group */ ? ThreadType$1.Group : ThreadType$1.User;
1641
+ }
1642
+ function toAttachment(input) {
1643
+ if (typeof input === "string") return input;
1644
+ return {
1645
+ data: input.data,
1646
+ filename: input.filename,
1647
+ metadata: {
1648
+ totalSize: input.totalSize ?? input.data.length,
1649
+ width: input.width,
1650
+ height: input.height
1651
+ }
1652
+ };
1653
+ }
1654
+ function normalizeQRImage(raw) {
1655
+ const s = raw.trim();
1656
+ if (s.startsWith("data:")) {
1657
+ const idx = s.indexOf(",");
1658
+ return { imageBase64: idx >= 0 ? s.slice(idx + 1) : s, imageDataUrl: s };
1659
+ }
1660
+ return { imageBase64: s, imageDataUrl: `data:image/png;base64,${s}` };
1661
+ }
1662
+ var ZcaTransport = class {
1663
+ constructor(options = {}) {
1664
+ this.options = options;
1665
+ }
1666
+ options;
1667
+ api = null;
1668
+ listenerAttached = false;
1669
+ createEngine() {
1670
+ return new Zalo({
1671
+ logging: false,
1672
+ selfListen: this.options.selfListen ?? false,
1673
+ checkUpdate: this.options.checkUpdate ?? false,
1674
+ imageMetadataGetter: this.options.imageMetadataGetter
1675
+ });
1676
+ }
1677
+ requireApi() {
1678
+ if (!this.api) {
1679
+ throw new AuthenticationError("Zapind client is not authenticated. Call await client.login() first.");
1680
+ }
1681
+ return this.api;
1682
+ }
1683
+ isConnected() {
1684
+ return this.api !== null;
1685
+ }
1686
+ getOwnId() {
1687
+ return String(this.requireApi().getOwnId());
1688
+ }
1689
+ getRawApi() {
1690
+ return this.requireApi();
1691
+ }
1692
+ async loginWithCredentials(credentials) {
1693
+ const engine = this.createEngine();
1694
+ const creds = {
1695
+ imei: credentials.imei,
1696
+ cookie: credentials.cookie,
1697
+ userAgent: credentials.userAgent,
1698
+ language: credentials.language
1699
+ };
1700
+ this.api = await engine.login(creds);
1701
+ this.listenerAttached = false;
1702
+ }
1703
+ async loginWithQR(options, callbacks) {
1704
+ const engine = this.createEngine();
1705
+ let captured = null;
1706
+ let abortFn = null;
1707
+ let failure = null;
1708
+ const onAbort = () => {
1709
+ failure = new AuthenticationError("QR code login timed out");
1710
+ try {
1711
+ abortFn?.();
1712
+ } catch {
1713
+ }
1714
+ };
1715
+ if (options.signal) {
1716
+ if (options.signal.aborted) throw new AuthenticationError("QR login aborted");
1717
+ options.signal.addEventListener("abort", onAbort, { once: true });
1718
+ }
1719
+ const onEvent = (evt) => {
1720
+ if (evt.actions && typeof evt.actions.abort === "function") {
1721
+ abortFn = evt.actions.abort;
1722
+ }
1723
+ switch (evt.type) {
1724
+ case LoginQRCallbackEventType.QRCodeGenerated: {
1725
+ const { imageBase64, imageDataUrl } = normalizeQRImage(String(evt.data?.image ?? ""));
1726
+ callbacks.onQRCode?.({ imageBase64, imageDataUrl, code: evt.data?.code });
1727
+ break;
1728
+ }
1729
+ case LoginQRCallbackEventType.QRCodeScanned: {
1730
+ callbacks.onScanned?.({
1731
+ displayName: String(evt.data?.display_name ?? ""),
1732
+ avatarUrl: String(evt.data?.avatar ?? "")
1733
+ });
1734
+ break;
1735
+ }
1736
+ case LoginQRCallbackEventType.QRCodeExpired: {
1737
+ failure = new AuthenticationError("QR code expired");
1738
+ callbacks.onExpired?.();
1739
+ try {
1740
+ evt.actions?.abort?.();
1741
+ } catch {
1742
+ }
1743
+ break;
1744
+ }
1745
+ case LoginQRCallbackEventType.QRCodeDeclined: {
1746
+ failure = new AuthenticationError("QR code login declined on device");
1747
+ callbacks.onDeclined?.();
1748
+ try {
1749
+ evt.actions?.abort?.();
1750
+ } catch {
1751
+ }
1752
+ break;
1753
+ }
1754
+ case LoginQRCallbackEventType.GotLoginInfo: {
1755
+ captured = {
1756
+ cookie: evt.data?.cookie ?? [],
1757
+ imei: String(evt.data?.imei ?? ""),
1758
+ userAgent: String(evt.data?.userAgent ?? options.userAgent),
1759
+ language: options.language
1760
+ };
1761
+ callbacks.onCredentials?.(captured);
1762
+ break;
1763
+ }
1764
+ }
1765
+ };
1766
+ try {
1767
+ const logged = await engine.loginQR(
1768
+ { userAgent: options.userAgent, language: options.language },
1769
+ onEvent
1770
+ );
1771
+ this.api = logged;
1772
+ this.listenerAttached = false;
1773
+ if (!captured) {
1774
+ const ctx = logged.getContext();
1775
+ const jar = logged.getCookie().toJSON();
1776
+ captured = {
1777
+ cookie: jar?.cookies ?? [],
1778
+ imei: String(ctx.imei ?? ""),
1779
+ userAgent: String(ctx.userAgent ?? options.userAgent),
1780
+ language: options.language
1781
+ };
1782
+ }
1783
+ return captured;
1784
+ } catch (err) {
1785
+ if (failure) throw failure;
1786
+ throw err;
1787
+ } finally {
1788
+ options.signal?.removeEventListener("abort", onAbort);
1789
+ }
1790
+ }
1791
+ async disconnect() {
1792
+ this.stopListening();
1793
+ this.api = null;
1794
+ }
1795
+ async fetchAccountInfo() {
1796
+ const res = await this.requireApi().fetchAccountInfo();
1797
+ return res?.profile ?? null;
1798
+ }
1799
+ async updateProfile(patch) {
1800
+ await this.requireApi().updateProfile({
1801
+ profile: {
1802
+ name: patch.name,
1803
+ dob: patch.dob,
1804
+ gender: patch.gender
1805
+ }
1806
+ });
1807
+ }
1808
+ async updateBio(bio) {
1809
+ await this.requireApi().updateProfileBio(bio);
1810
+ }
1811
+ async keepAlive() {
1812
+ const res = await this.requireApi().keepAlive();
1813
+ return { configVersion: Number(res?.config_vesion ?? 0) };
1814
+ }
1815
+ async getUserInfo(userIds) {
1816
+ const res = await this.requireApi().getUserInfo(userIds);
1817
+ return res?.changed_profiles ?? {};
1818
+ }
1819
+ async findUserByPhone(phone) {
1820
+ const res = await this.requireApi().findUser(phone);
1821
+ return res ?? null;
1822
+ }
1823
+ async findUserByUsername(username) {
1824
+ const res = await this.requireApi().findUserByUsername(username);
1825
+ return res ?? null;
1826
+ }
1827
+ async getLastOnline(userId) {
1828
+ const res = await this.requireApi().lastOnline(userId);
1829
+ return res;
1830
+ }
1831
+ async getAllFriends(count, page) {
1832
+ const res = await this.requireApi().getAllFriends(count, page);
1833
+ return Array.isArray(res) ? res : [];
1834
+ }
1835
+ async sendFriendRequest(userId, message) {
1836
+ await this.requireApi().sendFriendRequest(message, userId);
1837
+ }
1838
+ async acceptFriendRequest(userId) {
1839
+ await this.requireApi().acceptFriendRequest(userId);
1840
+ }
1841
+ async rejectFriendRequest(userId) {
1842
+ await this.requireApi().rejectFriendRequest(userId);
1843
+ }
1844
+ async removeFriend(userId) {
1845
+ await this.requireApi().removeFriend(userId);
1846
+ }
1847
+ async blockUser(userId) {
1848
+ await this.requireApi().blockUser(userId);
1849
+ }
1850
+ async unblockUser(userId) {
1851
+ await this.requireApi().unblockUser(userId);
1852
+ }
1853
+ async setFriendAlias(userId, alias) {
1854
+ await this.requireApi().changeFriendAlias(alias, userId);
1855
+ }
1856
+ async getOnlineFriends() {
1857
+ const res = await this.requireApi().getFriendOnlines();
1858
+ return Array.isArray(res?.onlines) ? res.onlines : [];
1859
+ }
1860
+ async getAllGroups() {
1861
+ const res = await this.requireApi().getAllGroups();
1862
+ return res?.gridVerMap ?? {};
1863
+ }
1864
+ async getGroupInfo(groupIds) {
1865
+ const res = await this.requireApi().getGroupInfo(groupIds);
1866
+ return res?.gridInfoMap ?? {};
1867
+ }
1868
+ async getGroupMembersInfo(memberIds) {
1869
+ const res = await this.requireApi().getGroupMembersInfo(memberIds);
1870
+ return res?.profiles ?? {};
1871
+ }
1872
+ async createGroup(options) {
1873
+ const res = await this.requireApi().createGroup({
1874
+ name: options.name,
1875
+ members: options.members
1876
+ });
1877
+ return { groupId: String(res?.groupId ?? "") };
1878
+ }
1879
+ async addGroupMembers(groupId, userIds) {
1880
+ await this.requireApi().addUserToGroup(userIds, groupId);
1881
+ }
1882
+ async removeGroupMembers(groupId, userIds) {
1883
+ await this.requireApi().removeUserFromGroup(userIds, groupId);
1884
+ }
1885
+ async renameGroup(groupId, name) {
1886
+ await this.requireApi().changeGroupName(name, groupId);
1887
+ }
1888
+ async leaveGroup(groupId) {
1889
+ await this.requireApi().leaveGroup(groupId);
1890
+ }
1891
+ async getPinnedConversations() {
1892
+ const res = await this.requireApi().getPinConversations();
1893
+ return {
1894
+ conversationIds: Array.isArray(res?.conversations) ? res.conversations.map(String) : [],
1895
+ version: Number(res?.version ?? 0)
1896
+ };
1897
+ }
1898
+ async getUnreadMarks() {
1899
+ const res = await this.requireApi().getUnreadMark();
1900
+ const mapList = (items, threadType) => (Array.isArray(items) ? items : []).map((i) => ({
1901
+ threadId: String(i.id),
1902
+ threadType,
1903
+ clientMsgId: String(i.cliMsgId),
1904
+ senderId: String(i.fromUid),
1905
+ timestamp: new Date(i.ts < 1e12 ? i.ts * 1e3 : i.ts)
1906
+ }));
1907
+ return {
1908
+ groups: mapList(res?.data?.convsGroup, 1 /* Group */),
1909
+ users: mapList(res?.data?.convsUser, 0 /* User */)
1910
+ };
1911
+ }
1912
+ async setPinnedConversations(ids, pinned, threadType) {
1913
+ await this.requireApi().setPinnedConversations(pinned, ids, toZcaType(threadType));
1914
+ }
1915
+ async setMute(threadId, durationSeconds, threadType) {
1916
+ const action = durationSeconds <= 0 ? MuteAction.UNMUTE : MuteAction.MUTE;
1917
+ await this.requireApi().setMute(
1918
+ { action, duration: durationSeconds },
1919
+ threadId,
1920
+ toZcaType(threadType)
1921
+ );
1922
+ }
1923
+ async sendTyping(threadId, threadType) {
1924
+ await this.requireApi().sendTypingEvent(threadId, toZcaType(threadType));
1925
+ }
1926
+ async sendMessage(threadId, payload, threadType) {
1927
+ const api = this.requireApi();
1928
+ const zcaType = toZcaType(threadType);
1929
+ if (payload.link) {
1930
+ const res2 = await api.sendLink(
1931
+ { link: payload.link.url, msg: payload.text ?? payload.link.title },
1932
+ threadId,
1933
+ zcaType
1934
+ );
1935
+ return { messageId: res2?.msgId !== void 0 ? String(res2.msgId) : null, attachmentMessageIds: [] };
1936
+ }
1937
+ if (payload.sticker) {
1938
+ const res2 = await api.sendSticker(payload.sticker, threadId, zcaType);
1939
+ return { messageId: res2?.msgId !== void 0 ? String(res2.msgId) : null, attachmentMessageIds: [] };
1940
+ }
1941
+ if (payload.voice) {
1942
+ const res2 = await api.sendVoice(
1943
+ { voiceUrl: payload.voice.voiceUrl, ttl: payload.voice.ttlMs },
1944
+ threadId,
1945
+ zcaType
1946
+ );
1947
+ return { messageId: res2?.msgId !== void 0 ? String(res2.msgId) : null, attachmentMessageIds: [] };
1948
+ }
1949
+ if (payload.video) {
1950
+ const res2 = await api.sendVideo(
1951
+ {
1952
+ msg: payload.video.msg ?? payload.text,
1953
+ videoUrl: payload.video.videoUrl,
1954
+ thumbnailUrl: payload.video.thumbnailUrl,
1955
+ duration: payload.video.duration,
1956
+ width: payload.video.width,
1957
+ height: payload.video.height,
1958
+ ttl: payload.video.ttlMs
1959
+ },
1960
+ threadId,
1961
+ zcaType
1962
+ );
1963
+ return { messageId: res2?.msgId !== void 0 ? String(res2.msgId) : null, attachmentMessageIds: [] };
1964
+ }
1965
+ const content = { msg: payload.text ?? "" };
1966
+ const allAttachments = [];
1967
+ if (payload.attachment) allAttachments.push(payload.attachment);
1968
+ if (payload.attachments) allAttachments.push(...payload.attachments);
1969
+ if (allAttachments.length > 0) {
1970
+ content.attachments = allAttachments.map(toAttachment);
1971
+ }
1972
+ if (payload.mentions && payload.mentions.length > 0) {
1973
+ content.mentions = payload.mentions.map((m) => ({ uid: m.userId, pos: m.pos, len: m.len }));
1974
+ }
1975
+ if (payload.styles && payload.styles.length > 0) {
1976
+ content.styles = payload.styles.map(
1977
+ (s) => s.indentSize !== void 0 ? {
1978
+ start: s.start,
1979
+ len: s.len,
1980
+ st: s.style,
1981
+ indentSize: s.indentSize
1982
+ } : {
1983
+ start: s.start,
1984
+ len: s.len,
1985
+ st: s.style
1986
+ }
1987
+ );
1988
+ }
1989
+ if (payload.urgency !== void 0) {
1990
+ content.urgency = payload.urgency;
1991
+ }
1992
+ if (payload.replyTo) {
1993
+ content.quote = {
1994
+ content: payload.replyTo.text,
1995
+ msgType: payload.replyTo.msgType,
1996
+ propertyExt: void 0,
1997
+ uidFrom: payload.replyTo.sender.id,
1998
+ msgId: payload.replyTo.id,
1999
+ cliMsgId: payload.replyTo.clientMsgId,
2000
+ ts: String(payload.replyTo.timestamp.getTime()),
2001
+ ttl: payload.replyTo.ttlMs
2002
+ };
2003
+ }
2004
+ if (payload.ttlMs !== void 0) {
2005
+ content.ttl = payload.ttlMs;
2006
+ }
2007
+ const res = await api.sendMessage(content, threadId, zcaType);
2008
+ return {
2009
+ messageId: res?.message?.msgId !== void 0 ? String(res.message.msgId) : null,
2010
+ attachmentMessageIds: Array.isArray(res?.attachment) ? res.attachment.map((a) => String(a.msgId)) : []
2011
+ };
2012
+ }
2013
+ async getGroupChatHistory(groupId, count) {
2014
+ const res = await this.requireApi().getGroupChatHistory(groupId, count);
2015
+ return {
2016
+ messages: Array.isArray(res?.groupMsgs) ? res.groupMsgs : [],
2017
+ hasMore: res?.more === 1,
2018
+ nextCursor: res?.lastActionId ? String(res.lastActionId) : null
2019
+ };
2020
+ }
2021
+ async undoMessage(message) {
2022
+ await this.requireApi().undo(
2023
+ { msgId: message.id, cliMsgId: message.clientMsgId },
2024
+ message.threadId,
2025
+ toZcaType(message.threadType)
2026
+ );
2027
+ }
2028
+ async deleteMessage(message, onlyMe) {
2029
+ await this.requireApi().deleteMessage(
2030
+ {
2031
+ data: {
2032
+ cliMsgId: message.clientMsgId,
2033
+ msgId: message.id,
2034
+ uidFrom: message.sender.id
2035
+ },
2036
+ threadId: message.threadId,
2037
+ type: toZcaType(message.threadType)
2038
+ },
2039
+ onlyMe
2040
+ );
2041
+ }
2042
+ async addReaction(message, reaction) {
2043
+ await this.requireApi().addReaction(reaction, {
2044
+ data: { msgId: message.id, cliMsgId: message.clientMsgId },
2045
+ threadId: message.threadId,
2046
+ type: toZcaType(message.threadType)
2047
+ });
2048
+ }
2049
+ async markSeen(messages, threadType) {
2050
+ const params = messages.map((m) => ({
2051
+ msgId: m.id,
2052
+ cliMsgId: m.clientMsgId,
2053
+ uidFrom: m.sender.id,
2054
+ idTo: m.recipientId || m.threadId,
2055
+ msgType: m.msgType,
2056
+ st: m.st,
2057
+ at: m.at,
2058
+ cmd: m.cmd,
2059
+ ts: String(m.timestamp.getTime())
2060
+ }));
2061
+ await this.requireApi().sendSeenEvent(params, toZcaType(threadType));
2062
+ }
2063
+ async uploadAttachment(sources, threadId, threadType) {
2064
+ const res = await this.requireApi().uploadAttachment(
2065
+ sources.map(toAttachment),
2066
+ threadId,
2067
+ toZcaType(threadType)
2068
+ );
2069
+ return Array.isArray(res) ? res : [];
2070
+ }
2071
+ async getAccountSettings() {
2072
+ const res = await this.requireApi().getSettings();
2073
+ return res;
2074
+ }
2075
+ async updateLanguage(lang) {
2076
+ await this.requireApi().updateLang(
2077
+ lang === "EN" ? UpdateLangAvailableLanguages.EN : UpdateLangAvailableLanguages.VI
2078
+ );
2079
+ }
2080
+ startListening(handlers, options) {
2081
+ const api = this.requireApi();
2082
+ if (this.listenerAttached) return;
2083
+ this.listenerAttached = true;
2084
+ api.listener.on("message", (msg) => {
2085
+ handlers.onMessage(msg);
2086
+ });
2087
+ api.listener.on("reaction", (r) => {
2088
+ const ts = Number(r.data?.ts ?? Date.now());
2089
+ handlers.onReaction({
2090
+ threadId: String(r.threadId ?? ""),
2091
+ threadType: r.isGroup ? 1 /* Group */ : 0 /* User */,
2092
+ senderId: String(r.data?.uidFrom ?? ""),
2093
+ icon: String(r.data?.content?.rIcon ?? ""),
2094
+ targetMessageIds: Array.isArray(r.data?.content?.rMsg) ? r.data.content.rMsg.map((x) => String(x.gMsgID)) : [],
2095
+ isSelf: Boolean(r.isSelf),
2096
+ timestamp: new Date(Number.isFinite(ts) ? ts : Date.now())
2097
+ });
2098
+ });
2099
+ api.listener.on("group_event", (evt) => {
2100
+ const data = evt.data ?? {};
2101
+ handlers.onGroupUpdate({
2102
+ groupId: String(evt.threadId ?? data.groupId ?? ""),
2103
+ type: String(evt.type ?? "unknown"),
2104
+ actorId: typeof data.sourceId === "string" ? data.sourceId : void 0,
2105
+ targetIds: Array.isArray(data.updateMembers) ? data.updateMembers.map((m) => String(m.id ?? "")).filter(Boolean) : [],
2106
+ data
2107
+ });
2108
+ });
2109
+ api.listener.on("friend_event", (evt) => {
2110
+ const data = evt.data ?? {};
2111
+ handlers.onUserUpdate({
2112
+ userId: String(evt.threadId ?? data.fromUid ?? ""),
2113
+ type: String(evt.type ?? "unknown"),
2114
+ data
2115
+ });
2116
+ });
2117
+ api.listener.on("typing", (t) => {
2118
+ handlers.onTyping({
2119
+ threadId: String(t.threadId ?? ""),
2120
+ threadType: t.type === ThreadType$1.Group ? 1 /* Group */ : 0 /* User */,
2121
+ userId: String(t.data?.uid ?? ""),
2122
+ isSelf: Boolean(t.isSelf)
2123
+ });
2124
+ });
2125
+ api.listener.on("seen_messages", (list) => {
2126
+ for (const item of list) {
2127
+ const d = item.data;
2128
+ handlers.onSeen({
2129
+ threadId: String(item.threadId ?? ""),
2130
+ threadType: item.type === ThreadType$1.Group ? 1 /* Group */ : 0 /* User */,
2131
+ messageIds: Array.isArray(d?.idTo) ? d.idTo.map(String) : [],
2132
+ seenBy: Array.isArray(d?.seenUids) ? d.seenUids.map(String) : []
2133
+ });
2134
+ }
2135
+ });
2136
+ api.listener.on("undo", (u) => {
2137
+ handlers.onUndo({
2138
+ threadId: String(u.threadId ?? ""),
2139
+ threadType: u.isGroup ? 1 /* Group */ : 0 /* User */,
2140
+ senderId: String(u.data?.uidFrom ?? ""),
2141
+ messageId: String(u.data?.content?.globalMsgId ?? u.data?.msgId ?? ""),
2142
+ clientMsgId: String(u.data?.content?.cliMsgId ?? u.data?.cliMsgId ?? ""),
2143
+ isSelf: Boolean(u.isSelf)
2144
+ });
2145
+ });
2146
+ api.listener.on("connected", () => handlers.onConnected({ connected: true }));
2147
+ api.listener.on(
2148
+ "closed",
2149
+ (code, reason) => handlers.onDisconnected({ connected: false, code, reason })
2150
+ );
2151
+ api.listener.on("error", (err) => handlers.onError(err));
2152
+ api.listener.start({ retryOnClose: options?.retryOnClose ?? false });
2153
+ }
2154
+ stopListening() {
2155
+ if (!this.api?.listener) return;
2156
+ try {
2157
+ this.api.listener.stop();
2158
+ } catch {
2159
+ }
2160
+ this.listenerAttached = false;
2161
+ }
2162
+ };
2163
+
2164
+ // src/zapind.ts
2165
+ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0";
2166
+ var Zapind = class {
2167
+ account;
2168
+ users;
2169
+ contacts;
2170
+ groups;
2171
+ conversations;
2172
+ messages;
2173
+ media;
2174
+ settings;
2175
+ events;
2176
+ transport;
2177
+ sessionStore;
2178
+ executor;
2179
+ logger;
2180
+ eventBus;
2181
+ registry;
2182
+ userCache;
2183
+ groupCache;
2184
+ dedup;
2185
+ selfListen;
2186
+ defaultUserAgent;
2187
+ defaultLanguage;
2188
+ defaultQrTimeoutMs;
2189
+ modelActions;
2190
+ status = "idle" /* Idle */;
2191
+ sessionInfo = null;
2192
+ listening = false;
2193
+ constructor(options = {}) {
2194
+ const timeoutMs = options.timeoutMs ?? 15e3;
2195
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2196
+ throw new ValidationError("timeoutMs must be a positive number");
2197
+ }
2198
+ this.defaultQrTimeoutMs = options.qrTimeoutMs ?? 18e4;
2199
+ this.selfListen = options.selfListen ?? false;
2200
+ this.defaultUserAgent = options.userAgent ?? DEFAULT_USER_AGENT;
2201
+ this.defaultLanguage = options.language ?? "vi";
2202
+ this.logger = new RedactingLogger({ sink: options.logger, debug: options.debug ?? false });
2203
+ this.sessionStore = typeof options.session === "string" ? new FileSessionStore(options.session) : options.session ?? new MemorySessionStore();
2204
+ this.transport = options.transport ?? new ZcaTransport({
2205
+ selfListen: this.selfListen,
2206
+ checkUpdate: false,
2207
+ imageMetadataGetter: options.imageMetadataGetter
2208
+ });
2209
+ const retryOptions = {
2210
+ maxAttempts: options.retry?.maxAttempts ?? 3,
2211
+ baseDelayMs: options.retry?.baseDelayMs ?? 300,
2212
+ maxDelayMs: options.retry?.maxDelayMs ?? 5e3
2213
+ };
2214
+ const rateLimiter = options.rateLimit === false ? null : new RateLimiter(options.rateLimit ?? { maxRequestsPerSecond: 5, burst: 10 });
2215
+ this.executor = new PolicyExecutor(timeoutMs, retryOptions, rateLimiter, this.logger);
2216
+ this.eventBus = new EventBus(this.logger);
2217
+ this.registry = new ThreadTypeRegistry(options.cacheTtlMs ?? 5 * 6e4);
2218
+ this.userCache = new TTLCache({
2219
+ maxEntries: options.maxCacheEntries ?? 500,
2220
+ defaultTtlMs: options.cacheTtlMs ?? 6e4
2221
+ });
2222
+ this.groupCache = new TTLCache({
2223
+ maxEntries: options.maxCacheEntries ?? 250,
2224
+ defaultTtlMs: options.cacheTtlMs ?? 6e4
2225
+ });
2226
+ this.dedup = new InFlightDeduplicator();
2227
+ const actions = {
2228
+ sendMessage: (id, content, type) => this.messages.send(id, content, type),
2229
+ replyMessage: (msg, content) => this.messages.reply(msg, content),
2230
+ reactMessage: (msg, reaction) => this.messages.react(msg, reaction),
2231
+ undoMessage: (msg) => this.messages.undo(msg),
2232
+ deleteMessage: (msg, onlyMe) => this.messages.delete(msg, onlyMe),
2233
+ markSeen: (msgs) => this.messages.markSeen(msgs),
2234
+ getGroupMessages: (groupId, count) => this.conversations.getMessages(groupId, count),
2235
+ sendTyping: (id, type) => this.conversations.sendTyping({ id, threadType: type }),
2236
+ pinConversation: (id, pinned, type) => this.conversations.pin({ id, threadType: type }, pinned),
2237
+ muteConversation: (id, duration, type) => this.conversations.mute({ id, threadType: type }, duration),
2238
+ sendFriendRequest: (uid, msg) => this.contacts.sendRequest(uid, msg),
2239
+ blockUser: (uid) => this.contacts.block(uid),
2240
+ unblockUser: (uid) => this.contacts.unblock(uid),
2241
+ setFriendAlias: (uid, alias) => this.contacts.setAlias(uid, alias),
2242
+ removeFriend: (uid) => this.contacts.remove(uid),
2243
+ addGroupMembers: (gid, uids) => this.groups.addMembers(gid, uids),
2244
+ removeGroupMembers: (gid, uids) => this.groups.removeMembers(gid, uids),
2245
+ renameGroup: (gid, name) => this.groups.rename(gid, name),
2246
+ leaveGroup: (gid) => this.groups.leave(gid)
2247
+ };
2248
+ this.modelActions = actions;
2249
+ const deps = {
2250
+ transport: this.transport,
2251
+ executor: this.executor,
2252
+ registry: this.registry,
2253
+ actions,
2254
+ userCache: this.userCache,
2255
+ groupCache: this.groupCache,
2256
+ dedup: this.dedup
2257
+ };
2258
+ this.account = new AccountService(deps);
2259
+ this.users = new UsersService(deps);
2260
+ this.contacts = new ContactsService(deps);
2261
+ this.groups = new GroupsService(deps);
2262
+ this.conversations = new ConversationsService(deps);
2263
+ this.messages = new MessagesService(deps);
2264
+ this.media = new MediaService(deps, this.messages);
2265
+ this.settings = new SettingsService(deps);
2266
+ this.events = {
2267
+ on: (e, h) => this.on(e, h),
2268
+ once: (e, h) => this.once(e, h),
2269
+ off: (e, h) => this.off(e, h),
2270
+ start: (opts) => this.startListening(opts),
2271
+ stop: () => this.stopListening()
2272
+ };
2273
+ }
2274
+ /**
2275
+ * Low-level escape hatch to access the underlying `zca-js` API directly.
2276
+ * Intended for advanced 10% use cases not wrapped by high-level domain services.
2277
+ */
2278
+ get raw() {
2279
+ return this.transport.getRawApi();
2280
+ }
2281
+ getStatus() {
2282
+ return this.status;
2283
+ }
2284
+ getSession() {
2285
+ return this.sessionInfo;
2286
+ }
2287
+ isAuthenticated() {
2288
+ return this.status === "connected" /* Connected */ && this.transport.isConnected() && this.sessionInfo !== null;
2289
+ }
2290
+ /**
2291
+ * Smart authentication entry point:
2292
+ * 1. If `options.credentials` is provided -> authenticates with those credentials.
2293
+ * 2. Otherwise tries to restore and validate a saved session from `SessionStore`.
2294
+ * 3. If missing or expired -> emits `auth.required` and performs QR login.
2295
+ */
2296
+ async login(options = {}) {
2297
+ if (options.credentials) {
2298
+ return this.authenticateWithCredentials(options.credentials);
2299
+ }
2300
+ if (!options.forceQR) {
2301
+ const stored = await this.sessionStore.load();
2302
+ if (stored?.credentials?.cookie?.length) {
2303
+ try {
2304
+ return await this.authenticateWithCredentials(stored.credentials);
2305
+ } catch (err) {
2306
+ const normalized = normalizeError(err, "Saved session expired or invalid");
2307
+ this.logger.warn("Saved session restore failed, falling back to QR login", {
2308
+ code: normalized.code
2309
+ });
2310
+ this.eventBus.emit("auth.required", {
2311
+ reason: "session_expired",
2312
+ error: normalized
2313
+ });
2314
+ }
2315
+ } else {
2316
+ this.eventBus.emit("auth.required", { reason: "no_session" });
2317
+ }
2318
+ }
2319
+ return this.loginWithQR(options);
2320
+ }
2321
+ async buildAndPersistSession(credentials) {
2322
+ let accountId = "";
2323
+ let displayName = "";
2324
+ let avatarUrl = "";
2325
+ try {
2326
+ const rawProfile = await this.executor.execute(() => this.transport.fetchAccountInfo(), {
2327
+ operation: "auth.fetchProfile",
2328
+ idempotent: true
2329
+ });
2330
+ if (rawProfile) {
2331
+ const p = mapProfileData(rawProfile);
2332
+ accountId = p.id;
2333
+ displayName = p.displayName;
2334
+ avatarUrl = p.avatarUrl;
2335
+ }
2336
+ } catch {
2337
+ }
2338
+ if (!accountId) accountId = this.transport.getOwnId();
2339
+ const info = {
2340
+ accountId,
2341
+ displayName,
2342
+ avatarUrl,
2343
+ status: "connected" /* Connected */,
2344
+ authenticatedAt: /* @__PURE__ */ new Date()
2345
+ };
2346
+ this.sessionInfo = info;
2347
+ this.status = "connected" /* Connected */;
2348
+ this.registry.registerUser(accountId);
2349
+ await this.sessionStore.save({
2350
+ version: 1,
2351
+ savedAt: Date.now(),
2352
+ credentials,
2353
+ account: { accountId, displayName, avatarUrl }
2354
+ });
2355
+ return info;
2356
+ }
2357
+ async authenticateWithCredentials(credentials) {
2358
+ if (!credentials.cookie?.length || !credentials.imei) {
2359
+ throw new ValidationError("Credentials must include non-empty cookie array and imei");
2360
+ }
2361
+ this.status = "starting" /* Starting */;
2362
+ try {
2363
+ await this.executor.execute(
2364
+ () => this.transport.loginWithCredentials({
2365
+ ...credentials,
2366
+ userAgent: credentials.userAgent || this.defaultUserAgent,
2367
+ language: credentials.language || this.defaultLanguage
2368
+ }),
2369
+ { operation: "auth.loginWithCredentials", idempotent: false }
2370
+ );
2371
+ return await this.buildAndPersistSession(credentials);
2372
+ } catch (err) {
2373
+ this.status = "error" /* Error */;
2374
+ this.sessionInfo = null;
2375
+ throw normalizeError(err, "Session authentication failed");
2376
+ }
2377
+ }
2378
+ async loginWithQR(options) {
2379
+ const timeoutMs = options.timeoutMs ?? this.defaultQrTimeoutMs;
2380
+ const ac = new AbortController();
2381
+ let timedOut = false;
2382
+ const timer = setTimeout(() => {
2383
+ timedOut = true;
2384
+ ac.abort();
2385
+ }, timeoutMs);
2386
+ timer.unref?.();
2387
+ this.status = "qr_pending" /* QRPending */;
2388
+ try {
2389
+ const creds = await this.transport.loginWithQR(
2390
+ {
2391
+ userAgent: options.userAgent ?? this.defaultUserAgent,
2392
+ language: options.language ?? this.defaultLanguage,
2393
+ signal: ac.signal
2394
+ },
2395
+ {
2396
+ onQRCode: (qr) => {
2397
+ this.status = "qr_pending" /* QRPending */;
2398
+ Promise.resolve(options.onQRCode?.(qr)).catch(() => {
2399
+ });
2400
+ },
2401
+ onScanned: (info) => {
2402
+ this.status = "scanned" /* Scanned */;
2403
+ Promise.resolve(options.onScanned?.(info)).catch(() => {
2404
+ });
2405
+ },
2406
+ onExpired: () => {
2407
+ this.status = "idle" /* Idle */;
2408
+ Promise.resolve(options.onExpired?.()).catch(() => {
2409
+ });
2410
+ },
2411
+ onDeclined: () => {
2412
+ this.status = "idle" /* Idle */;
2413
+ Promise.resolve(options.onDeclined?.()).catch(() => {
2414
+ });
2415
+ }
2416
+ }
2417
+ );
2418
+ return await this.buildAndPersistSession(creds);
2419
+ } catch (err) {
2420
+ this.status = "error" /* Error */;
2421
+ this.sessionInfo = null;
2422
+ if (timedOut) {
2423
+ throw new AuthenticationError(`QR login timed out after ${timeoutMs}ms`, err);
2424
+ }
2425
+ throw normalizeError(err, "QR login failed");
2426
+ } finally {
2427
+ clearTimeout(timer);
2428
+ }
2429
+ }
2430
+ async logout(options = {}) {
2431
+ this.stopListening();
2432
+ await this.transport.disconnect();
2433
+ this.sessionInfo = null;
2434
+ this.status = "idle" /* Idle */;
2435
+ this.userCache.clear();
2436
+ this.groupCache.clear();
2437
+ this.registry.clear();
2438
+ this.dedup.clear();
2439
+ if (options.clearSession ?? true) {
2440
+ await this.sessionStore.clear();
2441
+ }
2442
+ }
2443
+ // --- Event System ---
2444
+ on(event, handler) {
2445
+ return this.eventBus.on(event, handler);
2446
+ }
2447
+ once(event, handler) {
2448
+ return this.eventBus.once(event, handler);
2449
+ }
2450
+ off(event, handler) {
2451
+ this.eventBus.off(event, handler);
2452
+ }
2453
+ startListening(options) {
2454
+ if (!this.isAuthenticated()) {
2455
+ throw new AuthenticationError("Cannot start listening before login()");
2456
+ }
2457
+ if (this.listening) return;
2458
+ this.listening = true;
2459
+ this.transport.startListening(
2460
+ {
2461
+ onMessage: (raw) => {
2462
+ const data = mapMessageData(raw);
2463
+ if (data.threadType === 1 /* Group */) this.registry.registerGroup(data.threadId);
2464
+ else this.registry.registerUser(data.threadId);
2465
+ if (data.isSelf && !this.selfListen) return;
2466
+ this.eventBus.emit("message", new Message(data, this.modelActions));
2467
+ },
2468
+ onReaction: (evt) => {
2469
+ if (evt.isSelf && !this.selfListen) return;
2470
+ this.eventBus.emit("reaction", evt);
2471
+ },
2472
+ onGroupUpdate: (evt) => {
2473
+ if (evt.groupId) {
2474
+ this.registry.registerGroup(evt.groupId);
2475
+ this.groupCache.delete(evt.groupId);
2476
+ }
2477
+ this.eventBus.emit("group.update", evt);
2478
+ },
2479
+ onUserUpdate: (evt) => {
2480
+ if (evt.userId) {
2481
+ this.registry.registerUser(evt.userId);
2482
+ this.userCache.delete(evt.userId);
2483
+ }
2484
+ this.eventBus.emit("user.update", evt);
2485
+ },
2486
+ onTyping: (evt) => {
2487
+ if (evt.isSelf && !this.selfListen) return;
2488
+ this.eventBus.emit("typing", evt);
2489
+ },
2490
+ onSeen: (evt) => this.eventBus.emit("seen", evt),
2491
+ onUndo: (evt) => {
2492
+ if (evt.isSelf && !this.selfListen) return;
2493
+ this.eventBus.emit("undo", evt);
2494
+ },
2495
+ onConnected: (evt) => this.eventBus.emit("connected", evt),
2496
+ onDisconnected: (evt) => {
2497
+ this.listening = false;
2498
+ this.eventBus.emit("disconnected", evt);
2499
+ if (evt.code === 3003 /* KickConnection */ || evt.code === 3e3 /* DuplicateConnection */) {
2500
+ const err = new SessionError(`Realtime connection closed with code ${evt.code}`, void 0, evt.code);
2501
+ this.status = "error" /* Error */;
2502
+ this.sessionInfo = null;
2503
+ this.eventBus.emit("auth.required", { reason: "session_expired", error: err });
2504
+ }
2505
+ },
2506
+ onError: (err) => this.eventBus.emit("error", normalizeError(err, "Realtime listener error"))
2507
+ },
2508
+ options
2509
+ );
2510
+ }
2511
+ stopListening() {
2512
+ if (!this.listening) return;
2513
+ this.transport.stopListening();
2514
+ this.listening = false;
2515
+ }
2516
+ };
2517
+
2518
+ export { APIError, AuthenticationError, ClientStatus, CloseReason, Contact, Conversation, DEFAULT_USER_AGENT, EncryptedFileSessionStore, FileSessionStore, Gender, Group, GroupType, MemorySessionStore, Message, NetworkError, NotFoundError, PermissionError, Profile, RateLimitError, Reaction, RedactingLogger, SessionError, TextStyle, ThreadType, Urgency, User, ValidationError, Zapind, ZapindError, noopLogger };
2519
+ //# sourceMappingURL=index.js.map
2520
+ //# sourceMappingURL=index.js.map