@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Native Curve25519 / XEdDSA (Signal-style signatures with X25519 keys).
3
+ *
4
+ * Replaces `curve25519-js` (used indirectly through `libsignal/src/curve.js`).
5
+ * - Key agreement + X25519 keygen use `node:crypto` (native OpenSSL).
6
+ * - XEdDSA sign / verify use BigInt arithmetic over the Ed25519 curve, because
7
+ * Node's Ed25519 API cannot sign with a raw (already-clamped) scalar.
8
+ *
9
+ * Signatures are byte-for-byte identical to `curve25519-js` (deterministic
10
+ * variant, i.e. without the optional 64-byte random suffix) — verified by
11
+ * test/native-deps.mjs against the original package.
12
+ */
13
+ import { createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, randomBytes } from 'node:crypto'
14
+
15
+ const P = (1n << 255n) - 19n
16
+ const L = (1n << 252n) + 27742317777372353535851937790883648493n
17
+ // d = -121665/121666 mod p
18
+ const D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n
19
+ const SQRT_M1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n
20
+ const BASE_Y = 46316835694926478169428394003475163141307993866256225615783033603165251855960n
21
+ const BASE_X = 15112221349535400772501151409588531511454012693041857206046113283949847762202n
22
+
23
+ const mod = (a, m = P) => {
24
+ const r = a % m
25
+ return r >= 0n ? r : r + m
26
+ }
27
+ const pow = (b, e, m = P) => {
28
+ let r = 1n
29
+ b = mod(b, m)
30
+ while (e > 0n) {
31
+ if (e & 1n) r = (r * b) % m
32
+ b = (b * b) % m
33
+ e >>= 1n
34
+ }
35
+ return r
36
+ }
37
+ const inv = a => pow(a, P - 2n)
38
+
39
+ /* ---- byte <-> bigint (little endian) ---- */
40
+ const bytesToNumLE = b => {
41
+ let n = 0n
42
+ for (let i = b.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(b[i])
43
+ return n
44
+ }
45
+ const numToBytesLE = (n, len) => {
46
+ const out = Buffer.alloc(len)
47
+ for (let i = 0; i < len; i++) {
48
+ out[i] = Number(n & 0xffn)
49
+ n >>= 8n
50
+ }
51
+ return out
52
+ }
53
+
54
+ /* ---- Edwards curve, extended coordinates (X, Y, Z, T) ---- */
55
+ const ZERO = [0n, 1n, 1n, 0n]
56
+ const BASE = [BASE_X, BASE_Y, 1n, mod(BASE_X * BASE_Y)]
57
+
58
+ const pointAdd = (p, q) => {
59
+ const [X1, Y1, Z1, T1] = p
60
+ const [X2, Y2, Z2, T2] = q
61
+ const A = mod((Y1 - X1) * (Y2 - X2))
62
+ const B = mod((Y1 + X1) * (Y2 + X2))
63
+ const C = mod(2n * D * T1 * T2)
64
+ const Dd = mod(2n * Z1 * Z2)
65
+ const E = B - A
66
+ const F = Dd - C
67
+ const G = Dd + C
68
+ const H = B + A
69
+ return [mod(E * F), mod(G * H), mod(F * G), mod(E * H)]
70
+ }
71
+
72
+ const scalarMult = (point, scalar) => {
73
+ let r = ZERO
74
+ let q = point
75
+ while (scalar > 0n) {
76
+ if (scalar & 1n) r = pointAdd(r, q)
77
+ q = pointAdd(q, q)
78
+ scalar >>= 1n
79
+ }
80
+ return r
81
+ }
82
+
83
+ const encodePoint = p => {
84
+ const zi = inv(p[2])
85
+ const x = mod(p[0] * zi)
86
+ const y = mod(p[1] * zi)
87
+ const out = numToBytesLE(y, 32)
88
+ if (x & 1n) out[31] |= 0x80
89
+ return out
90
+ }
91
+
92
+ /** Decode an Edwards point; returns null if it is not on the curve. */
93
+ const decodePoint = bytes => {
94
+ const b = Buffer.from(bytes)
95
+ const sign = (b[31] & 0x80) >> 7
96
+ b[31] &= 0x7f
97
+ const y = bytesToNumLE(b)
98
+ if (y >= P) return null
99
+ const y2 = mod(y * y)
100
+ const u = mod(y2 - 1n)
101
+ const v = mod(D * y2 + 1n)
102
+ // x = sqrt(u/v)
103
+ const v3 = mod(v * v * v)
104
+ const v7 = mod(v3 * v3 * v)
105
+ let x = mod(u * v3 * pow(mod(u * v7), (P - 5n) / 8n))
106
+ const vx2 = mod(v * x * x)
107
+ if (vx2 !== mod(u)) {
108
+ if (vx2 !== mod(-u)) return null
109
+ x = mod(x * SQRT_M1)
110
+ }
111
+ if (Number(x & 1n) !== sign) x = mod(-x)
112
+ return [x, y, 1n, mod(x * y)]
113
+ }
114
+
115
+ const sha512 = (...parts) => {
116
+ const h = createHash('sha512')
117
+ for (const p of parts) h.update(p)
118
+ return h.digest()
119
+ }
120
+
121
+ const clamp = key => {
122
+ const k = Buffer.from(key)
123
+ k[0] &= 248
124
+ k[31] &= 127
125
+ k[31] |= 64
126
+ return k
127
+ }
128
+
129
+ /* ---- DER prefixes for raw X25519 keys (Node crypto) ---- */
130
+ const PUB_DER = Buffer.from('302a300506032b656e032100', 'hex')
131
+ const PRIV_DER = Buffer.from('302e020100300506032b656e04220420', 'hex')
132
+
133
+ /** X25519 shared secret. `pub` = 32 raw bytes, `priv` = 32 raw bytes. */
134
+ export const sharedKey = (priv, pub) =>
135
+ diffieHellman({
136
+ privateKey: createPrivateKey({ key: Buffer.concat([PRIV_DER, priv]), format: 'der', type: 'pkcs8' }),
137
+ publicKey: createPublicKey({ key: Buffer.concat([PUB_DER, pub]), format: 'der', type: 'spki' })
138
+ })
139
+
140
+ /** Random X25519 key pair (32-byte raw keys). */
141
+ export const randomX25519 = () => {
142
+ const { publicKey, privateKey } = generateKeyPairSync('x25519', {
143
+ publicKeyEncoding: { format: 'der', type: 'spki' },
144
+ privateKeyEncoding: { format: 'der', type: 'pkcs8' }
145
+ })
146
+ return {
147
+ pub: publicKey.subarray(PUB_DER.length, PUB_DER.length + 32),
148
+ priv: privateKey.subarray(PRIV_DER.length, PRIV_DER.length + 32)
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Public key for a given (possibly unclamped) 32-byte private key, exactly like
154
+ * curve25519-js `generateKeyPair(seed).public`: X25519(base point) with the
155
+ * top bit cleared.
156
+ */
157
+ export const publicFromPrivate = seed => {
158
+ if (seed.length !== 32) throw new Error('wrong seed length')
159
+ const priv = Buffer.from(seed)
160
+ // X25519 clamps internally; Node's diffieHellman against the base point (u=9) gives the public key
161
+ const base = Buffer.alloc(32)
162
+ base[0] = 9
163
+ const pub = Buffer.from(sharedKey(priv, base))
164
+ pub[31] &= 0x7f
165
+ return pub
166
+ }
167
+
168
+ /** Curve25519 (Montgomery u) -> Ed25519 (Edwards y): y = (u - 1) / (u + 1) */
169
+ const montToEdY = pk => {
170
+ const b = Buffer.from(pk)
171
+ b[31] &= 0x7f // curve25519-js unpack25519 ignores the top bit
172
+ const u = mod(bytesToNumLE(b))
173
+ const y = mod((u - 1n) * inv(mod(u + 1n)))
174
+ return numToBytesLE(y, 32)
175
+ }
176
+
177
+ /**
178
+ * XEdDSA sign (deterministic variant). Equivalent to curve25519-js `sign(sk, msg)`.
179
+ * @returns {Buffer} 64-byte signature
180
+ */
181
+ export const sign = (secretKey, msg) => {
182
+ if (secretKey.length !== 32) throw new Error('wrong secret key length')
183
+ const a = clamp(secretKey)
184
+ const aNum = bytesToNumLE(a)
185
+ const A = encodePoint(scalarMult(BASE, aNum))
186
+ const signBit = A[31] & 0x80
187
+ // r = H(a || m) mod L (curve25519-js hashes the clamped secret directly)
188
+ const r = mod(bytesToNumLE(sha512(a, msg)), L)
189
+ const R = encodePoint(scalarMult(BASE, r))
190
+ const Acompressed = Buffer.from(A)
191
+ // h = H(R || A || m) mod L — A here is the packed public key WITH its sign bit
192
+ const h = mod(bytesToNumLE(sha512(R, Acompressed, msg)), L)
193
+ const S = mod(r + h * aNum, L)
194
+ const sig = Buffer.concat([R, numToBytesLE(S, 32)])
195
+ sig[63] |= signBit
196
+ return sig
197
+ }
198
+
199
+ /**
200
+ * XEdDSA verify. Equivalent to curve25519-js `verify(pk, msg, sig)`.
201
+ * @returns {boolean}
202
+ */
203
+ export const verify = (publicKey, msg, signature) => {
204
+ if (signature.length !== 64) throw new Error('wrong signature length')
205
+ if (publicKey.length !== 32) throw new Error('wrong public key length')
206
+ const sig = Buffer.from(signature)
207
+ const edpk = montToEdY(publicKey)
208
+ edpk[31] |= sig[63] & 0x80
209
+ sig[63] &= 0x7f
210
+ const A = decodePoint(edpk)
211
+ if (!A) return false
212
+ const R = sig.subarray(0, 32)
213
+ const S = bytesToNumLE(sig.subarray(32))
214
+ const h = mod(bytesToNumLE(sha512(R, edpk, msg)), L)
215
+ // check: S*B == R + h*A <=> S*B - h*A == R (compare encodings, like the reference)
216
+ const negA = [mod(-A[0]), A[1], A[2], mod(-A[3])]
217
+ const check = pointAdd(scalarMult(negA, h), scalarMult(BASE, S))
218
+ return Buffer.compare(encodePoint(check), R) === 0
219
+ }
220
+
221
+ export { randomBytes }
@@ -0,0 +1,320 @@
1
+ /**
2
+ * Native link preview (replaces `link-preview-js`). `fetch` + a small, tolerant HTML head scanner.
3
+ *
4
+ * Result shape follows link-preview-js:
5
+ * HTML page : { url, title, siteName, description, mediaType, contentType, images[], videos[], favicons[] }
6
+ * image : { url, mediaType: 'image', contentType, favicons[] }
7
+ * audio/video/application: { url, mediaType, contentType, favicons[] }
8
+ * Throws Error('... did not receive a valid a url or text') when the text contains no http(s) URL (same message the
9
+ * package used; getUrlInfo relies on it).
10
+ *
11
+ * The HTML scanner reads <meta>, <title>, <link>, <base> and <img> with a state machine that follows the WHATWG HTML
12
+ * tokenizer (quoting, `=` and `/` corner cases, first duplicate attribute wins, unterminated tags dropped, comments,
13
+ * script/style/textarea/title/noscript content treated as text). Named entities: ~100 common ones plus all numeric ones
14
+ * (parse5 knows 2231 named entities; an unknown one is left as written). Verified against cheerio/parse5 in
15
+ * test/native-link-preview.mjs.
16
+ */
17
+
18
+ const REGEX_VALID_URL = /^(?:https?:\/\/)[^\s]+$/i
19
+ const DEFAULT_UA = 'Mozilla/5.0 (compatible; baileys-lite link preview)'
20
+ const MAX_BYTES = 1024 * 1024
21
+
22
+ /* ------------------------------ entities ------------------------------ */
23
+
24
+ const NAMED = {
25
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', copy: '©', reg: '®', trade: '™', hellip: '…', mdash: '—', ndash: '–',
26
+ lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”', laquo: '«', raquo: '»', bull: '•', middot: '·', euro: '€', pound: '£', yen: '¥', cent: '¢',
27
+ sect: '§', deg: '°', plusmn: '±', times: '×', divide: '÷', para: '¶', iexcl: '¡', iquest: '¿', shy: '\u00ad', larr: '←', rarr: '→', uarr: '↑',
28
+ darr: '↓', hearts: '♥', check: '✓', star: '☆', infin: '∞', ne: '≠', le: '≤', ge: '≥', frac12: '½', frac14: '¼', frac34: '¾', sup2: '²', sup3: '³',
29
+ micro: 'µ', agrave: 'à', aacute: 'á', acirc: 'â', atilde: 'ã', auml: 'ä', aring: 'å', aelig: 'æ', ccedil: 'ç', egrave: 'è', eacute: 'é', ecirc: 'ê',
30
+ euml: 'ë', igrave: 'ì', iacute: 'í', icirc: 'î', iuml: 'ï', ntilde: 'ñ', ograve: 'ò', oacute: 'ó', ocirc: 'ô', otilde: 'õ', ouml: 'ö', oslash: 'ø',
31
+ ugrave: 'ù', uacute: 'ú', ucirc: 'û', uuml: 'ü', yacute: 'ý', yuml: 'ÿ', szlig: 'ß', Agrave: 'À', Aacute: 'Á', Acirc: 'Â', Atilde: 'Ã', Auml: 'Ä',
32
+ Aring: 'Å', AElig: 'Æ', Ccedil: 'Ç', Egrave: 'È', Eacute: 'É', Ecirc: 'Ê', Euml: 'Ë', Igrave: 'Ì', Iacute: 'Í', Icirc: 'Î', Iuml: 'Ï', Ntilde: 'Ñ',
33
+ Ograve: 'Ò', Oacute: 'Ó', Ocirc: 'Ô', Otilde: 'Õ', Ouml: 'Ö', Oslash: 'Ø', Ugrave: 'Ù', Uacute: 'Ú', Ucirc: 'Û', Uuml: 'Ü', Yacute: 'Ý'
34
+ }
35
+
36
+ // Legacy entities the HTML spec also decodes WITHOUT a trailing semicolon (text context only; see decodeEntities)
37
+ const LEGACY = /^(amp|lt|gt|quot|nbsp|copy|reg|deg|plusmn|times|divide|para|sect|shy|micro|middot|laquo|raquo|iexcl|iquest|cent|pound|yen)$/
38
+
39
+ /**
40
+ * Named entities follow the HTML rules: `&name;` decodes when known; otherwise the LONGEST legacy prefix that is valid
41
+ * without a semicolon decodes (`&amp8` -> `&8`). Inside an attribute value a semicolon-less match is NOT decoded when the
42
+ * next character is `=` or alphanumeric (so `?a=1&copy=2` in a URL survives).
43
+ */
44
+ const decodeEntities = (s, inAttr = false) => {
45
+ if (!s.includes('&')) return s
46
+ return s.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*))(;?)/g, (m, dec, hex, name, semi, offset) => {
47
+ if (name) {
48
+ if (semi && Object.prototype.hasOwnProperty.call(NAMED, name)) return NAMED[name]
49
+ for (let len = name.length; len >= 2; len--) {
50
+ const prefix = name.slice(0, len)
51
+ if (!LEGACY.test(prefix)) continue
52
+ const rest = name.slice(len) + semi
53
+ const next = rest[0] ?? s[offset + m.length]
54
+ if (inAttr && next !== undefined && /[=A-Za-z0-9]/.test(next)) return m
55
+ return NAMED[prefix] + rest
56
+ }
57
+ return m
58
+ }
59
+ const cp = dec !== undefined ? parseInt(dec, 10) : parseInt(hex, 16)
60
+ if (!cp || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return '\ufffd'
61
+ return String.fromCodePoint(cp)
62
+ })
63
+ }
64
+
65
+ /* ------------------------------ HTML scanning ------------------------------ */
66
+
67
+ // Elements whose content is not markup (tokenizer states RCDATA / RAWTEXT / script data). `title` is captured, the rest skipped.
68
+ const TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript'])
69
+ const WS = new Set([' ', '\t', '\n', '\f', '\r'])
70
+ const isAlpha = c => c !== undefined && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
71
+
72
+ /**
73
+ * Follows the WHATWG HTML tokenizer for start tags: attribute names/values, quoting, `=` and `/` corner cases,
74
+ * duplicate attributes (first wins), unterminated tags (dropped), comments, bogus comments (`<!...>`, `<?...>`, CDATA in
75
+ * HTML content) and text-only elements. Returns { metas, links, imgs, title, base } — attribute maps with lower-case
76
+ * names and entity-decoded values.
77
+ */
78
+ export function scanHtml(html) {
79
+ const out = { metas: [], links: [], imgs: [], title: undefined, base: undefined }
80
+ const n = html.length
81
+ let i = 0
82
+ while (i < n) {
83
+ const lt = html.indexOf('<', i)
84
+ if (lt === -1) break
85
+ i = lt + 1
86
+ const c = html[i]
87
+ if (c === '!') {
88
+ // comment, doctype or bogus comment
89
+ if (html.startsWith('--', i + 1)) {
90
+ if (html[i + 3] === '>') i += 4 // <!-->
91
+ else if (html.startsWith('->', i + 3)) i += 5 // <!--->
92
+ else {
93
+ const end = html.indexOf('-->', i + 3)
94
+ const alt = html.indexOf('--!>', i + 3)
95
+ const e = end === -1 ? alt : alt === -1 ? end : Math.min(end, alt)
96
+ if (e === -1) break // unterminated comment swallows the rest
97
+ i = e + (html.startsWith('--!>', e) ? 4 : 3)
98
+ }
99
+ } else {
100
+ const gt = html.indexOf('>', i)
101
+ if (gt === -1) break
102
+ i = gt + 1
103
+ }
104
+ continue
105
+ }
106
+ if (c === '?') {
107
+ const gt = html.indexOf('>', i)
108
+ if (gt === -1) break
109
+ i = gt + 1
110
+ continue
111
+ }
112
+ if (c === '/') {
113
+ // end tag: skipped (attributes are irrelevant); "</>" and "</ x>" follow the spec's bogus-comment rules
114
+ const d = html[i + 1]
115
+ if (d === '>') {
116
+ i += 2
117
+ continue
118
+ }
119
+ const gt = html.indexOf('>', i)
120
+ if (gt === -1) break
121
+ i = gt + 1
122
+ continue
123
+ }
124
+ if (!isAlpha(c)) continue // a literal '<' in text
125
+ // ---- start tag ----
126
+ let j = i
127
+ while (j < n && !WS.has(html[j]) && html[j] !== '/' && html[j] !== '>') j++
128
+ let name = html.slice(i, j).toLowerCase()
129
+ if (name === 'image') name = 'img' // the tree builder renames <image> to <img>
130
+ const attrs = {}
131
+ let closed = false
132
+ // attribute loop (before attribute name state)
133
+ for (;;) {
134
+ while (j < n && (WS.has(html[j]) || html[j] === '/')) j++ // '/' not followed by '>' is ignored
135
+ if (j >= n) break // EOF inside the tag: the tag is dropped
136
+ if (html[j] === '>') {
137
+ j++
138
+ closed = true
139
+ break
140
+ }
141
+ // attribute name: a leading '=' becomes part of the name
142
+ let k = j + 1
143
+ while (k < n && !WS.has(html[k]) && html[k] !== '/' && html[k] !== '>' && html[k] !== '=') k++
144
+ const aname = html.slice(j, k).toLowerCase().replace(/\0/g, '\ufffd')
145
+ j = k
146
+ while (j < n && WS.has(html[j])) j++
147
+ let value = ''
148
+ if (html[j] === '=') {
149
+ j++
150
+ while (j < n && WS.has(html[j])) j++
151
+ const q = html[j]
152
+ if (q === '"' || q === "'") {
153
+ const e = html.indexOf(q, j + 1)
154
+ if (e === -1) {
155
+ j = n // EOF inside a quoted value: the tag is dropped
156
+ break
157
+ }
158
+ value = html.slice(j + 1, e)
159
+ j = e + 1
160
+ } else {
161
+ let e = j
162
+ while (e < n && !WS.has(html[e]) && html[e] !== '>') e++
163
+ value = html.slice(j, e)
164
+ j = e
165
+ }
166
+ value = decodeEntities(value, true)
167
+ }
168
+ if (!(aname in attrs)) attrs[aname] = value // duplicate attributes: the first one wins
169
+ }
170
+ if (!closed) break
171
+ i = j
172
+ if (name === 'meta') out.metas.push(attrs)
173
+ else if (name === 'link') out.links.push(attrs)
174
+ else if (name === 'img') out.imgs.push(attrs)
175
+ else if (name === 'base') {
176
+ if (out.base === undefined && attrs.href) out.base = attrs.href
177
+ }
178
+ if (TEXT_ELEMENTS.has(name)) {
179
+ // content up to the matching end tag is text, not markup
180
+ const re = new RegExp('</' + name + '(?=[\\s/>])', 'i')
181
+ const m = re.exec(html.slice(i))
182
+ const end = m ? i + m.index : n
183
+ if (name === 'title' && out.title === undefined) out.title = decodeEntities(html.slice(i, end))
184
+ i = end
185
+ }
186
+ }
187
+ return out
188
+ }
189
+
190
+ const resolveUrl = (href, base) => {
191
+ try {
192
+ return new URL(href.trim(), base).href
193
+ } catch {
194
+ return undefined
195
+ }
196
+ }
197
+
198
+ /* ------------------------------ fetching ------------------------------ */
199
+
200
+ const charsetFrom = (contentType, head) => {
201
+ const h = /charset\s*=\s*["']?([\w.:-]+)/i.exec(contentType || '')
202
+ if (h) return h[1]
203
+ const m = /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(head) || /<meta[^>]+content\s*=\s*["'][^"']*charset=([\w.:-]+)/i.exec(head)
204
+ return m ? m[1] : 'utf-8'
205
+ }
206
+
207
+ const decodeBody = (bytes, contentType) => {
208
+ const head = Buffer.from(bytes.subarray(0, 2048)).toString('latin1')
209
+ const charset = charsetFrom(contentType, head)
210
+ try {
211
+ return new TextDecoder(charset).decode(bytes)
212
+ } catch {
213
+ return new TextDecoder('utf-8').decode(bytes)
214
+ }
215
+ }
216
+
217
+ /** Reads at most `max` bytes; stops early once `</head>` has been seen (everything we need is there). */
218
+ const readBody = async (res, max) => {
219
+ const reader = res.body?.getReader()
220
+ if (!reader) return new Uint8Array(await res.arrayBuffer()).subarray(0, max)
221
+ const chunks = []
222
+ let total = 0
223
+ let tail = ''
224
+ while (total < max) {
225
+ const { done, value } = await reader.read()
226
+ if (done) break
227
+ chunks.push(value)
228
+ total += value.length
229
+ tail = (tail + Buffer.from(value).toString('latin1')).slice(-16)
230
+ if (/<\/head\s*>/i.test(tail)) break
231
+ }
232
+ reader.cancel().catch(() => {})
233
+ const buf = new Uint8Array(Math.min(total, max))
234
+ let o = 0
235
+ for (const c of chunks) {
236
+ const take = Math.min(c.length, buf.length - o)
237
+ buf.set(c.subarray(0, take), o)
238
+ o += take
239
+ }
240
+ return buf
241
+ }
242
+
243
+ /**
244
+ * @param {string} text a URL, or text containing one
245
+ * @param {{ timeout?: number, headers?: Record<string,string>, followRedirects?: 'follow'|'manual'|'error',
246
+ * handleRedirects?: (baseUrl: string, forwardedUrl: string) => boolean, maxBytes?: number }} [options]
247
+ */
248
+ export async function getLinkPreview(text, options = {}) {
249
+ if (typeof text !== 'string') throw new Error('link-preview did not receive a valid a url or text')
250
+ const detected = text.replace(/\n/g, ' ').split(' ').find(token => REGEX_VALID_URL.test(token))
251
+ if (!detected) throw new Error('link-preview did not receive a valid a url or text')
252
+ const { timeout = 3000, followRedirects = 'follow', handleRedirects, maxBytes = MAX_BYTES } = options
253
+ const headers = { 'user-agent': DEFAULT_UA, accept: 'text/html,application/xhtml+xml,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.9', ...(options.headers || {}) }
254
+
255
+ let url = detected
256
+ let res
257
+ for (let hops = 0; ; hops++) {
258
+ res = await fetch(url, { headers, redirect: followRedirects === 'manual' ? 'manual' : followRedirects, signal: AbortSignal.timeout(timeout) })
259
+ if (followRedirects === 'manual' && res.status >= 300 && res.status < 400 && res.headers.get('location')) {
260
+ const forwarded = new URL(res.headers.get('location'), url).href
261
+ res.body?.cancel().catch(() => {})
262
+ if (hops >= 10 || !handleRedirects || !handleRedirects(url, forwarded)) throw new Error('link-preview could not handle redirect')
263
+ url = forwarded
264
+ continue
265
+ }
266
+ break
267
+ }
268
+ const finalUrl = res.url || url
269
+ const contentType = (res.headers.get('content-type') || '').toLowerCase()
270
+ const type = contentType.split(';')[0].trim()
271
+ const origin = (() => {
272
+ try {
273
+ return new URL(finalUrl).origin
274
+ } catch {
275
+ return ''
276
+ }
277
+ })()
278
+ const defaultFavicons = origin ? [origin + '/favicon.ico'] : []
279
+
280
+ if (type.startsWith('image/')) {
281
+ res.body?.cancel().catch(() => {})
282
+ return { url: finalUrl, mediaType: 'image', contentType: type, favicons: defaultFavicons }
283
+ }
284
+ if (type.startsWith('audio/') || type.startsWith('video/') || type.startsWith('application/') && !type.includes('html') && !type.includes('xml')) {
285
+ res.body?.cancel().catch(() => {})
286
+ return { url: finalUrl, mediaType: type.split('/')[0], contentType: type, favicons: defaultFavicons }
287
+ }
288
+ if (type && !type.includes('html') && !type.includes('xml') && !type.startsWith('text/')) throw new Error(`link-preview: unsupported content type ${type}`)
289
+
290
+ const html = decodeBody(await readBody(res, maxBytes), contentType)
291
+ const doc = scanHtml(html)
292
+ const base = doc.base ? (resolveUrl(doc.base, finalUrl) ?? finalUrl) : finalUrl
293
+ const meta = (...keys) => {
294
+ for (const k of keys) {
295
+ const hit = doc.metas.find(a => (a.property ?? a.name ?? '').toLowerCase() === k && a.content !== undefined && a.content.trim() !== '')
296
+ if (hit) return hit.content.trim()
297
+ }
298
+ }
299
+ const metaAll = (...keys) => doc.metas.filter(a => keys.includes((a.property ?? a.name ?? '').toLowerCase()) && a.content?.trim()).map(a => a.content.trim())
300
+ const title = meta('og:title', 'twitter:title') ?? doc.title?.trim() ?? undefined
301
+ const description = meta('og:description', 'twitter:description', 'description')
302
+ const siteName = meta('og:site_name')
303
+ const mediaType = meta('og:type') ?? 'website'
304
+
305
+ const images = []
306
+ const pushUrl = (list, href) => {
307
+ if (!href || /^data:/i.test(href.trim())) return
308
+ const u = resolveUrl(href, base)
309
+ if (u && !list.includes(u)) list.push(u)
310
+ }
311
+ for (const v of metaAll('og:image', 'og:image:url', 'og:image:secure_url', 'twitter:image', 'twitter:image:src')) pushUrl(images, v)
312
+ if (!images.length) for (const img of doc.imgs.slice(0, 20)) pushUrl(images, img.src)
313
+ const videos = []
314
+ for (const v of metaAll('og:video', 'og:video:url', 'og:video:secure_url')) pushUrl(videos, v)
315
+ const favicons = []
316
+ for (const l of doc.links) if (/(^|\s)(shortcut\s+)?icon(\s|$)|apple-touch-icon/i.test(l.rel ?? '') && l.href) pushUrl(favicons, l.href)
317
+ if (!favicons.length) favicons.push(...defaultFavicons)
318
+
319
+ return { url: finalUrl, title, siteName, description, mediaType, contentType: type || 'text/html', images, videos, favicons }
320
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Minimal drop-in logger replacing `pino`.
3
+ * Supports the subset of the pino API Baileys actually uses:
4
+ * logger.info/warn/error/debug/trace/fatal(obj?, msg?)
5
+ * logger.child(bindings) -> returns a new logger merging bindings into every line
6
+ * logger.level (get/set)
7
+ *
8
+ * Output: newline-delimited JSON on stdout/stderr, matching pino's default
9
+ * shape closely enough for log processors that expect { level, time, msg }.
10
+ */
11
+
12
+ const LEVELS = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60 }
13
+
14
+ function serializeError(err) {
15
+ if (!(err instanceof Error)) return err
16
+ return { type: err.name, message: err.message, stack: err.stack, ...err }
17
+ }
18
+
19
+ function createLogger(bindings = {}, level = 'info') {
20
+ const state = { level }
21
+
22
+ function write(levelName, args) {
23
+ if (LEVELS[levelName] < LEVELS[state.level]) return
24
+
25
+ let obj = {}
26
+ let msg = ''
27
+ if (args.length && typeof args[0] === 'object' && args[0] !== null) {
28
+ obj = args[0]
29
+ msg = args[1] ?? ''
30
+ } else {
31
+ msg = args[0] ?? ''
32
+ }
33
+ if (obj.err) obj = { ...obj, err: serializeError(obj.err) }
34
+
35
+ const line = {
36
+ level: LEVELS[levelName],
37
+ time: Date.now(),
38
+ ...bindings,
39
+ ...obj,
40
+ msg
41
+ }
42
+
43
+ const out = levelName === 'error' || levelName === 'fatal' ? process.stderr : process.stdout
44
+ out.write(JSON.stringify(line) + '\n')
45
+ }
46
+
47
+ const logger = {
48
+ get level() {
49
+ return state.level
50
+ },
51
+ set level(v) {
52
+ state.level = v
53
+ },
54
+ trace: (...a) => write('trace', a),
55
+ debug: (...a) => write('debug', a),
56
+ info: (...a) => write('info', a),
57
+ warn: (...a) => write('warn', a),
58
+ error: (...a) => write('error', a),
59
+ fatal: (...a) => write('fatal', a),
60
+ child(childBindings = {}) {
61
+ return createLogger({ ...bindings, ...childBindings }, state.level)
62
+ }
63
+ }
64
+
65
+ return logger
66
+ }
67
+
68
+ export default createLogger()
69
+ export { createLogger }