plainscript-lang 1.0.3 → 1.0.35

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 (74) hide show
  1. package/README.md +29 -0
  2. package/compiler/cli.js +1 -1
  3. package/compiler/dependency-detector.js +6 -2
  4. package/compiler/generator.js +422 -51
  5. package/compiler/parser.js +40 -2
  6. package/compiler/version.js +1 -1
  7. package/docs/CAPABILITY_GAP_AUDIT.md +9 -3
  8. package/docs/PLAINSCRIPT-SPEC.md +135 -3
  9. package/docs/index.html +27 -26
  10. package/docs/logo-pln.jpg +0 -0
  11. package/docs/visualization-example.svg +32 -0
  12. package/docs/website/script.js +130 -1
  13. package/docs/website/style.css +211 -47
  14. package/examples/ai-providers.pln +1 -1
  15. package/examples/arrays.pln +1 -1
  16. package/examples/async-errors.pln +1 -1
  17. package/examples/auth-api.pln +1 -1
  18. package/examples/auth-sessions.pln +1 -1
  19. package/examples/basics.pln +1 -1
  20. package/examples/bots.pln +1 -1
  21. package/examples/cache-and-jobs.pln +1 -1
  22. package/examples/cache-schedule.pln +1 -1
  23. package/examples/collections.pln +1 -1
  24. package/examples/concurrency.pln +1 -1
  25. package/examples/conditions.pln +1 -1
  26. package/examples/database.pln +1 -1
  27. package/examples/day2.pln +1 -1
  28. package/examples/day3.pln +1 -1
  29. package/examples/deployment.pln +1 -1
  30. package/examples/email-send.pln +1 -1
  31. package/examples/error-handling.pln +1 -1
  32. package/examples/expressions.pln +1 -1
  33. package/examples/file-uploads.pln +1 -1
  34. package/examples/files-and-config.pln +1 -1
  35. package/examples/files.pln +1 -1
  36. package/examples/football-backend/app.pln +1 -1
  37. package/examples/functions.pln +1 -1
  38. package/examples/hello.pln +1 -1
  39. package/examples/http-client.pln +1 -1
  40. package/examples/http.pln +1 -1
  41. package/examples/id-verification/app.pln +1 -1
  42. package/examples/json.pln +1 -1
  43. package/examples/loops.pln +1 -1
  44. package/examples/modules/app.pln +1 -1
  45. package/examples/modules/main.pln +1 -1
  46. package/examples/modules/math.pln +1 -1
  47. package/examples/mongo.pln +1 -1
  48. package/examples/objects.pln +1 -1
  49. package/examples/ocr.pln +1 -1
  50. package/examples/packages.pln +1 -1
  51. package/examples/record-kinds.pln +1 -1
  52. package/examples/records.pln +1 -1
  53. package/examples/rest-api-fetch.pln +1 -1
  54. package/examples/rest-api.pln +1 -1
  55. package/examples/scheduled-tasks.pln +1 -1
  56. package/examples/search-and-filter.pln +1 -1
  57. package/examples/server.pln +1 -1
  58. package/examples/sessions-and-cookies.pln +1 -1
  59. package/examples/sqlite.pln +1 -1
  60. package/examples/start.pln +1 -1
  61. package/examples/stdlib.pln +1 -1
  62. package/examples/string-verbs.pln +1 -1
  63. package/examples/telegram-ai-bot.pln +1 -1
  64. package/examples/telegram-bot.pln +1 -1
  65. package/examples/testing.pln +1 -1
  66. package/examples/visualization.pln +12 -0
  67. package/examples/web-api.pln +1 -1
  68. package/examples/web-app.pln +1 -1
  69. package/examples/websocket-server.pln +1 -1
  70. package/examples/websocket.pln +1 -1
  71. package/examples/whatsapp-bot/pairing.pln +24 -2
  72. package/examples/whatsapp-bot/qr.pln +18 -2
  73. package/package.json +2 -1
  74. package/docs/logo.jpg +0 -0
@@ -221,6 +221,96 @@ const BUILTIN_DECLARATIONS = {
221
221
  ` });`,
222
222
  `}`,
223
223
  ].join('\n'),
224
+ // v1.0.35 — dependency-free SVG images and visualizations.
225
+ // The image value is an SVG string, so it can be saved, embedded, or returned
226
+ // from a web route without a native graphics dependency.
227
+ visualization: [
228
+ `const __vizFs = require('fs');`,
229
+ `function __svgEscape(value) {`,
230
+ ` return String(value == null ? '' : value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');`,
231
+ `}`,
232
+ `function __vizOptions(options) {`,
233
+ ` return Object.assign({ width: 720, height: 420, background: '#071b10', foreground: '#e6f1e7', grid: '#284734', accent: '#40c463', muted: '#8da99a' }, options || {});`,
234
+ `}`,
235
+ `function __svgImage(width, height, content, options) {`,
236
+ ` const opt = __vizOptions(options);`,
237
+ ` const w = Number(width) || opt.width;`,
238
+ ` const h = Number(height) || opt.height;`,
239
+ ` return '<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '" role="img">' +`,
240
+ ` '<rect width="100%" height="100%" fill="' + __svgEscape(opt.background) + '"/>' + String(content == null ? '' : content) + '</svg>';`,
241
+ `}`,
242
+ `function __vizText(x, y, value, size, fill, anchor, weight) {`,
243
+ ` return '<text x="' + x + '" y="' + y + '" fill="' + __svgEscape(fill) + '" font-family="Arial, sans-serif" font-size="' + size + '" text-anchor="' + (anchor || 'start') + '" font-weight="' + (weight || 400) + '">' + __svgEscape(value) + '</text>';`,
244
+ `}`,
245
+ `function __barChart(title, labels, values, options) {`,
246
+ ` const opt = __vizOptions(options);`,
247
+ ` const names = Array.isArray(labels) ? labels : [];`,
248
+ ` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
249
+ ` const count = Math.max(names.length, nums.length, 1);`,
250
+ ` const width = Number(opt.width) || 720;`,
251
+ ` const height = Number(opt.height) || 420;`,
252
+ ` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
253
+ ` const plotWidth = Math.max(1, width - left - right);`,
254
+ ` const plotHeight = Math.max(1, height - top - bottom);`,
255
+ ` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
256
+ ` const barWidth = plotWidth / count * 0.68;`,
257
+ ` const gap = plotWidth / count;`,
258
+ ` let body = '';`,
259
+ ` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
260
+ ` for (let tick = 0; tick <= 4; tick++) {`,
261
+ ` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
262
+ ` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
263
+ ` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
264
+ ` }`,
265
+ ` for (let index = 0; index < count; index++) {`,
266
+ ` const value = Math.max(0, nums[index] || 0); const barHeight = value / max * plotHeight;`,
267
+ ` const x = left + index * gap + (gap - barWidth) / 2; const y = top + plotHeight - barHeight;`,
268
+ ` body += '<rect x="' + x + '" y="' + y + '" width="' + barWidth + '" height="' + barHeight + '" rx="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
269
+ ` body += __vizText(left + index * gap + gap / 2, height - 24, names[index] == null ? '' : names[index], 12, opt.muted, 'middle', 400);`,
270
+ ` }`,
271
+ ` return __svgImage(width, height, body, opt);`,
272
+ `}`,
273
+ `function __lineChart(title, labels, values, options) {`,
274
+ ` const opt = __vizOptions(options);`,
275
+ ` const names = Array.isArray(labels) ? labels : [];`,
276
+ ` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
277
+ ` const count = Math.max(names.length, nums.length, 2);`,
278
+ ` const width = Number(opt.width) || 720;`,
279
+ ` const height = Number(opt.height) || 420;`,
280
+ ` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
281
+ ` const plotWidth = Math.max(1, width - left - right);`,
282
+ ` const plotHeight = Math.max(1, height - top - bottom);`,
283
+ ` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
284
+ ` let body = '';`,
285
+ ` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
286
+ ` for (let tick = 0; tick <= 4; tick++) {`,
287
+ ` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
288
+ ` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
289
+ ` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
290
+ ` }`,
291
+ ` const points = nums.map((value, index) => {`,
292
+ ` const x = left + (count === 1 ? plotWidth / 2 : index * plotWidth / (count - 1));`,
293
+ ` const y = top + plotHeight - Math.max(0, value) / max * plotHeight;`,
294
+ ` return { x, y, label: names[index] == null ? '' : names[index] };`,
295
+ ` });`,
296
+ ` if (points.length) {`,
297
+ ` body += '<polyline fill="none" stroke="' + __svgEscape(opt.accent) + '" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" points="' + points.map(point => point.x + ',' + point.y).join(' ') + '"/>';`,
298
+ ` for (const point of points) {`,
299
+ ` body += '<circle cx="' + point.x + '" cy="' + point.y + '" r="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
300
+ ` body += __vizText(point.x, height - 24, point.label, 12, opt.muted, 'middle', 400);`,
301
+ ` }`,
302
+ ` }`,
303
+ ` return __svgImage(width, height, body, opt);`,
304
+ `}`,
305
+ `function __saveImage(file, image) {`,
306
+ ` const target = String(file);`,
307
+ ` __vizFs.writeFileSync(target, String(image == null ? '' : image), 'utf8');`,
308
+ ` return target;`,
309
+ `}`,
310
+ `function __imageDataUri(image) {`,
311
+ ` return 'data:image/svg+xml;base64,' + Buffer.from(String(image == null ? '' : image), 'utf8').toString('base64');`,
312
+ `}`,
313
+ ].join('\n'),
224
314
  // v1.0.1 — process execution (child processes).
225
315
  process: [
226
316
  `const { execFile } = require('child_process');`,
@@ -389,8 +479,9 @@ const BUILTIN_DECLARATIONS = {
389
479
  // lifecycle and messages.upsert normalization. PlainScript programs only ever
390
480
  // see __whatsappStart/__whatsappOnMessage/__whatsappReply.
391
481
  whatsapp: [
392
- `const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {`,
482
+ `const { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload } = (() => {`,
393
483
  ` let sock = null;`,
484
+ ` let __waBaileysPkg = '@qwerty-xcv/baileys';`,
394
485
  ` const handlers = [];`,
395
486
  ` const __waSilentLogger = (() => {`,
396
487
  ` const noop = () => {};`,
@@ -415,21 +506,95 @@ const BUILTIN_DECLARATIONS = {
415
506
  ` }`,
416
507
  ` function __waExtractText(content) {`,
417
508
  ` if (!content) return '';`,
418
- ` return String(` +
419
- `(content.conversation || (content.extendedTextMessage || {}).text || ` +
420
- `(content.imageMessage || {}).caption || (content.videoMessage || {}).caption || ` +
421
- `(content.documentMessage || {}).caption) || '');`,
509
+ ` const c = content;`,
510
+ ` if (c.conversation != null) return String(c.conversation);`,
511
+ ` if (c.extendedTextMessage && c.extendedTextMessage.text != null) return String(c.extendedTextMessage.text);`,
512
+ ` if (c.imageMessage && c.imageMessage.caption != null) return String(c.imageMessage.caption);`,
513
+ ` if (c.videoMessage && c.videoMessage.caption != null) return String(c.videoMessage.caption);`,
514
+ ` if (c.documentMessage && c.documentMessage.caption != null) return String(c.documentMessage.caption);`,
515
+ ` if (c.audioMessage && c.audioMessage.caption != null) return String(c.audioMessage.caption);`,
516
+ ` if (c.stickerMessage && c.stickerMessage.caption != null) return String(c.stickerMessage.caption);`,
517
+ ` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return String(c.buttonsResponseMessage.selectedButtonId);`,
518
+ ` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply && c.listResponseMessage.singleSelectReply.selectedRowId != null) return String(c.listResponseMessage.singleSelectReply.selectedRowId);`,
519
+ ` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return String(c.templateButtonReplyMessage.selectedId);`,
520
+ ` if (c.reactionMessage && c.reactionMessage.text != null) return String(c.reactionMessage.text);`,
521
+ ` if (c.contactMessage && c.contactMessage.displayName != null) return String(c.contactMessage.displayName);`,
522
+ ` if (c.contactsArrayMessage && c.contactsArrayMessage.contacts) return c.contactsArrayMessage.contacts.map(x => x.displayName || '').join(', ');`,
523
+ ` if (c.locationMessage) return String(c.locationMessage.degreesLatitude) + ',' + String(c.locationMessage.degreesLongitude);`,
524
+ ` if (c.groupInviteMessage) return String(c.groupInviteMessage.groupJid || '');`,
525
+ ` if (c.pollCreationMessage && c.pollCreationMessage.name != null) return String(c.pollCreationMessage.name);`,
526
+ ` return '';`,
527
+ ` }`,
528
+ ` function __waMessageType(content) {`,
529
+ ` if (!content) return 'unknown';`,
530
+ ` const c = content;`,
531
+ ` if (c.conversation != null || c.extendedTextMessage) return 'text';`,
532
+ ` if (c.imageMessage) return 'image';`,
533
+ ` if (c.videoMessage) return 'video';`,
534
+ ` if (c.audioMessage) return 'audio';`,
535
+ ` if (c.documentMessage) return 'document';`,
536
+ ` if (c.stickerMessage) return 'sticker';`,
537
+ ` if (c.buttonsResponseMessage) return 'button';`,
538
+ ` if (c.listResponseMessage) return 'list';`,
539
+ ` if (c.templateButtonReplyMessage) return 'template-button';`,
540
+ ` if (c.interactiveResponseMessage) return 'interactive';`,
541
+ ` if (c.reactionMessage) return 'reaction';`,
542
+ ` if (c.contactMessage) return 'contact';`,
543
+ ` if (c.contactsArrayMessage) return 'contacts';`,
544
+ ` if (c.locationMessage) return 'location';`,
545
+ ` if (c.liveLocationMessage) return 'live-location';`,
546
+ ` if (c.pollCreationMessage) return 'poll';`,
547
+ ` if (c.pollUpdateMessage) return 'poll-update';`,
548
+ ` if (c.groupInviteMessage) return 'group-invite';`,
549
+ ` if (c.protocolMessage) return 'protocol';`,
550
+ ` if (c.buttonsMessage) return 'buttons';`,
551
+ ` if (c.templateMessage) return 'template';`,
552
+ ` if (c.interactiveMessage) return 'interactive';`,
553
+ ` return 'other';`,
554
+ ` }`,
555
+ ` function __waButtonId(content) {`,
556
+ ` if (!content) return null;`,
557
+ ` const c = content;`,
558
+ ` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return c.buttonsResponseMessage.selectedButtonId;`,
559
+ ` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply) return c.listResponseMessage.singleSelectReply.selectedRowId || null;`,
560
+ ` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return c.templateButtonReplyMessage.selectedId;`,
561
+ ` if (c.interactiveResponseMessage && c.interactiveResponseMessage.nativeFlowResponseMessage) {`,
562
+ ` try { return JSON.parse(c.interactiveResponseMessage.nativeFlowResponseMessage.paramsJson).id || null; } catch (_) { return null; }`,
563
+ ` }`,
564
+ ` return null;`,
565
+ ` }`,
566
+ ` async function __waDownload(message, dest) {`,
567
+ ` if (!sock) throw new Error('WhatsApp: the bot is not connected.');`,
568
+ ` const { downloadMediaMessage } = require(__waBaileysPkg);`,
569
+ ` const raw = message && message.raw ? message.raw : message;`,
570
+ ` const buffer = await downloadMediaMessage(raw, 'buffer', {}, { logger: __waSilentLogger, reuploadRequest: sock.updateMediaMessage });`,
571
+ ` if (!dest) return buffer;`,
572
+ ` const fs = require('fs'), path = require('path');`,
573
+ ` const dir = path.dirname(path.resolve(dest));`,
574
+ ` if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });`,
575
+ ` fs.writeFileSync(dest, buffer);`,
576
+ ` return dest;`,
577
+ ` }`,
578
+ ` async function __whatsappDownload(message, dest) {`,
579
+ ` if (!message) throw new Error('WhatsApp: there is no message to download.');`,
580
+ ` await __waDownload(message, dest);`,
581
+ ` console.log('WhatsApp: saved media to ' + dest);`,
422
582
  ` }`,
423
- ` async function __whatsappReply(chat, value) {`,
583
+ ` async function __whatsappReply(chat, value, extra) {`,
424
584
  ` if (!sock) throw new Error('WhatsApp: cannot reply because the bot is not connected yet.');`,
425
585
  ` const text = typeof value === 'string' ? value : JSON.stringify(value);`,
426
- ` return sock.sendMessage(chat, { text });`,
586
+ ` return sock.sendMessage(chat, Object.assign({ text }, extra || {}));`,
587
+ ` }`,
588
+ ` async function __whatsappSend(chat, value) {`,
589
+ ` if (!sock) throw new Error('WhatsApp: cannot send because the bot is not connected yet.');`,
590
+ ` return sock.sendMessage(chat, typeof value === 'string' ? { text: value } : value);`,
427
591
  ` }`,
428
592
  ` function __whatsappOnMessage(handler) { handlers.push(handler); }`,
429
593
  ` async function __whatsappStart(options) {`,
430
- ` const baileys = require('@whiskeysockets/baileys');`,
594
+ ` __waBaileysPkg = options.baileys || '@qwerty-xcv/baileys';`,
595
+ ` const baileys = require(__waBaileysPkg);`,
431
596
  ` const makeWASocket = baileys.default;`,
432
- ` const { useMultiFileAuthState, fetchLatestBaileysVersion, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
597
+ ` const { useMultiFileAuthState, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
433
598
  ` const folder = options.folder || 'plainscript-whatsapp-auth';`,
434
599
  ` const mode = options.login && options.login.mode === 'pairing' ? 'pairing' : 'qr';`,
435
600
  ` const pairingPhone = mode === 'pairing' ? __waNormalizePhone(options.login.phone) : null;`,
@@ -441,35 +606,45 @@ const BUILTIN_DECLARATIONS = {
441
606
  // Auth/session persistence: useMultiFileAuthState stores credentials in
442
607
  // the folder from `auth "<name>"`; saveCreds writes every update back.
443
608
  ` const { state, saveCreds } = await useMultiFileAuthState(folder);`,
444
- ` let version;`,
445
- ` try { version = (await fetchLatestBaileysVersion()).version; } catch (_) {}`,
446
- // Proven socket settings: these exact options are required for pairing
447
- // codes to survive WhatsApp's handshake without a 428 connection close.
609
+ // v2.14 — adopt the proven pairing-safe socket settings used by the
610
+ // reference Dual-Crasher build on the qwerty fork: a fixed Baileys protocol
611
+ // version and the exact browser fingerprint that survives WhatsApp's
612
+ // handshake without a 428 connection close.
448
613
  ` sock = makeWASocket({`,
449
- ` ...(version ? { version } : {}),`,
450
- ` browser: ['Ubuntu', 'Edge', '20.0.04'],`,
614
+ ` version: [2, 2413, 1],`,
615
+ ` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
451
616
  ` printQRInTerminal: false,`,
452
617
  ` syncFullHistory: false,`,
453
618
  ` markOnlineOnConnect: false,`,
619
+ ` generateHighQualityLinkPreview: true,`,
454
620
  ` defaultQueryTimeoutMs: 60000,`,
455
- ` keepAliveIntervalMs: 30000,`,
621
+ ` keepAliveIntervalMs: 50000,`,
456
622
  ` logger: __waSilentLogger,`,
457
623
  ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
458
624
  ` });`,
459
625
  ` sock.ev.on('creds.update', saveCreds);`,
460
626
  // Pairing codes are requested two seconds after socket creation — asking
461
- // earlier aborts the link attempt. PlainScript calls requestPairingCode(phone)
462
- // with no custom suffix; the number was validated at compile time.
627
+ // earlier aborts the link attempt. PlainScript retries a few times (spam)
628
+ // so a dropped request never blocks linking. The number was validated at
629
+ // compile time; no custom suffix is applied.
463
630
  ` if (mode === 'pairing' && !state.creds.registered) {`,
464
- ` setTimeout(() => {`,
465
- ` if (!sock) return;`,
466
- ` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
467
- ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
468
- ` console.log('WhatsApp pairing code: ' + pretty);`,
469
- ` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
470
- ` }).catch((error) => {`,
471
- ` console.error('WhatsApp pairing code failed: ' + error.message);`,
472
- ` });`,
631
+ ` let attempts = 0;`,
632
+ ` const requestCode = async () => {`,
633
+ ` if (!sock || attempts >= 4) return;`,
634
+ ` attempts += 1;`,
635
+ ` try {`,
636
+ ` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
637
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
638
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
639
+ ` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
640
+ ` }).catch((error) => {`,
641
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
642
+ ` });`,
643
+ ` } catch (_) {}`,
644
+ ` };`,
645
+ ` setTimeout(async () => {`,
646
+ ` await requestCode();`,
647
+ ` setTimeout(requestCode, 4000);`,
473
648
  ` }, 2000);`,
474
649
  ` }`,
475
650
  // Connection lifecycle: the QR code while linking, a friendly note on
@@ -514,16 +689,23 @@ const BUILTIN_DECLARATIONS = {
514
689
  ` if (key.fromMe) continue;`,
515
690
  ` const chat = key.remoteJid;`,
516
691
  ` if (!chat || chat === 'status@broadcast') continue;`,
692
+ ` const content = __waUnwrap(msg.message);`,
517
693
  ` const message = {`,
518
- ` text: __waExtractText(__waUnwrap(msg.message)),`,
694
+ ` text: __waExtractText(content),`,
695
+ ` type: __waMessageType(content),`,
696
+ ` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
697
+ ` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
698
+ ` buttonId: __waButtonId(content),`,
519
699
  ` chat,`,
520
700
  ` sender: key.participant || chat,`,
521
701
  ` name: msg.pushName || null,`,
522
702
  ` id: key.id || null,`,
523
703
  ` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
524
704
  ` isGroup: chat.endsWith('@g.us'),`,
705
+ ` raw: msg,`,
706
+ ` download: (dest) => __waDownload(msg, dest),`,
525
707
  ` };`,
526
- ` const ctx = { chat, message, reply: (value) => __whatsappReply(chat, value) };`,
708
+ ` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
527
709
  ` for (const handler of handlers) {`,
528
710
  ` await handler(ctx);`,
529
711
  ` }`,
@@ -538,7 +720,107 @@ const BUILTIN_DECLARATIONS = {
538
720
  ` };`,
539
721
  ` await connect();`,
540
722
  ` }`,
541
- ` return { __whatsappStart, __whatsappOnMessage, __whatsappReply };`,
723
+ ` async function __whatsappPair(phone, onCode, onOpen) {`,
724
+ ` const digits = __waNormalizePhone(phone);`,
725
+ ` const baileys = require(__waBaileysPkg);`,
726
+ ` const makeWASocket = baileys.default;`,
727
+ ` const { useMultiFileAuthState, makeCacheableSignalKeyStore } = baileys;`,
728
+ ` const { state, saveCreds } = await useMultiFileAuthState('whatsapp-session');`,
729
+ ` let pairSock = makeWASocket({`,
730
+ ` version: [2, 2413, 1],`,
731
+ ` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
732
+ ` printQRInTerminal: false,`,
733
+ ` syncFullHistory: false,`,
734
+ ` markOnlineOnConnect: false,`,
735
+ ` generateHighQualityLinkPreview: true,`,
736
+ ` defaultQueryTimeoutMs: 60000,`,
737
+ ` keepAliveIntervalMs: 50000,`,
738
+ ` logger: __waSilentLogger,`,
739
+ ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
740
+ ` });`,
741
+ ` pairSock.ev.on('creds.update', saveCreds);`,
742
+ ` pairSock.ev.on('messages.upsert', async (upsert) => {`,
743
+ ` try {`,
744
+ ` if (!upsert || upsert.type !== 'notify') return;`,
745
+ ` for (const msg of upsert.messages || []) {`,
746
+ ` const key = msg.key || {};`,
747
+ ` if (key.fromMe) continue;`,
748
+ ` const chat = key.remoteJid;`,
749
+ ` if (!chat || chat === 'status@broadcast') continue;`,
750
+ ` const content = __waUnwrap(msg.message);`,
751
+ ` const message = {`,
752
+ ` text: __waExtractText(content),`,
753
+ ` type: __waMessageType(content),`,
754
+ ` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
755
+ ` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
756
+ ` buttonId: __waButtonId(content),`,
757
+ ` chat,`,
758
+ ` sender: key.participant || chat,`,
759
+ ` name: msg.pushName || null,`,
760
+ ` id: key.id || null,`,
761
+ ` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
762
+ ` isGroup: chat.endsWith('@g.us'),`,
763
+ ` raw: msg,`,
764
+ ` download: (dest) => __waDownload(msg, dest),`,
765
+ ` };`,
766
+ ` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
767
+ ` for (const handler of handlers) {`,
768
+ ` await handler(ctx);`,
769
+ ` }`,
770
+ ` }`,
771
+ ` } catch (error) {`,
772
+ ` console.error(error);`,
773
+ ` }`,
774
+ ` });`,
775
+ ` if (onCode) {`,
776
+ ` await new Promise((resolve) => {`,
777
+ ` let attempts = 0;`,
778
+ ` const requestCode = async () => {`,
779
+ ` if (!pairSock || attempts >= 4) { resolve(); return; }`,
780
+ ` attempts += 1;`,
781
+ ` try {`,
782
+ ` pairSock.requestPairingCode(digits).then((rawCode) => {`,
783
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
784
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
785
+ ` onCode(pretty);`,
786
+ ` resolve();`,
787
+ ` }).catch((error) => {`,
788
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
789
+ ` resolve();`,
790
+ ` });`,
791
+ ` } catch (_) { resolve(); }`,
792
+ ` };`,
793
+ ` setTimeout(async () => {`,
794
+ ` await requestCode();`,
795
+ ` setTimeout(requestCode, 4000);`,
796
+ ` }, 2000);`,
797
+ ` });`,
798
+ ` } else {`,
799
+ ` await new Promise((resolve) => {`,
800
+ ` let attempts = 0;`,
801
+ ` const requestCode = async () => {`,
802
+ ` if (!pairSock || attempts >= 4) { resolve(); return; }`,
803
+ ` attempts += 1;`,
804
+ ` try {`,
805
+ ` pairSock.requestPairingCode(digits).then((rawCode) => {`,
806
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
807
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
808
+ ` resolve();`,
809
+ ` }).catch((error) => {`,
810
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
811
+ ` resolve();`,
812
+ ` });`,
813
+ ` } catch (_) { resolve(); }`,
814
+ ` };`,
815
+ ` setTimeout(async () => {`,
816
+ ` await requestCode();`,
817
+ ` setTimeout(requestCode, 4000);`,
818
+ ` }, 2000);`,
819
+ ` });`,
820
+ ` }`,
821
+ ` return digits;`,
822
+ ` }`,
823
+ ` return { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload };`,
542
824
  `})();`,
543
825
  ].join('\n'),
544
826
  // v2.1.1 — HTTP client runtime on the global fetch API (Node.js 18+).
@@ -1032,6 +1314,37 @@ const BUILTIN_DECLARATIONS = {
1032
1314
  ` const result = await coll.insertOne(doc);`,
1033
1315
  ` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
1034
1316
  ` };`,
1317
+ ` __mongoDb.__update = async function(sql, params) {`,
1318
+ ` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
1319
+ ` const m = String(sql).match(/^\\s*UPDATE\\s+(\\w+)\\s+SET\\s+(.+?)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
1320
+ ` if (!m) throw new Error('MongoDB update: use UPDATE collection SET field = ? WHERE field = ?');`,
1321
+ ` const [, collection, setClause, whereClause] = m;`,
1322
+ ` const coll = __mongoCollection(collection);`,
1323
+ ` const filter = {};`,
1324
+ ` if (whereClause) {`,
1325
+ ` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1326
+ ` if (wm) filter[wm[1]] = params[1] !== undefined ? params[1] : params[0];`,
1327
+ ` }`,
1328
+ ` const updateDoc = {};`,
1329
+ ` const sm = setClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1330
+ ` if (sm) updateDoc[sm[1]] = params[0];`,
1331
+ ` const result = await coll.updateMany(filter, { $set: updateDoc });`,
1332
+ ` return { rowCount: result.modifiedCount };`,
1333
+ ` };`,
1334
+ ` __mongoDb.__delete = async function(sql, params) {`,
1335
+ ` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
1336
+ ` const m = String(sql).match(/^\\s*DELETE\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
1337
+ ` if (!m) throw new Error('MongoDB delete: use DELETE FROM collection WHERE field = ?');`,
1338
+ ` const [, collection, whereClause] = m;`,
1339
+ ` const coll = __mongoCollection(collection);`,
1340
+ ` const filter = {};`,
1341
+ ` if (whereClause) {`,
1342
+ ` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1343
+ ` if (wm) filter[wm[1]] = params[0];`,
1344
+ ` }`,
1345
+ ` const result = await coll.deleteMany(filter);`,
1346
+ ` return { rowCount: result.deletedCount };`,
1347
+ ` };`,
1035
1348
  ` __mongoDb.__execute = async function(sql, params) {`,
1036
1349
  ` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
1037
1350
  ` };`,
@@ -1195,6 +1508,27 @@ const BUILTIN_DECLARATIONS = {
1195
1508
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1196
1509
  readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1197
1510
  writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
1511
+ // v2.4.0 — dependency-free SVG image and visualization helpers.
1512
+ svgImage: (args, context) => {
1513
+ ensureBuiltin(context, 'visualization');
1514
+ return `__svgImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1515
+ },
1516
+ barChart: (args, context) => {
1517
+ ensureBuiltin(context, 'visualization');
1518
+ return `__barChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1519
+ },
1520
+ lineChart: (args, context) => {
1521
+ ensureBuiltin(context, 'visualization');
1522
+ return `__lineChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1523
+ },
1524
+ saveImage: (args, context) => {
1525
+ ensureBuiltin(context, 'visualization');
1526
+ return `__saveImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1527
+ },
1528
+ imageDataUri: (args, context) => {
1529
+ ensureBuiltin(context, 'visualization');
1530
+ return `__imageDataUri(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1531
+ },
1198
1532
  fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
1199
1533
  read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1200
1534
  sleep: (args, context) => `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${generateExpr(args[0], context)})`,
@@ -2281,14 +2615,13 @@ function emitSqlCall(kind, sql, params, indent, context) {
2281
2615
  }
2282
2616
  if (_sqlDriver === 'mongo') {
2283
2617
  markAsync(context);
2284
- // For MongoDB, we delegate to helper functions that parse SQL-like syntax
2285
- // into MongoDB operations. This is a simplified approach.
2286
- // All MongoDB operations are async, so always await them.
2287
2618
  return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
2288
2619
  }
2289
2620
  switch (kind) {
2290
2621
  case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
2291
2622
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
2623
+ case 'update': return `db.prepare(\`${sql}\`).run(${args})`;
2624
+ case 'delete': return `db.prepare(\`${sql}\`).run(${args})`;
2292
2625
  case 'execute': return `db.exec(\`${sql}\`)`;
2293
2626
  default: throw new Error(`Unknown SQL kind "${kind}".`);
2294
2627
  }
@@ -3235,9 +3568,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3235
3568
  return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
3236
3569
 
3237
3570
  case 'InsertStatement':
3571
+ return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
3238
3572
  case 'UpdateStatement':
3573
+ return `${indent}${emitSqlCall('update', node.sql, node.params, indent, context)};`;
3239
3574
  case 'DeleteStatement':
3240
- return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
3575
+ return `${indent}${emitSqlCall('delete', node.sql, node.params, indent, context)};`;
3241
3576
 
3242
3577
  case 'ExecuteStatement':
3243
3578
  return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
@@ -3245,7 +3580,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3245
3580
  // v2.1.0 — remember <name> as query|insert|update|delete … done
3246
3581
  case 'RememberSqlStatement': {
3247
3582
  const kind = node.kind === 'query' ? 'query'
3248
- : node.kind === 'execute' ? 'execute' : 'write';
3583
+ : node.kind === 'execute' ? 'execute'
3584
+ : node.kind === 'update' ? 'update'
3585
+ : node.kind === 'delete' ? 'delete'
3586
+ : 'write';
3249
3587
  return `${indent}let ${node.name} = ${emitSqlCall(kind, node.sql, node.params, indent, context)};`;
3250
3588
  }
3251
3589
 
@@ -3317,26 +3655,32 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3317
3655
 
3318
3656
  // whatsapp bot … done — starts the Baileys runtime with the declared
3319
3657
  // auth folder and login mode, then registers every "on message" handler.
3658
+ // When no login line is present (login is null), only registers handlers
3659
+ // without auto-starting — used by hybrid bots that pair on-demand.
3320
3660
  case 'WhatsAppBotStatement': {
3321
3661
  ensureBuiltin(context, 'whatsapp');
3322
3662
  markAsync(context);
3323
- // v2.1.2 — the pairing phone may be a compile-time literal or any
3324
- // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
3325
- // are normalized/validated by __waNormalizePhone at startup.
3326
- let loginArg;
3327
- if (node.login.mode === 'pairing') {
3328
- loginArg = node.login.phoneExpr != null
3329
- ? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
3330
- : `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
3331
- } else {
3332
- loginArg = `{ mode: 'qr' }`;
3663
+ const lines = [];
3664
+ if (node.login) {
3665
+ // v2.1.2 — the pairing phone may be a compile-time literal or any
3666
+ // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
3667
+ // are normalized/validated by __waNormalizePhone at startup.
3668
+ let loginArg;
3669
+ if (node.login.mode === 'pairing') {
3670
+ loginArg = node.login.phoneExpr != null
3671
+ ? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
3672
+ : `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
3673
+ } else {
3674
+ loginArg = `{ mode: 'qr' }`;
3675
+ }
3676
+ lines.push(
3677
+ `${indent}await __whatsappStart({`,
3678
+ `${indent} folder: ${JSON.stringify(node.authFolder)},`,
3679
+ `${indent} login: ${loginArg},`,
3680
+ ...(node.baileysModule ? [`${indent} baileys: ${JSON.stringify(node.baileysModule)},`] : []),
3681
+ `${indent}});`,
3682
+ );
3333
3683
  }
3334
- const lines = [
3335
- `${indent}await __whatsappStart({`,
3336
- `${indent} folder: ${JSON.stringify(node.authFolder)},`,
3337
- `${indent} login: ${loginArg},`,
3338
- `${indent}});`,
3339
- ];
3340
3684
  for (const handlerNode of node.handlers) {
3341
3685
  const generated = generateStatement(handlerNode, indent, context);
3342
3686
  if (generated) lines.push(generated);
@@ -3344,6 +3688,23 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3344
3688
  return lines.join('\n');
3345
3689
  }
3346
3690
 
3691
+ // pair whatsapp "<phone>" — on-demand WhatsApp pairing session.
3692
+ // When _inTelegram is true, relays the pairing code and connection status
3693
+ // to the Telegram chat via ctx.chatId.
3694
+ case 'WhatsAppPairStatement': {
3695
+ ensureBuiltin(context, 'whatsapp');
3696
+ markAsync(context);
3697
+ const phoneArg = node.phone.type === 'StringLiteral'
3698
+ ? JSON.stringify(node.phone.value)
3699
+ : generateExpr(node.phone, context);
3700
+ if (_inTelegram) {
3701
+ return [
3702
+ `${indent}await __whatsappPair(${phoneArg}, (code) => Telegram.sendMessage(ctx.chatId, "WhatsApp pairing code: " + code), () => Telegram.sendMessage(ctx.chatId, "WhatsApp connected."));`,
3703
+ ].join('\n');
3704
+ }
3705
+ return `${indent}await __whatsappPair(${phoneArg}, null, null);`;
3706
+ }
3707
+
3347
3708
  // on message … done — registers the handler that receives each incoming
3348
3709
  // WhatsApp message as a normalized PlainScript record on `message`.
3349
3710
  case 'WhatsAppOnMessageStatement': {
@@ -3369,6 +3730,16 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3369
3730
  ensureBuiltin(context, 'whatsapp');
3370
3731
  return `${indent}console.log(__waCtx.message);`;
3371
3732
 
3733
+ // v2.14 — download "<path>" — saves the current message's media to a file.
3734
+ // Handler-only by design: outside "on message" there is no message media.
3735
+ case 'WhatsAppDownloadStatement':
3736
+ if (!_inWhatsApp) {
3737
+ throw new Error('"download" can only be used inside an "on message" block to save the current message\'s media.\n\nExample:\n whatsapp bot\n on message\n if message.type is "image"\n download "media/photo.jpg"\n reply "Saved your photo!"\n done\n done\n done');
3738
+ }
3739
+ ensureBuiltin(context, 'whatsapp');
3740
+ markAsync(context);
3741
+ return `${indent}await __whatsappDownload(__waCtx.message, ${JSON.stringify(node.filePath)});`;
3742
+
3372
3743
  // v2.1.0 — mail, cache, scheduling, background jobs, websocket
3373
3744
 
3374
3745
  case 'MailTransportStatement': {