@hiroosy/baileys-lite 0.0.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,12 +1,7 @@
1
- /**
2
- * Message composition utilities. Combines what used to be messages.js and
3
- * rich-message-utils.js. LANGUAGE_KEYWORDS (syntax-highlighting keyword lists)
4
- * moved here from WABinary/constants.js, where it had been misplaced — it's
5
- * message-composition data, not WA binary-protocol data.
6
- */
7
1
  import { getRandomValues, randomBytes, randomUUID } from 'node:crypto'
8
2
  import { promises as fs } from 'node:fs'
9
3
  import { proto } from '../../WAProto/index.js'
4
+ import { AIRichBuilder, aiRichBuilderFromSpec } from '../foundation/ai-rich.js'
10
5
  import { Boom } from '../foundation/boom.js'
11
6
  import { zip } from '../foundation/zip.js'
12
7
  import {
@@ -60,10 +55,6 @@ const MessageTypeProto = {
60
55
  document: WAProto.Message.DocumentMessage
61
56
  }
62
57
 
63
- /* ------------------------------------------------------------------ */
64
- /* Code syntax-highlighting keyword lists (for richResponseMessage) */
65
- /* ------------------------------------------------------------------ */
66
-
67
58
  const CPP_KEYWORDS = new Set([
68
59
  'alignas','alignof','and','and_eq','asm','auto','bitand','bitor','bool','break','case',
69
60
  'catch','char','class','compl','concept','const','consteval','constexpr','constinit',
@@ -249,6 +240,8 @@ export const tokenizeCode = (code, language = 'javascript') => {
249
240
  return blocks
250
241
  }
251
242
 
243
+ const CODE_HIGHLIGHT_NAME = ['DEFAULT', 'KEYWORD', 'METHOD', 'STR', 'NUMBER', 'COMMENT']
244
+
252
245
  export const toUnified = (submessages, uuid) => ({
253
246
  response_id: uuid || randomUUID(),
254
247
  sections: submessages.map(submessage => {
@@ -259,7 +252,7 @@ export const toUnified = (submessages, uuid) => ({
259
252
  view_model: {
260
253
  primitive: {
261
254
  language: codeMetadata.codeLanguage,
262
- code_blocks: codeMetadata.codeBlocks.map(block => ({ content: block.codeContent, type: CodeHighlightType[block.highlightType] })),
255
+ code_blocks: codeMetadata.codeBlocks.map(block => ({ content: block.codeContent, type: CODE_HIGHLIGHT_NAME[block.highlightType] ?? 'DEFAULT' })),
263
256
  __typename: 'GenAICodeUXPrimitive'
264
257
  },
265
258
  __typename: 'GenAISingleLayoutViewModel'
@@ -423,11 +416,6 @@ export const wrapToBotForwardedMessage = richResponseMessage => ({
423
416
  botForwardedMessage: { message: { richResponseMessage } }
424
417
  })
425
418
 
426
- /* ------------------------------------------------------------------ */
427
- /* Message content composition */
428
- /* ------------------------------------------------------------------ */
429
-
430
- /** Uses a regex to test whether the string contains a URL, and returns the URL if it does. */
431
419
  export const extractUrlFromText = text => text.match(URL_REGEX)?.[0]
432
420
 
433
421
  export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
@@ -602,10 +590,6 @@ const prepareProductMessage = async (message, options) => {
602
590
  return content
603
591
  }
604
592
 
605
- /**
606
- * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1
607
- * (https://github.com/jlucaso1), based on https://github.com/WhiskeySockets/Baileys/pull/1561
608
- */
609
593
  const prepareStickerPackMessage = async (message, options) => {
610
594
  const { cover, stickers = [], name = '📦 Sticker Pack', publisher = '', description = '' } = message
611
595
  if (stickers.length > 60) throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 })
@@ -757,6 +741,146 @@ const prepareStickerPackMessage = async (message, options) => {
757
741
  return WAProto.Message.StickerPackMessage.fromObject(obj)
758
742
  }
759
743
 
744
+ // Text inside a bloksWidget uses a system font without color-emoji glyphs, so icons
745
+ // default to plain ASCII. `style: 'symbol'` uses simple unicode symbols instead.
746
+ const WIDGET_ICON_ASCII = {
747
+ accountCircle: '[user]', add: '[+]', arrowBack: '[<]', arrowForward: '[>]', attachFile: '[attach]',
748
+ calendarToday: '[date]', call: '[call]', camera: '[camera]', check: '[ok]', close: '[x]', delete: '[delete]',
749
+ download: '[download]', edit: '[edit]', event: '[event]', error: '[!]', fastForward: '[>>]', favorite: '[fav]',
750
+ favoriteOff: '[fav]', folder: '[folder]', help: '[?]', home: '[home]', info: '[i]', locationOn: '[location]',
751
+ lock: '[lock]', lockOpen: '[unlock]', mail: '[mail]', menu: '[menu]', moreVert: '[more]', moreHoriz: '[more]',
752
+ notificationsOff: '[muted]', notifications: '[alert]', pause: '[pause]', payment: '[pay]', person: '[user]',
753
+ phone: '[phone]', photo: '[photo]', play: '[play]', print: '[print]', refresh: '[refresh]', rewind: '[<<]',
754
+ search: '[search]', send: '[send]', settings: '[settings]', share: '[share]', shoppingCart: '[cart]',
755
+ skipNext: '[next]', skipPrevious: '[prev]', star: '[star]', starHalf: '[star]', starOff: '[star]',
756
+ stop: '[stop]', upload: '[upload]', visibility: '[show]', visibilityOff: '[hide]', volumeDown: '[vol-]',
757
+ volumeMute: '[mute]', volumeOff: '[mute]', volumeUp: '[vol+]', warning: '[!]'
758
+ }
759
+ const WIDGET_ICON_SYMBOL = {
760
+ accountCircle: '☺', add: '+', arrowBack: '<', arrowForward: '>', attachFile: '@',
761
+ calendarToday: '#', call: '☎', camera: '◉', check: '✓', close: '✕', delete: '✕',
762
+ download: '↓', edit: '✎', event: '#', error: '!', fastForward: '»', favorite: '♥',
763
+ favoriteOff: '♡', folder: '▤', help: '?', home: '⌂', info: 'i', locationOn: '⚑',
764
+ lock: '⚿', lockOpen: '⚿', mail: '✉', menu: '≡', moreVert: '⋮', moreHoriz: '…',
765
+ notificationsOff: '⌇', notifications: '☏', pause: '‖', payment: '$', person: '☺',
766
+ phone: '☎', photo: '▨', play: '▶', print: '⎙', refresh: '↻', rewind: '«',
767
+ search: '⚲', send: '➤', settings: '⚙', share: '⤴', shoppingCart: '⛁',
768
+ skipNext: '»', skipPrevious: '«', star: '★', starHalf: '★', starOff: '☆',
769
+ stop: '■', upload: '↑', visibility: '◉', visibilityOff: '◎', volumeDown: '◑',
770
+ volumeMute: '◌', volumeOff: '◌', volumeUp: '◕', warning: '!'
771
+ }
772
+
773
+ const buildWidgetItem = (item = {}, id, components) => {
774
+ if (item.image) {
775
+ components.push({ id, component: 'Image', url: item.image, variant: item.variant || 'header', fit: item.fit || 'cover', ...(item.description ? { description: String(item.description) } : {}) })
776
+ } else if (item.text) {
777
+ components.push({ id, component: 'Text', text: String(item.text), variant: item.variant || 'body' })
778
+ } else if (item.icon || item.name) {
779
+ const iconName = item.icon || item.name
780
+ if (item.native) {
781
+ components.push({ id, component: 'Icon', name: iconName })
782
+ } else {
783
+ const map = item.style === 'symbol' ? WIDGET_ICON_SYMBOL : WIDGET_ICON_ASCII
784
+ components.push({ id, component: 'Text', text: map[iconName] || (item.style === 'symbol' ? '•' : `[${iconName}]`), variant: item.variant || 'body' })
785
+ }
786
+ } else if (item.video) {
787
+ components.push({ id, component: 'Video', url: item.video })
788
+ } else if (item.audio) {
789
+ components.push({ id, component: 'AudioPlayer', url: item.audio, ...(item.description ? { description: String(item.description) } : {}) })
790
+ } else if (item.divider) {
791
+ components.push({ id, component: 'Divider', axis: typeof item.divider === 'string' ? item.divider : 'horizontal' })
792
+ } else if (item.button) {
793
+ const textId = `${id}_text`
794
+ components.push(
795
+ { id, component: 'Button', child: textId, variant: item.variant || 'primary', action: { call: 'openUrl', args: { url: String(item.url || '') } } },
796
+ { id: textId, component: 'Text', text: String(item.button), variant: 'body' }
797
+ )
798
+ } else if (item.input) {
799
+ components.push({
800
+ id, component: 'TextField',
801
+ label: String(item.label || item.input),
802
+ ...(item.value !== undefined ? { value: String(item.value) } : {}),
803
+ variant: item.variant || 'shortText',
804
+ ...(item.validationRegexp ? { validationRegexp: item.validationRegexp } : {})
805
+ })
806
+ } else if (item.checkbox) {
807
+ components.push({ id, component: 'CheckBox', label: String(item.checkbox), value: !!item.value })
808
+ } else if (item.choice) {
809
+ components.push({
810
+ id, component: 'ChoicePicker',
811
+ ...(item.label ? { label: String(item.label) } : {}),
812
+ options: item.choice.map(o => (typeof o === 'string' ? { label: o, value: o } : { label: String(o.label), value: String(o.value) })),
813
+ value: item.value ? (Array.isArray(item.value) ? item.value.map(String) : [String(item.value)]) : [],
814
+ variant: item.variant || 'mutuallyExclusive',
815
+ ...(item.displayStyle ? { displayStyle: item.displayStyle } : {}),
816
+ ...(item.filterable !== undefined ? { filterable: !!item.filterable } : {})
817
+ })
818
+ } else if (item.slider !== undefined) {
819
+ components.push({ id, component: 'Slider', ...(item.label ? { label: String(item.label) } : {}), min: item.min ?? 0, max: item.slider, value: item.value ?? item.min ?? 0 })
820
+ } else if (item.datetime) {
821
+ components.push({
822
+ id, component: 'DateTimeInput',
823
+ value: item.value !== undefined ? String(item.value) : '',
824
+ enableDate: item.enableDate !== undefined ? !!item.enableDate : true,
825
+ enableTime: !!item.enableTime,
826
+ ...(item.min ? { min: String(item.min) } : {}),
827
+ ...(item.max ? { max: String(item.max) } : {}),
828
+ ...(item.label ? { label: String(item.label) } : {})
829
+ })
830
+ } else if (item.row) {
831
+ const children = item.row.map((sub, j) => buildWidgetItem(sub, `${id}_${j}`, components)).filter(Boolean)
832
+ components.push({ id, component: 'Row', children, justify: item.justify || 'start', align: item.align || 'stretch' })
833
+ } else if (item.column) {
834
+ const children = item.column.map((sub, j) => buildWidgetItem(sub, `${id}_${j}`, components)).filter(Boolean)
835
+ components.push({ id, component: 'Column', children, justify: item.justify || 'start', align: item.align || 'stretch' })
836
+ } else if (item.list) {
837
+ const children = item.list.map((sub, j) => buildWidgetItem(sub, `${id}_${j}`, components)).filter(Boolean)
838
+ components.push({ id, component: 'List', children, direction: item.direction || 'vertical', align: item.align || 'stretch' })
839
+ } else {
840
+ return null
841
+ }
842
+ return id
843
+ }
844
+
845
+ const widgetItemFallback = (item = {}) => {
846
+ if (item.image) return '[image]'
847
+ if (item.text) return String(item.text)
848
+ if (item.icon || item.name) return WIDGET_ICON_ASCII[item.icon || item.name] || `[${item.icon || item.name}]`
849
+ if (item.video) return '[video]'
850
+ if (item.audio) return '[audio]'
851
+ if (item.button) return `${item.button}: ${item.url || ''}`
852
+ if (item.input) return `${item.label || item.input}: ${item.value ?? ''}`
853
+ if (item.checkbox) return `[ ] ${item.checkbox}`
854
+ if (item.choice) return `${item.label || ''} ${(Array.isArray(item.value) ? item.value : [item.value]).filter(Boolean).join(', ')}`.trim()
855
+ if (item.slider !== undefined) return `${item.label || 'slider'}: ${item.value ?? item.min ?? 0}/${item.slider}`
856
+ if (item.datetime) return `${item.label || 'date'}: ${item.value || ''}`
857
+ if (item.row) return item.row.map(widgetItemFallback).filter(Boolean).join(' | ')
858
+ if (item.column || item.list) return (item.column || item.list).map(widgetItemFallback).filter(Boolean).join('\n')
859
+ return ''
860
+ }
861
+
862
+ const prepareBloksWidget = (widget = {}) => {
863
+ const { align = 'center', items = [], fallback } = widget
864
+ const uuid = randomUUID()
865
+ const components = []
866
+ const children = items.map((item, i) => buildWidgetItem(item, `item_${i}`, components)).filter(Boolean)
867
+ components.unshift({ id: 'root', component: 'Column', justify: 'center', align, children })
868
+ const data = JSON.stringify({
869
+ version: 'v0.9',
870
+ createSurface: {
871
+ surfaceId: uuid,
872
+ catalogId: 'https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json',
873
+ components
874
+ }
875
+ })
876
+ return {
877
+ uuid,
878
+ data,
879
+ type: 'im_a2ui',
880
+ fallback: fallback || items.map(widgetItemFallback).filter(Boolean).join('\n') || 'Cannot load widget'
881
+ }
882
+ }
883
+
760
884
  const prepareNativeFlowButtons = message => {
761
885
  const buttons = message.nativeFlow
762
886
  const isButtonsFieldArray = Array.isArray(buttons)
@@ -812,11 +936,6 @@ export const prepareDisappearingMessageSettingContent = ephemeralExpiration => {
812
936
  })
813
937
  }
814
938
 
815
- /**
816
- * Generate forwarded message content like WA does.
817
- * @param message the message to forward
818
- * @param forceForward will show the message as forwarded even if it is from you
819
- */
820
939
  export const generateForwardMessageContent = (message, forceForward) => {
821
940
  let content = message.message
822
941
  if (!content) throw new Boom('no content in message', { statusCode: 400 })
@@ -842,11 +961,31 @@ export const hasValidInteractiveHeader = message =>
842
961
  !!(message.imageMessage || message.videoMessage || message.documentMessage || message.productMessage || message.locationMessage)
843
962
  export const hasValidCarouselHeader = message => !!(message.imageMessage || message.videoMessage || message.productMessage)
844
963
 
964
+ // Tempat contextInfo (mentions, externalAdReply, groupStatus, spoiler, contextInfo) untuk konten `m`.
965
+ // Object.keys(m)[0] salah untuk pesan aiRich/richResponse: key pertamanya `messageContextInfo`, dan isi
966
+ // sebenarnya terbungkus botForwardedMessage -> richResponseMessage (di situlah contextInfo dibaca klien).
967
+ const getContextInfoHolder = m => {
968
+ const pick = obj => Object.keys(obj || {}).find(k => k !== 'messageContextInfo' && k !== 'senderKeyDistributionMessage')
969
+ const type = pick(m)
970
+ if (!type) return undefined
971
+ let holder = m[type]
972
+ if (type === 'botForwardedMessage' && holder?.message) {
973
+ const inner = holder.message
974
+ const innerType = pick(inner)
975
+ if (innerType && inner[innerType]) holder = inner[innerType]
976
+ }
977
+ return holder
978
+ }
979
+
845
980
  export const generateWAMessageContent = async (message, options) => {
846
981
  let m = {}
847
982
  if (hasNonNullishProperty(message, 'raw')) {
848
983
  delete message.raw
849
984
  return message
985
+ } else if (hasNonNullishProperty(message, 'aiRich')) {
986
+ const { aiRich, forwarded, quoted, quotedParticipant, botJid } = message
987
+ const builder = aiRich instanceof AIRichBuilder ? aiRich : aiRichBuilderFromSpec(aiRich)
988
+ m = builder.build({ forwarded, quoted, quotedParticipant, botJid })
850
989
  } else if (
851
990
  hasNonNullishProperty(message, 'code') ||
852
991
  hasNonNullishProperty(message, 'links') ||
@@ -1005,21 +1144,21 @@ export const generateWAMessageContent = async (message, options) => {
1005
1144
  allowAddOption: message.poll.canAddOption ?? false
1006
1145
  }
1007
1146
  if (message.poll.toAnnouncementGroup) {
1008
- m.pollCreationMessageV2 = pollCreationMessage // v2: community announcement groups (single + multiple select)
1147
+ m.pollCreationMessageV2 = pollCreationMessage
1009
1148
  } else if (message.poll.pollType === 1) {
1010
1149
  if (!message.poll.correctAnswer) throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 })
1011
1150
  m.pollCreationMessageV5 = {
1012
- ...pollCreationMessage, // quiz — newsletter only
1151
+ ...pollCreationMessage,
1013
1152
  correctAnswer: { optionName: message.poll.correctAnswer.toString() },
1014
1153
  pollType: 1,
1015
1154
  selectableOptionsCount: 1
1016
1155
  }
1017
1156
  } else if (message.poll.hideVoter) {
1018
- m.pollCreationMessageV6 = pollCreationMessage // v6: hidden-voter-names poll variant
1157
+ m.pollCreationMessageV6 = pollCreationMessage
1019
1158
  } else if (message.poll.selectableCount === 1) {
1020
- m.pollCreationMessageV3 = pollCreationMessage // v3: single select polls
1159
+ m.pollCreationMessageV3 = pollCreationMessage
1021
1160
  } else {
1022
- m.pollCreationMessage = pollCreationMessage // multiple choice polls
1161
+ m.pollCreationMessage = pollCreationMessage
1023
1162
  }
1024
1163
  m.messageContextInfo = { messageSecret: message.poll.messageSecret || randomBytes(32) }
1025
1164
  } else if (hasNonNullishProperty(message, 'pollResult')) {
@@ -1119,7 +1258,8 @@ export const generateWAMessageContent = async (message, options) => {
1119
1258
  hydratedTemplate.hydratedContentText = message.text
1120
1259
  } else {
1121
1260
  if (hasOptionalProperty(message, 'caption')) {
1122
- hydratedTemplate.hydratedTitleText = message.title
1261
+ // oneof 'title': teks judul dan media header tidak boleh terisi bersamaan
1262
+ if (!hasValidInteractiveHeader(m) && message.title) hydratedTemplate.hydratedTitleText = message.title
1123
1263
  hydratedTemplate.hydratedContentText = message.caption
1124
1264
  }
1125
1265
  Object.assign(hydratedTemplate, m)
@@ -1137,14 +1277,16 @@ export const generateWAMessageContent = async (message, options) => {
1137
1277
  if (hasOptionalProperty(message, 'text')) {
1138
1278
  interactiveMessage.body = { text: message.text }
1139
1279
  } else {
1140
- if (hasOptionalProperty(message, 'caption')) {
1141
- const isValidHeader = hasValidInteractiveHeader(m)
1142
- if (!isValidHeader) throw new Boom('Invalid media type for interactive message header', { statusCode: 400 })
1143
- interactiveMessage.header = { title: message.title || '', subtitle: message.subtitle || '', hasMediaAttachment: isValidHeader }
1144
- interactiveMessage.body = { text: message.caption }
1280
+ const isValidHeader = hasValidInteractiveHeader(m)
1281
+ if (!isValidHeader) {
1282
+ if (hasOptionalProperty(message, 'caption')) throw new Boom('Invalid media type for interactive message header', { statusCode: 400 })
1283
+ throw new Boom('nativeFlow needs `text`, or a media (image/video/document/location/product) with an optional `caption`', { statusCode: 400 })
1145
1284
  }
1146
- if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) interactiveMessage.jpegThumbnail = message.thumbnail
1285
+ // header media selalu dibuat, juga saat caption tidak diisi (sebelumnya: TypeError pada Object.assign(undefined, m))
1286
+ interactiveMessage.header = { title: message.title || '', subtitle: message.subtitle || '', hasMediaAttachment: true }
1147
1287
  Object.assign(interactiveMessage.header, m)
1288
+ interactiveMessage.body = { text: hasOptionalProperty(message, 'caption') ? message.caption : '' }
1289
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) interactiveMessage.jpegThumbnail = message.thumbnail
1148
1290
  }
1149
1291
  if (hasOptionalProperty(message, 'audioFooter')) {
1150
1292
  const { audioMessage } = await prepareWAMessageMedia({ audio: message.audioFooter }, options)
@@ -1152,6 +1294,7 @@ export const generateWAMessageContent = async (message, options) => {
1152
1294
  } else if (hasOptionalProperty(message, 'footer')) {
1153
1295
  interactiveMessage.footer = { text: message.footer }
1154
1296
  }
1297
+ if (hasNonNullishProperty(message, 'widget')) interactiveMessage.bloksWidget = prepareBloksWidget(message.widget)
1155
1298
  m = { interactiveMessage }
1156
1299
  } else if (hasNonNullishProperty(message, 'cards')) {
1157
1300
  const interactiveMessage = {
@@ -1160,19 +1303,26 @@ export const generateWAMessageContent = async (message, options) => {
1160
1303
  message.cards.map(async card => {
1161
1304
  let carouselHeader = {}
1162
1305
  if (hasNonNullishProperty(card, 'product')) carouselHeader.productMessage = await prepareProductMessage(card, options)
1163
- else carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}))
1306
+ else {
1307
+ try {
1308
+ carouselHeader = await prepareWAMessageMedia(card, options)
1309
+ } catch (err) {
1310
+ // kalau card memang membawa media, error upload/baca file harus sampai ke pemanggil, bukan tersamar jadi "Invalid media type"
1311
+ if (card.image || card.video) throw err
1312
+ carouselHeader = {}
1313
+ }
1314
+ }
1164
1315
  const isValidHeader = hasValidCarouselHeader(carouselHeader)
1165
1316
  if (!isValidHeader) throw new Boom('Invalid media type for carousel card', { statusCode: 400 })
1166
- const carouselCard = { nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : []) }
1317
+ const carouselCard = { nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : { nativeFlow: [] }) }
1318
+ // header media wajib ada di setiap card (dulu hilang kalau card memakai `text`, dan TypeError kalau tanpa `caption`)
1319
+ carouselCard.header = { title: card.title || '', subtitle: card.subtitle || '', hasMediaAttachment: true }
1320
+ Object.assign(carouselCard.header, carouselHeader)
1167
1321
  if (hasOptionalProperty(card, 'text')) {
1168
1322
  carouselCard.body = { text: card.text }
1169
1323
  } else {
1170
- if (hasOptionalProperty(card, 'caption')) {
1171
- carouselCard.header = { title: card.title || '', subtitle: card.subtitle || '', hasMediaAttachment: isValidHeader }
1172
- carouselCard.body = { text: card.caption }
1173
- }
1324
+ if (hasOptionalProperty(card, 'caption')) carouselCard.body = { text: card.caption }
1174
1325
  if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) carouselCard.jpegThumbnail = card.thumbnail
1175
- Object.assign(carouselCard.header, carouselHeader)
1176
1326
  }
1177
1327
  if (hasOptionalProperty(card, 'audioFooter')) {
1178
1328
  const { audioMessage } = await prepareWAMessageMedia({ audio: card.audioFooter }, options)
@@ -1230,8 +1380,7 @@ export const generateWAMessageContent = async (message, options) => {
1230
1380
  }
1231
1381
 
1232
1382
  if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1233
- const messageType = Object.keys(m)[0]
1234
- const key = m[messageType]
1383
+ const key = getContextInfoHolder(m)
1235
1384
  const content = message.externalAdReply
1236
1385
  if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) throw new Boom('Thumbnail must in buffer type', { statusCode: 400 })
1237
1386
  if (content.url != null && typeof content.url !== 'string') throw new Boom('externalAdReply.url must be a string', { statusCode: 400 })
@@ -1249,12 +1398,11 @@ export const generateWAMessageContent = async (message, options) => {
1249
1398
  delete externalAdReply.subTitle
1250
1399
  delete externalAdReply.largeThumbnail
1251
1400
  delete externalAdReply.url
1252
- if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply }
1401
+ if (key && 'contextInfo' in key && !!key.contextInfo) key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply }
1253
1402
  else if (key) key.contextInfo = { externalAdReply }
1254
1403
  }
1255
1404
  if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) || (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1256
- const messageType = Object.keys(m)[0]
1257
- const key = m[messageType]
1405
+ const key = getContextInfoHolder(m)
1258
1406
  if (key && 'contextInfo' in key) {
1259
1407
  key.contextInfo = key.contextInfo || {}
1260
1408
  if (message.mentions?.length) key.contextInfo.mentionedJid = message.mentions
@@ -1264,23 +1412,20 @@ export const generateWAMessageContent = async (message, options) => {
1264
1412
  }
1265
1413
  }
1266
1414
  if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1267
- const messageType = Object.keys(m)[0]
1268
- const key = m[messageType]
1269
- if ('contextInfo' in key && !!key.contextInfo) key.contextInfo = { ...key.contextInfo, ...message.contextInfo }
1415
+ const key = getContextInfoHolder(m)
1416
+ if (key && 'contextInfo' in key && !!key.contextInfo) key.contextInfo = { ...key.contextInfo, ...message.contextInfo }
1270
1417
  else if (key) key.contextInfo = message.contextInfo
1271
1418
  }
1272
1419
  if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1273
- const messageType = Object.keys(m)[0]
1274
- const key = m[messageType]
1275
- if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.isGroupStatus = message.groupStatus
1420
+ const key = getContextInfoHolder(m)
1421
+ if (key && 'contextInfo' in key && !!key.contextInfo) key.contextInfo.isGroupStatus = message.groupStatus
1276
1422
  else if (key) key.contextInfo = { isGroupStatus: message.groupStatus }
1277
1423
  m = { groupStatusMessageV2: { message: m } }
1278
1424
  delete message.groupStatus
1279
1425
  }
1280
1426
  if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1281
- const messageType = Object.keys(m)[0]
1282
- const key = m[messageType]
1283
- if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.isSpoiler = message.spoiler
1427
+ const key = getContextInfoHolder(m)
1428
+ if (key && 'contextInfo' in key && !!key.contextInfo) key.contextInfo.isSpoiler = message.spoiler
1284
1429
  else if (key) key.contextInfo = { isSpoiler: message.spoiler }
1285
1430
  m = { spoilerMessage: { message: m } }
1286
1431
  delete message.spoiler
@@ -1327,14 +1472,14 @@ export const generateWAMessageFromContent = (jid, message, options) => {
1327
1472
  const participant = quoted.key.fromMe ? userJid : quoted.participant || quoted.key.participant || quoted.key.remoteJid
1328
1473
  let quotedMsg = normalizeMessageContent(quoted.message)
1329
1474
  const msgType = getContentType(quotedMsg)
1330
- quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] }) // strip redundant properties
1475
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] })
1331
1476
  const quotedContent = quotedMsg[msgType]
1332
1477
  if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) delete quotedContent.contextInfo
1333
1478
  const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {}
1334
1479
  contextInfo.participant = jidNormalizedUser(participant)
1335
1480
  contextInfo.stanzaId = quoted.key.id
1336
1481
  contextInfo.quotedMessage = quotedMsg
1337
- // if a participant is quoted, then it must be a group, so remoteJid of that group must also be set
1482
+
1338
1483
  if (!isNewsletter && jid !== quoted.key.remoteJid) contextInfo.remoteJid = quoted.key.remoteJid
1339
1484
  if (contextInfo && innerMessage[key]) innerMessage[key].contextInfo = contextInfo
1340
1485
  }
@@ -1356,13 +1501,12 @@ export const generateWAMessageFromContent = (jid, message, options) => {
1356
1501
  }
1357
1502
 
1358
1503
  export const generateWAMessage = async (jid, content, options) => {
1359
- // ensure msg ID is with every log
1504
+
1360
1505
  options.logger = options?.logger?.child({ msgId: options.messageId })
1361
- // Pass jid in the options to generateWAMessageContent (copy: do not mutate the caller's options)
1506
+
1362
1507
  return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options)
1363
1508
  }
1364
1509
 
1365
- /** Get the key to access the true type of content */
1366
1510
  export const getContentType = content => {
1367
1511
  if (content) {
1368
1512
  const keys = Object.keys(content)
@@ -1399,10 +1543,6 @@ const getFutureProofMessage = message =>
1399
1543
  message?.viewOnceMessageV2 ||
1400
1544
  message?.viewOnceMessageV2Extension
1401
1545
 
1402
- /**
1403
- * Normalizes ephemeral, view once messages to regular message content.
1404
- * Eg. image messages in ephemeral messages, in view once messages etc.
1405
- */
1406
1546
  export const normalizeMessageContent = content => {
1407
1547
  if (!content) return undefined
1408
1548
  for (let i = 0; i < 5; i++) {
@@ -1413,7 +1553,6 @@ export const normalizeMessageContent = content => {
1413
1553
  return content
1414
1554
  }
1415
1555
 
1416
- /** Extract the true message content from a message. Eg. extracts the inner message from a disappearing/view-once message. */
1417
1556
  export const extractMessageContent = content => {
1418
1557
  const extractFromTemplateMessage = msg => {
1419
1558
  if (msg.imageMessage) return { imageMessage: msg.imageMessage }
@@ -1430,11 +1569,9 @@ export const extractMessageContent = content => {
1430
1569
  return content
1431
1570
  }
1432
1571
 
1433
- /** Returns the device predicted by message ID */
1434
1572
  export const getDevice = id =>
1435
1573
  /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^(3F|.{18}$)/.test(id) ? 'desktop' : 'unknown'
1436
1574
 
1437
- /** Upserts a receipt in the message */
1438
1575
  export const updateMessageWithReceipt = (msg, receipt) => {
1439
1576
  msg.userReceipt = msg.userReceipt || []
1440
1577
  const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
@@ -1442,7 +1579,6 @@ export const updateMessageWithReceipt = (msg, receipt) => {
1442
1579
  else msg.userReceipt.push(receipt)
1443
1580
  }
1444
1581
 
1445
- /** Update the message with a new reaction */
1446
1582
  export const updateMessageWithReaction = (msg, reaction) => {
1447
1583
  const authorID = getKeyAuthor(reaction.key)
1448
1584
  const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
@@ -1451,7 +1587,6 @@ export const updateMessageWithReaction = (msg, reaction) => {
1451
1587
  msg.reactions = reactions
1452
1588
  }
1453
1589
 
1454
- /** Update the message with a new poll update */
1455
1590
  export const updateMessageWithPollUpdate = (msg, update) => {
1456
1591
  const authorID = getKeyAuthor(update.pollUpdateMessageKey)
1457
1592
  const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
@@ -1459,7 +1594,6 @@ export const updateMessageWithPollUpdate = (msg, update) => {
1459
1594
  msg.pollUpdates = reactions
1460
1595
  }
1461
1596
 
1462
- /** Update the message with a new event response */
1463
1597
  export const updateMessageWithEventResponse = (msg, update) => {
1464
1598
  const authorID = getKeyAuthor(update.eventResponseMessageKey)
1465
1599
  const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID)
@@ -1467,7 +1601,6 @@ export const updateMessageWithEventResponse = (msg, update) => {
1467
1601
  msg.eventResponses = responses
1468
1602
  }
1469
1603
 
1470
- /** Aggregates all poll updates in a poll. Returns a list of options & their voters. */
1471
1604
  export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1472
1605
  const opts =
1473
1606
  message?.pollCreationMessage?.options ||
@@ -1497,7 +1630,6 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1497
1630
  return Object.values(voteHashMap)
1498
1631
  }
1499
1632
 
1500
- /** Aggregates all event responses in an event message. Returns a list of response types & their responders. */
1501
1633
  export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1502
1634
  const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE']
1503
1635
  const responseMap = {}
@@ -1509,7 +1641,6 @@ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1509
1641
  return Object.values(responseMap)
1510
1642
  }
1511
1643
 
1512
- /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk. */
1513
1644
  export const aggregateMessageKeysNotFromMe = keys => {
1514
1645
  const keyMap = {}
1515
1646
  for (const { remoteJid, id, participant, fromMe } of keys) {
@@ -1524,7 +1655,6 @@ export const aggregateMessageKeysNotFromMe = keys => {
1524
1655
 
1525
1656
  const REUPLOAD_REQUIRED_STATUS = [410, 404]
1526
1657
 
1527
- /** Downloads the given message. Throws an error if it's not a media message. */
1528
1658
  export const downloadMediaMessage = async (message, type, options, ctx) => {
1529
1659
  async function downloadMsg() {
1530
1660
  const mContent = extractMessageContent(message.message)
@@ -1561,7 +1691,6 @@ export const downloadMediaMessage = async (message, type, options, ctx) => {
1561
1691
  })
1562
1692
  }
1563
1693
 
1564
- /** Checks whether the given message is a media message; if it is returns the inner content */
1565
1694
  export const assertMediaContent = content => {
1566
1695
  content = extractMessageContent(content)
1567
1696
  const mediaContent = content?.documentMessage || content?.imageMessage || content?.videoMessage || content?.audioMessage || content?.stickerMessage
@@ -1569,7 +1698,6 @@ export const assertMediaContent = content => {
1569
1698
  return mediaContent
1570
1699
  }
1571
1700
 
1572
- /** Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag, or ANIM/ANMF chunks */
1573
1701
  const isAnimatedWebP = buffer => {
1574
1702
  if (!isWebPBuffer(buffer)) return false
1575
1703
  let offset = 12
@@ -1587,7 +1715,6 @@ const isAnimatedWebP = buffer => {
1587
1715
  return false
1588
1716
  }
1589
1717
 
1590
- /** Checks if a buffer is a WebP file */
1591
1718
  const isWebPBuffer = buffer =>
1592
1719
  buffer.length >= 12 &&
1593
1720
  buffer[0] === 0x52 &&
@@ -1599,11 +1726,7 @@ const isWebPBuffer = buffer =>
1599
1726
  buffer[10] === 0x42 &&
1600
1727
  buffer[11] === 0x50
1601
1728
 
1602
- /**
1603
- * Determines whether a message should include a Biz Binary Node.
1604
- * A Biz Binary Node is added only for interactive messages such as buttons or other supported interactive types.
1605
- */
1606
1729
  export const shouldIncludeBizBinaryNode = message =>
1607
- !!(message.buttonsMessage || message.listMessage || message.templateMessage || (message.interactiveMessage && message.interactiveMessage.nativeFlowMessage))
1730
+ !!(message.buttonsMessage || message.listMessage || message.templateMessage || (message.interactiveMessage && (message.interactiveMessage.nativeFlowMessage || message.interactiveMessage.carouselMessage)))
1608
1731
 
1609
1732
  export { AssociationType }