plainscript-lang 0.1.7-latest

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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +815 -0
  3. package/compiler/bundler.js +86 -0
  4. package/compiler/cli.js +843 -0
  5. package/compiler/dependency-detector.js +173 -0
  6. package/compiler/formatter.js +170 -0
  7. package/compiler/generator.js +2032 -0
  8. package/compiler/lexer.js +413 -0
  9. package/compiler/parser.js +2077 -0
  10. package/compiler/version.js +6 -0
  11. package/docs/PLINJS_SPEC.md +1051 -0
  12. package/docs/index.html +2287 -0
  13. package/docs/logo.jpg +0 -0
  14. package/docs/website/index.html +1500 -0
  15. package/docs/website/script.js +197 -0
  16. package/docs/website/style.css +1117 -0
  17. package/examples/arrays.pln +13 -0
  18. package/examples/cache-and-jobs.pln +29 -0
  19. package/examples/database.pln +41 -0
  20. package/examples/day2.pln +7 -0
  21. package/examples/day3.pln +11 -0
  22. package/examples/deployment.pln +12 -0
  23. package/examples/email-send.pln +22 -0
  24. package/examples/expressions.pln +40 -0
  25. package/examples/football-backend/app.pln +90 -0
  26. package/examples/hello.pln +3 -0
  27. package/examples/id-verification/app.pln +29 -0
  28. package/examples/id-verification/make-sample-id.js +123 -0
  29. package/examples/loops.pln +17 -0
  30. package/examples/objects.pln +12 -0
  31. package/examples/rest-api-fetch.pln +94 -0
  32. package/examples/rest-api.pln +68 -0
  33. package/examples/scheduled-tasks.pln +23 -0
  34. package/examples/server.pln +25 -0
  35. package/examples/start.pln +2 -0
  36. package/examples/stdlib.pln +41 -0
  37. package/examples/telegram-bot.pln +42 -0
  38. package/examples/web-app.pln +20 -0
  39. package/examples/websocket-server.pln +27 -0
  40. package/examples/whatsapp-bot/pairing.pln +17 -0
  41. package/examples/whatsapp-bot/qr.pln +8 -0
  42. package/package.json +47 -0
@@ -0,0 +1,2032 @@
1
+ // Generator: converts a PlainScript AST into JavaScript source code.
2
+
3
+ const vm = require('vm');
4
+ const { splitPackageSpec } = require('./dependency-detector');
5
+
6
+ // Known runtime packages and their require() statements.
7
+ const KNOWN_PACKAGES = {
8
+ express: `const express = require('express');`,
9
+ sqlite: `const Database = require('better-sqlite3');`,
10
+ fs: `const fs = require('fs');`,
11
+ path: `const path = require('path');`,
12
+ axios: `const axios = require('axios');`,
13
+ chalk: `const chalk = require('chalk');`,
14
+ // v2.1.0 — PostgreSQL driver behind the friendly "postgres" name.
15
+ postgres: `const { Pool } = require('pg');`,
16
+ };
17
+
18
+ // PlainScript module names whose npm package name differs from the PlainScript name.
19
+ // Used to de-duplicate runtime requires across aliases (RFC-0011 §22).
20
+ const NPM_NAME = {
21
+ sqlite: 'better-sqlite3',
22
+ postgres: 'pg',
23
+ // v2.1.1 — portable WebAssembly SQLite engine used by the "database"
24
+ // statement as an automatic fallback (or explicit choice) when
25
+ // better-sqlite3's native binding is unavailable.
26
+ 'wasm-sqlite': 'sql.js',
27
+ };
28
+
29
+ // JavaScript reserved words that cannot be used as a const binding name.
30
+ const JS_RESERVED = new Set([
31
+ 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger',
32
+ 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally',
33
+ 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface',
34
+ 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static',
35
+ 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while',
36
+ 'with', 'yield',
37
+ ]);
38
+
39
+ const BUILTIN_DECLARATIONS = {
40
+ fs: `const fs = require('fs');`,
41
+ crypto: `const crypto = require('crypto');`,
42
+ // v1.1.1 — ask runtime (RFC-0011 §14)
43
+ ask: [
44
+ `const readline = require('readline');`,
45
+ `async function __ask(prompt = '') {`,
46
+ ` const rl = readline.createInterface({ input: process.stdin, output: process.stdout });`,
47
+ ` try {`,
48
+ ` return await new Promise((resolve) => rl.question(prompt, resolve));`,
49
+ ` } finally {`,
50
+ ` rl.close();`,
51
+ ` }`,
52
+ `}`,
53
+ ].join('\n'),
54
+ // v2.0.1 — OCR runtime (tesseract.js). Extracts text from an image file.
55
+ // The worker is created per call and always terminated, so repeated ocr
56
+ // statements do not leak workers.
57
+ ocr: [
58
+ `const { createWorker } = require('tesseract.js');`,
59
+ `async function __ocr(imagePath, lang) {`,
60
+ ` const worker = await createWorker(lang || 'eng');`,
61
+ ` try {`,
62
+ ` const { data } = await worker.recognize(imagePath);`,
63
+ ` return data.text;`,
64
+ ` } finally {`,
65
+ ` await worker.terminate();`,
66
+ ` }`,
67
+ `}`,
68
+ ].join('\n'),
69
+ // v2.1.0 — request validation runtime. Returns the names of required
70
+ // fields whose value is missing (undefined/null/empty string) in data.
71
+ validation: [
72
+ `function __validate(data, fields) {`,
73
+ ` return (fields || []).filter((field) => {`,
74
+ ` const value = data == null ? undefined : data[field];`,
75
+ ` return value === undefined || value === null || value === '';`,
76
+ ` });`,
77
+ `}`,
78
+ ].join('\n'),
79
+ // v2.1.0 — email runtime (nodemailer). One transport per program; sending
80
+ // fails with a teaching error when no transport was configured.
81
+ mailer: [
82
+ `const nodemailer = require('nodemailer');`,
83
+ `let __mailTransport = null;`,
84
+ `function __mailCreate(options) { __mailTransport = nodemailer.createTransport(options); }`,
85
+ `async function __mailSend(options) {`,
86
+ ` if (!__mailTransport) throw new Error('Email: no transport configured. Use "mail transport ... done" before "send mail".');`,
87
+ ` return __mailTransport.sendMail(options);`,
88
+ `}`,
89
+ ].join('\n'),
90
+ // v2.1.0 — cron scheduling runtime (croner). Zero dependencies, validates
91
+ // expressions at registration time.
92
+ scheduler: [
93
+ `const cron = require('croner');`,
94
+ ].join('\n'),
95
+ // v2.1.0 — WebSocket runtime (ws). Standalone server bound to its own port.
96
+ websocket: [
97
+ `const { WebSocketServer } = require('ws');`,
98
+ `function __wsServerCreate(port, handlers) {`,
99
+ ` const server = new WebSocketServer({ port });`,
100
+ ` server.on('connection', (socket) => {`,
101
+ ` if (handlers.connect) handlers.connect(socket);`,
102
+ ` socket.on('message', (raw) => {`,
103
+ ` if (handlers.message) handlers.message(socket, raw.toString());`,
104
+ ` });`,
105
+ ` socket.on('close', () => { if (handlers.disconnect) handlers.disconnect(socket); });`,
106
+ ` });`,
107
+ ` return server;`,
108
+ `}`,
109
+ `function __wsSend(socket, value) {`,
110
+ ` socket.send(typeof value === 'string' ? value : JSON.stringify(value));`,
111
+ `}`,
112
+ `function __wsBroadcast(server, value) {`,
113
+ ` const text = typeof value === 'string' ? value : JSON.stringify(value);`,
114
+ ` for (const client of server.clients) {`,
115
+ ` if (client.readyState === 1) client.send(text);`,
116
+ ` }`,
117
+ `}`,
118
+ ].join('\n'),
119
+ // v2.1.0 — cache runtime (Redis via the redis package). The client is
120
+ // created by the "cache" statement; accessors fail with a teaching error
121
+ // when no cache was configured.
122
+ cache: [
123
+ `let __cache = null;`,
124
+ `function __cacheClient() {`,
125
+ ` if (!__cache) throw new Error('Cache: no cache configured. Add a cache "<redis-url>" statement first.');`,
126
+ ` return __cache;`,
127
+ `}`,
128
+ ].join('\n'),
129
+ // v2.1.1 — WhatsApp runtime (@whiskeysockets/baileys behind the
130
+ // "whatsapp bot" block). Everything Baileys-shaped stays in here: socket
131
+ // creation, auth-state files, QR rendering, pairing codes, connection
132
+ // lifecycle and messages.upsert normalization. PlainScript programs only ever
133
+ // see __whatsappStart/__whatsappOnMessage/__whatsappReply.
134
+ whatsapp: [
135
+ `const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {`,
136
+ ` let sock = null;`,
137
+ ` const handlers = [];`,
138
+ ` const __waSilentLogger = (() => {`,
139
+ ` const noop = () => {};`,
140
+ ` const logger = { level: 'silent', child: () => logger, trace: noop, debug: noop, info: noop, warn: noop, error: noop, fatal: noop };`,
141
+ ` return logger;`,
142
+ ` })();`,
143
+ ` function __waNormalizePhone(raw) {`,
144
+ ` const digits = String(raw == null ? '' : raw).replace(/[\\s()+\\-.]/g, '');`,
145
+ ` if (!/^[0-9]+$/.test(digits) || digits.length < 8 || digits.length > 15) {`,
146
+ ` throw new Error('WhatsApp: "' + raw + '" is not a valid pairing phone number. Use the full international number, digits only (country code included, no "+").');`,
147
+ ` }`,
148
+ ` return digits;`,
149
+ ` }`,
150
+ ` function __waUnwrap(content) {`,
151
+ ` let node = content;`,
152
+ ` for (let depth = 0; node && depth < 5; depth++) {`,
153
+ ` const inner = (node.ephemeralMessage || node.viewOnceMessage || node.viewOnceMessageV2 || node.documentWithCaptionMessage || {}).message;`,
154
+ ` if (!inner) break;`,
155
+ ` node = inner;`,
156
+ ` }`,
157
+ ` return node;`,
158
+ ` }`,
159
+ ` function __waExtractText(content) {`,
160
+ ` if (!content) return '';`,
161
+ ` return String(` +
162
+ `(content.conversation || (content.extendedTextMessage || {}).text || ` +
163
+ `(content.imageMessage || {}).caption || (content.videoMessage || {}).caption || ` +
164
+ `(content.documentMessage || {}).caption) || '');`,
165
+ ` }`,
166
+ ` async function __whatsappReply(chat, value) {`,
167
+ ` if (!sock) throw new Error('WhatsApp: cannot reply because the bot is not connected yet.');`,
168
+ ` const text = typeof value === 'string' ? value : JSON.stringify(value);`,
169
+ ` return sock.sendMessage(chat, { text });`,
170
+ ` }`,
171
+ ` function __whatsappOnMessage(handler) { handlers.push(handler); }`,
172
+ ` async function __whatsappStart(options) {`,
173
+ ` const baileys = require('@whiskeysockets/baileys');`,
174
+ ` const makeWASocket = baileys.default;`,
175
+ ` const { useMultiFileAuthState, fetchLatestBaileysVersion, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
176
+ ` const folder = options.folder || 'plainscript-whatsapp-auth';`,
177
+ ` const mode = options.login && options.login.mode === 'pairing' ? 'pairing' : 'qr';`,
178
+ ` const pairingPhone = mode === 'pairing' ? __waNormalizePhone(options.login.phone) : null;`,
179
+ ` let connecting = false;`,
180
+ ` const connect = async () => {`,
181
+ ` if (connecting) return;`,
182
+ ` connecting = true;`,
183
+ ` try {`,
184
+ // Auth/session persistence: useMultiFileAuthState stores credentials in
185
+ // the folder from `auth "<name>"`; saveCreds writes every update back.
186
+ ` const { state, saveCreds } = await useMultiFileAuthState(folder);`,
187
+ ` let version;`,
188
+ ` try { version = (await fetchLatestBaileysVersion()).version; } catch (_) {}`,
189
+ // Proven socket settings: these exact options are required for pairing
190
+ // codes to survive WhatsApp's handshake without a 428 connection close.
191
+ ` sock = makeWASocket({`,
192
+ ` ...(version ? { version } : {}),`,
193
+ ` browser: ['Ubuntu', 'Edge', '20.0.04'],`,
194
+ ` printQRInTerminal: false,`,
195
+ ` syncFullHistory: false,`,
196
+ ` markOnlineOnConnect: false,`,
197
+ ` defaultQueryTimeoutMs: 60000,`,
198
+ ` keepAliveIntervalMs: 30000,`,
199
+ ` logger: __waSilentLogger,`,
200
+ ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
201
+ ` });`,
202
+ ` sock.ev.on('creds.update', saveCreds);`,
203
+ // Pairing codes are requested two seconds after socket creation — asking
204
+ // earlier aborts the link attempt. PlainScript calls requestPairingCode(phone)
205
+ // with no custom suffix; the number was validated at compile time.
206
+ ` if (mode === 'pairing' && !state.creds.registered) {`,
207
+ ` setTimeout(() => {`,
208
+ ` if (!sock) return;`,
209
+ ` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
210
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
211
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
212
+ ` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
213
+ ` }).catch((error) => {`,
214
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
215
+ ` });`,
216
+ ` }, 2000);`,
217
+ ` }`,
218
+ // Connection lifecycle: the QR code while linking, a friendly note on
219
+ // open, and automatic reconnection on every close except loggedOut.
220
+ ` sock.ev.on('connection.update', async (update) => {`,
221
+ ` try {`,
222
+ ` const statusCode = update.lastDisconnect && update.lastDisconnect.error && (`,
223
+ ` (update.lastDisconnect.error.output || {}).statusCode != null`,
224
+ ` ? update.lastDisconnect.error.output.statusCode`,
225
+ ` : (((update.lastDisconnect.error.error || {}).output || {}).statusCode));`,
226
+ ` if (update.qr && mode === 'qr') {`,
227
+ ` console.log('Scan this QR code with WhatsApp (Settings > Linked devices > Link a device):');`,
228
+ ` try {`,
229
+ ` require('qrcode-terminal').generate(update.qr, { small: true });`,
230
+ ` } catch (_) {`,
231
+ ` console.log(update.qr);`,
232
+ ` }`,
233
+ ` }`,
234
+ ` if (update.connection === 'open') {`,
235
+ ` console.log('WhatsApp connected.');`,
236
+ ` }`,
237
+ ` if (update.connection === 'close') {`,
238
+ ` sock = null;`,
239
+ ` if (statusCode === DisconnectReason.loggedOut) {`,
240
+ ` console.error('WhatsApp signed out. Delete the "' + folder + '" folder and restart to link this device again.');`,
241
+ ` } else {`,
242
+ ` console.error('WhatsApp connection closed (' + statusCode + '). Reconnecting in 3 seconds...');`,
243
+ ` setTimeout(() => { connect().catch((error) => console.error('WhatsApp reconnect failed: ' + error.message)); }, 3000);`,
244
+ ` }`,
245
+ ` }`,
246
+ ` } catch (error) {`,
247
+ ` console.error('WhatsApp connection error: ' + error.message);`,
248
+ ` }`,
249
+ ` });`,
250
+ // Incoming messages: only fresh ("notify") deliveries, never our own,
251
+ // never status broadcasts. Each message becomes a PlainScript record.
252
+ ` sock.ev.on('messages.upsert', async (upsert) => {`,
253
+ ` try {`,
254
+ ` if (!upsert || upsert.type !== 'notify') return;`,
255
+ ` for (const msg of upsert.messages || []) {`,
256
+ ` const key = msg.key || {};`,
257
+ ` if (key.fromMe) continue;`,
258
+ ` const chat = key.remoteJid;`,
259
+ ` if (!chat || chat === 'status@broadcast') continue;`,
260
+ ` const message = {`,
261
+ ` text: __waExtractText(__waUnwrap(msg.message)),`,
262
+ ` chat,`,
263
+ ` sender: key.participant || chat,`,
264
+ ` name: msg.pushName || null,`,
265
+ ` id: key.id || null,`,
266
+ ` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
267
+ ` isGroup: chat.endsWith('@g.us'),`,
268
+ ` };`,
269
+ ` const ctx = { chat, message, reply: (value) => __whatsappReply(chat, value) };`,
270
+ ` for (const handler of handlers) {`,
271
+ ` await handler(ctx);`,
272
+ ` }`,
273
+ ` }`,
274
+ ` } catch (error) {`,
275
+ ` console.error(error);`,
276
+ ` }`,
277
+ ` });`,
278
+ ` } finally {`,
279
+ ` connecting = false;`,
280
+ ` }`,
281
+ ` };`,
282
+ ` await connect();`,
283
+ ` }`,
284
+ ` return { __whatsappStart, __whatsappOnMessage, __whatsappReply };`,
285
+ `})();`,
286
+ ].join('\n'),
287
+ // v2.1.1 — HTTP client runtime on the global fetch API (Node.js 18+).
288
+ // Every response becomes a PlainScript-friendly record: { ok, status, headers,
289
+ // data }, where data holds parsed JSON when the content type says JSON.
290
+ http: [
291
+ `async function __httpRequest(method, url, options = {}) {`,
292
+ ` if (typeof fetch !== 'function') {`,
293
+ ` throw new Error('HTTP requests need Node.js 18 or newer (global fetch is missing). Current version: ' + process.version);`,
294
+ ` }`,
295
+ ` const timeoutMs = options.timeoutMs == null ? 30000 : Number(options.timeoutMs);`,
296
+ ` const controller = new AbortController();`,
297
+ ` const timer = setTimeout(() => controller.abort(), timeoutMs);`,
298
+ ` let response;`,
299
+ ` try {`,
300
+ ` response = await fetch(url, {`,
301
+ ` method,`,
302
+ ` headers: options.headers,`,
303
+ ` body: options.body == null ? undefined`,
304
+ ` : (typeof options.body === 'string' || Buffer.isBuffer(options.body) ? options.body : JSON.stringify(options.body)),`,
305
+ ` signal: controller.signal,`,
306
+ ` });`,
307
+ ` } catch (error) {`,
308
+ ` clearTimeout(timer);`,
309
+ ` if (error.name === 'AbortError') {`,
310
+ ` throw new Error(method + ' ' + url + ' timed out after ' + timeoutMs + 'ms.');`,
311
+ ` }`,
312
+ ` throw new Error(method + ' ' + url + ' failed: ' + error.message);`,
313
+ ` }`,
314
+ ` clearTimeout(timer);`,
315
+ ` const text = await response.text();`,
316
+ ` let data = text;`,
317
+ ` const contentType = response.headers.get('content-type') || '';`,
318
+ ` if (contentType.includes('json')) {`,
319
+ ` try { data = JSON.parse(text); } catch (_) {}`,
320
+ ` }`,
321
+ ` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
322
+ `}`,
323
+ ].join('\n'),
324
+ // v2.1.1 — file upload runtime (multer behind "accept uploads"). Files are
325
+ // held in memory by default or written to disk when a folder is given.
326
+ // Normalised records expose: name, type, size, data (buffer) and path.
327
+ uploads: [
328
+ `function __uploads(options = {}) {`,
329
+ ` const multer = require('multer');`,
330
+ ` if (options.folder) require('fs').mkdirSync(options.folder, { recursive: true });`,
331
+ ` const config = {`,
332
+ ` storage: options.folder`,
333
+ ` ? multer.diskStorage({ destination: (_req, _file, cb) => cb(null, options.folder) })`,
334
+ ` : multer.memoryStorage(),`,
335
+ ` };`,
336
+ ` if (options.limitBytes != null) config.limits = { fileSize: options.limitBytes };`,
337
+ ` if (options.mimes && options.mimes.length) {`,
338
+ ` config.fileFilter = (_req, file, cb) => {`,
339
+ ` if (options.mimes.includes(file.mimetype)) return cb(null, true);`,
340
+ ` const error = new Error('Upload rejected: "' + file.originalname + '" has type "' + file.mimetype + '". Allowed types: ' + options.mimes.join(', '));`,
341
+ ` error.statusCode = 415;`,
342
+ ` return cb(error);`,
343
+ ` };`,
344
+ ` }`,
345
+ ` const handler = multer(config).any();`,
346
+ ` return (req, res, next) => {`,
347
+ ` handler(req, res, (error) => {`,
348
+ ` if (!error) return next();`,
349
+ ` const status = error.statusCode || (error.code === 'LIMIT_FILE_SIZE' ? 413 : 400);`,
350
+ ` const message = error.code === 'LIMIT_FILE_SIZE'`,
351
+ ` ? 'Upload rejected: file exceeds the size limit (' + options.limitBytes + ' bytes).'`,
352
+ ` : error.message;`,
353
+ ` res.status(status).json({ error: message });`,
354
+ ` });`,
355
+ ` };`,
356
+ `}`,
357
+ `function __normalizeUpload(file) {`,
358
+ ` if (!file) return null;`,
359
+ ` return { name: file.originalname, type: file.mimetype, size: file.size, data: file.buffer || null, path: file.path || null };`,
360
+ `}`,
361
+ `function __uploadedFile(req, field) {`,
362
+ ` return __normalizeUpload((req.files || []).find((f) => f.fieldname === field) || null);`,
363
+ `}`,
364
+ `function __uploadedFiles(req, field) {`,
365
+ ` return (req.files || []).filter((f) => f.fieldname === field).map(__normalizeUpload);`,
366
+ `}`,
367
+ ].join('\n'),
368
+ // v2.1.1 — cookie helpers shared by the cookie() accessor and the session
369
+ // runtime.
370
+ cookies: [
371
+ `function __parseCookies(header) {`,
372
+ ` const jar = {};`,
373
+ ` for (const part of String(header || '').split(';')) {`,
374
+ ` const index = part.indexOf('=');`,
375
+ ` if (index === -1) continue;`,
376
+ ` try {`,
377
+ ` jar[part.slice(0, index).trim()] = decodeURIComponent(part.slice(index + 1).trim());`,
378
+ ` } catch (_) {`,
379
+ ` jar[part.slice(0, index).trim()] = part.slice(index + 1).trim();`,
380
+ ` }`,
381
+ ` }`,
382
+ ` return jar;`,
383
+ `}`,
384
+ `function __cookieValue(req, name) {`,
385
+ ` const value = __parseCookies(req.headers.cookie)[String(name)];`,
386
+ ` return value === undefined ? null : value;`,
387
+ `}`,
388
+ ].join('\n'),
389
+ // v2.1.1 — session runtime. Cookie-signed session ids backed by an
390
+ // in-memory store (sessions reset when the server restarts).
391
+ sessions: [
392
+ `const __sessionStore = new Map();`,
393
+ `const __sessionsCrypto = require('crypto');`,
394
+ `function __enableSessions(secret) {`,
395
+ ` return (req, res, next) => {`,
396
+ ` const cookies = __parseCookies(req.headers.cookie);`,
397
+ ` req.__session = null;`,
398
+ ` const sid = cookies['plainscript.sid'];`,
399
+ ` if (sid && sid.startsWith('s:') && sid.indexOf('.', 2) !== -1) {`,
400
+ ` const dot = sid.indexOf('.', 2);`,
401
+ ` const id = sid.slice(2, dot);`,
402
+ ` const expected = __sessionsCrypto.createHmac('sha256', String(secret)).update(id).digest('base64url');`,
403
+ ` if (__sessionStore.has(id) && sid.slice(dot + 1) === expected) {`,
404
+ ` req.__session = __sessionStore.get(id);`,
405
+ ` }`,
406
+ ` }`,
407
+ ` if (!req.__session) {`,
408
+ ` const id = __sessionsCrypto.randomUUID();`,
409
+ ` req.__session = {};`,
410
+ ` __sessionStore.set(id, req.__session);`,
411
+ ` const signature = __sessionsCrypto.createHmac('sha256', String(secret)).update(id).digest('base64url');`,
412
+ ` res.setHeader('Set-Cookie', 'plainscript.sid=s:' + id + '.' + signature + '; Path=/; HttpOnly; SameSite=Lax');`,
413
+ ` }`,
414
+ ` next();`,
415
+ ` };`,
416
+ `}`,
417
+ `function __sessionOf(request) {`,
418
+ ` if (!request.__session) throw new Error('Sessions are not enabled. Add "enable sessions <secret>" before reading "session of request".');`,
419
+ ` return request.__session;`,
420
+ `}`,
421
+ `function __userOf(request) {`,
422
+ ` return request.__oauthUser || (request.__session && request.__session.user) || null;`,
423
+ `}`,
424
+ `function __destroySession(request, response) {`,
425
+ ` const sid = __parseCookies(request.headers.cookie)['plainscript.sid'];`,
426
+ ` if (sid && sid.startsWith('s:') && sid.indexOf('.', 2) !== -1) {`,
427
+ ` __sessionStore.delete(sid.slice(2, sid.indexOf('.', 2)));`,
428
+ ` }`,
429
+ ` response.setHeader('Set-Cookie', 'plainscript.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');`,
430
+ `}`,
431
+ ].join('\n'),
432
+ // v2.1.1 — authentication runtime: scrypt password hashing and signed
433
+ // tokens (HS256 format), both zero-dependency.
434
+ auth: [
435
+ `const __authCrypto = require('crypto');`,
436
+ `function hashPassword(password) {`,
437
+ ` const salt = __authCrypto.randomBytes(16).toString('hex');`,
438
+ ` const hash = __authCrypto.scryptSync(String(password), salt, 64).toString('hex');`,
439
+ ` return 'scrypt$' + salt + '$' + hash;`,
440
+ `}`,
441
+ `function checkPassword(password, stored) {`,
442
+ ` try {`,
443
+ ` const [scheme, salt, hash] = String(stored).split('$');`,
444
+ ` if (scheme !== 'scrypt' || !salt || !hash) return false;`,
445
+ ` const candidate = __authCrypto.scryptSync(String(password), salt, 64);`,
446
+ ` const expected = Buffer.from(hash, 'hex');`,
447
+ ` return candidate.length === expected.length && __authCrypto.timingSafeEqual(candidate, expected);`,
448
+ ` } catch (_) {`,
449
+ ` return false;`,
450
+ ` }`,
451
+ `}`,
452
+ `function createToken(payload, secret, expiresInSeconds) {`,
453
+ ` const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');`,
454
+ ` const now = Math.floor(Date.now() / 1000);`,
455
+ ` const claims = Object.assign({}, payload, { iat: now, exp: now + Math.floor(Number(expiresInSeconds == null ? 3600 : expiresInSeconds)) });`,
456
+ ` const header = encode({ alg: 'HS256', typ: 'JWT' });`,
457
+ ` const body = encode(claims);`,
458
+ ` const signature = __authCrypto.createHmac('sha256', String(secret)).update(header + '.' + body).digest('base64url');`,
459
+ ` return header + '.' + body + '.' + signature;`,
460
+ `}`,
461
+ `function readToken(token, secret) {`,
462
+ ` try {`,
463
+ ` const parts = String(token).split('.');`,
464
+ ` if (parts.length !== 3) return null;`,
465
+ ` const [header, body, signature] = parts;`,
466
+ ` const want = Buffer.from(__authCrypto.createHmac('sha256', String(secret)).update(header + '.' + body).digest('base64url'));`,
467
+ ` const given = Buffer.from(signature);`,
468
+ ` if (given.length !== want.length || !__authCrypto.timingSafeEqual(given, want)) return null;`,
469
+ ` const claims = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));`,
470
+ ` if (claims.exp != null && Math.floor(Date.now() / 1000) >= claims.exp) return null;`,
471
+ ` return claims;`,
472
+ ` } catch (_) {`,
473
+ ` return null;`,
474
+ ` }`,
475
+ `}`,
476
+ ].join('\n'),
477
+ // v2.1.1 — Google sign-in (OAuth 2.0 authorization code flow). Registers
478
+ // two endpoints: /auth/google (redirect) and the configured callback URL
479
+ // (token exchange + profile fetch), then redirects to the landing page.
480
+ oauth: [
481
+ `const __oauthCrypto = require('crypto');`,
482
+ `function __googleOAuth(app, options) {`,
483
+ ` const pendingStates = new Set();`,
484
+ ` app.get('/auth/google', (req, res) => {`,
485
+ ` const state = __oauthCrypto.randomUUID();`,
486
+ ` pendingStates.add(state);`,
487
+ ` const params = new URLSearchParams({`,
488
+ ` client_id: options.clientId,`,
489
+ ` redirect_uri: options.callbackUrl,`,
490
+ ` response_type: 'code',`,
491
+ ` scope: 'openid email profile',`,
492
+ ` state,`,
493
+ ` });`,
494
+ ` res.redirect('https://accounts.google.com/o/oauth2/v2/auth?' + params.toString());`,
495
+ ` });`,
496
+ ` app.get(new URL(options.callbackUrl).pathname, async (req, res) => {`,
497
+ ` try {`,
498
+ ` if (req.query.error) {`,
499
+ ` return res.status(401).json({ error: 'Google sign-in was cancelled.', detail: req.query.error });`,
500
+ ` }`,
501
+ ` if (!pendingStates.delete(req.query.state)) {`,
502
+ ` return res.status(400).json({ error: 'Sign-in link expired or state mismatch. Start again at /auth/google.' });`,
503
+ ` }`,
504
+ ` const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {`,
505
+ ` method: 'POST',`,
506
+ ` headers: { 'Content-Type': 'application/x-www-form-urlencoded' },`,
507
+ ` body: new URLSearchParams({`,
508
+ ` code: req.query.code,`,
509
+ ` client_id: options.clientId,`,
510
+ ` client_secret: options.clientSecret,`,
511
+ ` redirect_uri: options.callbackUrl,`,
512
+ ` grant_type: 'authorization_code',`,
513
+ ` }),`,
514
+ ` });`,
515
+ ` const tokens = await tokenResponse.json();`,
516
+ ` if (!tokens.access_token) {`,
517
+ ` return res.status(401).json({ error: 'Google token exchange failed.', detail: tokens.error_description || tokens.error });`,
518
+ ` }`,
519
+ ` const profileResponse = await fetch('https://openidconnect.googleapis.com/v1/userinfo', {`,
520
+ ` headers: { Authorization: 'Bearer ' + tokens.access_token },`,
521
+ ` });`,
522
+ ` const profile = await profileResponse.json();`,
523
+ ` req.__oauthUser = { email: profile.email, name: profile.name, picture: profile.picture, role: 'user' };`,
524
+ ` if (req.__session) req.__session.user = req.__oauthUser;`,
525
+ ` res.redirect(options.afterLogin || '/');`,
526
+ ` } catch (error) {`,
527
+ ` res.status(500).json({ error: 'Google sign-in failed: ' + error.message });`,
528
+ ` }`,
529
+ ` });`,
530
+ `}`,
531
+ ].join('\n'),
532
+ // v2.1.1 — per-IP request rate limiting with an in-memory sliding window.
533
+ ratelimit: [
534
+ `function __rateLimit(options) {`,
535
+ ` const hits = new Map();`,
536
+ ` const sweeper = setInterval(() => {`,
537
+ ` const cutoff = Date.now() - options.windowMs;`,
538
+ ` for (const [key, times] of hits) {`,
539
+ ` const recent = times.filter((t) => t > cutoff);`,
540
+ ` if (recent.length === 0) hits.delete(key); else hits.set(key, recent);`,
541
+ ` }`,
542
+ ` }, Math.min(options.windowMs, 60000));`,
543
+ ` if (sweeper.unref) sweeper.unref();`,
544
+ ` return (req, res, next) => {`,
545
+ ` const key = req.ip || (req.socket && req.socket.remoteAddress) || 'unknown';`,
546
+ ` const now = Date.now();`,
547
+ ` const times = (hits.get(key) || []).filter((t) => now - t < options.windowMs);`,
548
+ ` if (times.length >= options.max) {`,
549
+ ` return res.status(429).json({ error: 'Too many requests. Limit: ' + options.max + ' per ' + Math.round(options.windowMs / 1000) + ' seconds.' });`,
550
+ ` }`,
551
+ ` times.push(now);`,
552
+ ` hits.set(key, times);`,
553
+ ` next();`,
554
+ ` };`,
555
+ `}`,
556
+ ].join('\n'),
557
+ // v2.1.1 — pause helper for "retry N times every N seconds".
558
+ retry: [
559
+ `const __retrySleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));`,
560
+ ].join('\n'),
561
+ // v2.1.1 — SQLite runtime with a portable engine chain. Default order:
562
+ // better-sqlite3 (native binding) first, sql.js (WebAssembly) as fallback.
563
+ // Both engines are wrapped in the same tiny synchronous surface that PlainScript
564
+ // generates (prepare().all()/.run(), exec(), transaction()), so compiled
565
+ // database code is identical either way. The WebAssembly engine persists
566
+ // the whole database back to disk after every write.
567
+ sqlite: [
568
+ `let __sqliteNative = null;`,
569
+ `let __sqliteNativeReason = '';`,
570
+ `async function __dbOpen(file, mode) {`,
571
+ ` if (mode !== 'wasm') {`,
572
+ ` const native = __sqliteLoadNative();`,
573
+ ` if (native) return __sqliteWrapNative(new native(file));`,
574
+ ` if (mode === 'native') {`,
575
+ ` throw new Error('Database: the native SQLite engine is not usable on this machine (' + __sqliteNativeReason + ').\\nFix the better-sqlite3 build, or run anywhere with:\\n database "' + file + '" using "wasm"');`,
576
+ ` }`,
577
+ ` console.error('PlainScript: native SQLite unavailable (' + __sqliteNativeReason + '); using the WebAssembly engine instead.');`,
578
+ ` }`,
579
+ ` const initSqlJs = require('sql.js');`,
580
+ ` const SQL = await initSqlJs();`,
581
+ ` let raw;`,
582
+ ` try {`,
583
+ ` raw = new SQL.Database(require('fs').readFileSync(file));`,
584
+ ` } catch (_) {`,
585
+ ` raw = new SQL.Database();`,
586
+ ` }`,
587
+ ` return __sqliteWrapWasm(raw, file);`,
588
+ `}`,
589
+ `function __sqliteLoadNative() {`,
590
+ ` if (__sqliteNative !== null) return __sqliteNative;`,
591
+ ` try {`,
592
+ ` const Database = require('better-sqlite3');`,
593
+ ` const probe = new Database(':memory:');`,
594
+ ` probe.close();`,
595
+ ` __sqliteNative = Database;`,
596
+ ` } catch (error) {`,
597
+ ` __sqliteNative = false;`,
598
+ ` __sqliteNativeReason = error.message;`,
599
+ ` }`,
600
+ ` return __sqliteNative;`,
601
+ `}`,
602
+ `function __sqliteWrapNative(db) {`,
603
+ ` return {`,
604
+ ` prepare: (sql) => db.prepare(sql),`,
605
+ ` exec: (sql) => db.exec(sql),`,
606
+ // Pass through better-sqlite3 semantics: transaction(fn) returns a
607
+ // callable that runs fn inside BEGIN/COMMIT (the generated code invokes
608
+ // it once).
609
+ ` transaction: (fn) => db.transaction(fn),`,
610
+ ` };`,
611
+ `}`,
612
+ `function __sqliteWrapWasm(db, file) {`,
613
+ ` const persist = () => {`,
614
+ ` if (file === ':memory:') return;`,
615
+ ` try {`,
616
+ ` require('fs').writeFileSync(file, Buffer.from(db.export()));`,
617
+ ` } catch (error) {`,
618
+ ` console.error('PlainScript: could not save the database to ' + file + ': ' + error.message);`,
619
+ ` }`,
620
+ ` };`,
621
+ ` return {`,
622
+ ` prepare(sql) {`,
623
+ ` return {`,
624
+ ` all(...params) {`,
625
+ ` const stmt = db.prepare(sql);`,
626
+ ` try {`,
627
+ ` stmt.bind(params);`,
628
+ ` const rows = [];`,
629
+ ` while (stmt.step()) rows.push(stmt.getAsObject());`,
630
+ ` return rows;`,
631
+ ` } finally {`,
632
+ ` stmt.free();`,
633
+ ` }`,
634
+ ` },`,
635
+ ` run(...params) {`,
636
+ ` db.run(sql, params);`,
637
+ ` const result = { changes: db.getRowsModified(), lastInsertRowid: null };`,
638
+ ` try {`,
639
+ ` const ids = db.exec('SELECT last_insert_rowid()');`,
640
+ ` if (ids.length && ids[0].values.length) result.lastInsertRowid = ids[0].values[0][0];`,
641
+ ` } catch (_) {}`,
642
+ ` if (/^\\s*(insert|update|delete|replace)/i.test(sql)) persist();`,
643
+ ` return result;`,
644
+ ` },`,
645
+ ` };`,
646
+ ` },`,
647
+ ` exec(sql) {`,
648
+ ` db.run(sql);`,
649
+ ` if (!/^\\s*select/i.test(sql)) persist();`,
650
+ ` },`,
651
+ ` transaction(fn) {`,
652
+ ` return () => {`,
653
+ ` db.run('BEGIN');`,
654
+ ` try {`,
655
+ ` const out = fn();`,
656
+ ` db.run('COMMIT');`,
657
+ ` persist();`,
658
+ ` return out;`,
659
+ ` } catch (error) {`,
660
+ ` try { db.run('ROLLBACK'); } catch (_) {}`,
661
+ ` throw error;`,
662
+ ` }`,
663
+ ` };`,
664
+ ` },`,
665
+ ` };`,
666
+ `}`,
667
+ ].join('\n'),
668
+ // v1.2 — Telegram runtime. Polling-based: no webhook endpoint needed.
669
+ // Exposes `Telegram` (the raw API client) plus a `createTelegramBot(token)`
670
+ // factory that registers handlers and polls getUpdates in a loop. `BOT` is
671
+ // assigned by `bot "<token>"`. The token also falls back to the
672
+ // TELEGRAM_BOT_TOKEN environment variable at call time.
673
+ telegram: [
674
+ `const Telegram = (() => {`,
675
+ ` let token = process.env.TELEGRAM_BOT_TOKEN;`,
676
+ ` const call = async (method, params = {}) => {`,
677
+ ` if (!token) throw new Error('Telegram: TELEGRAM_BOT_TOKEN is not set. Use: bot "YOUR_BOT_TOKEN"');`,
678
+ ` const response = await fetch('https://api.telegram.org/bot' + token + '/' + method, {`,
679
+ ` method: 'POST',`,
680
+ ` headers: { 'Content-Type': 'application/json' },`,
681
+ ` body: JSON.stringify(params),`,
682
+ ` });`,
683
+ ` const json = await response.json();`,
684
+ ` if (!json.ok) throw new Error('Telegram: ' + method + ' failed: ' + JSON.stringify(json));`,
685
+ ` return json.result;`,
686
+ ` };`,
687
+ ` const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));`,
688
+ ` const chats = new Map();`,
689
+ ` const handlers = { command: [], pattern: [], callback: [] };`,
690
+ ` const keyboard = (rows) => ({`,
691
+ ` reply_markup: {`,
692
+ ` inline_keyboard: [rows.map(([text, data]) => ({ text, callback_data: data }))],`,
693
+ ` },`,
694
+ ` });`,
695
+ // v2.0.1 — createTelegramBot is defined inside this module so its handler
696
+ // registry (`handlers`) and API transport (`call`, `sleep`) are in scope.
697
+ // Defining it outside made every BOT.onCommand/onPattern/onCallback call
698
+ // throw "ReferenceError: handlers is not defined", so no rendered inline
699
+ // button could ever execute its PlainScript callback.
700
+ ` async function createTelegramBot(botToken) {`,
701
+ ` const resolved = botToken || process.env.TELEGRAM_BOT_TOKEN;`,
702
+ ` if (!resolved) throw new Error('Telegram: bot token is missing. Use: bot "YOUR_BOT_TOKEN"');`,
703
+ ` token = resolved; // bind the API transport to this bot's credential`,
704
+ ` let offset = 0;`,
705
+ ` const onText = async (chatId, text) => {`,
706
+ ` for (const { matcher, handler } of handlers.pattern) {`,
707
+ ` const match = text.match(matcher);`,
708
+ ` if (match) { await handler({ chatId, text, matches: match }); return; }`,
709
+ ` }`,
710
+ ` const first = text.split(' ')[0];`,
711
+ ` for (const { matcher, handler } of handlers.command) {`,
712
+ ` if (first === matcher) {`,
713
+ ` await handler({ chatId, text, args: text.split(' ').slice(1) });`,
714
+ ` return;`,
715
+ ` }`,
716
+ ` }`,
717
+ ` };`,
718
+ ` const onCallback = async (data, message) => {`,
719
+ ` for (const { matcher, handler } of handlers.callback) {`,
720
+ ` if (data === matcher) {`,
721
+ ` await handler({ data, message, chatId: message.chat.id });`,
722
+ ` return;`,
723
+ ` }`,
724
+ ` }`,
725
+ ` };`,
726
+ ` return {`,
727
+ ` start: async () => {`,
728
+ ` while (true) {`,
729
+ ` let updates;`,
730
+ ` try {`,
731
+ ` updates = await call('getUpdates', { offset, timeout: 30 });`,
732
+ ` } catch (error) {`,
733
+ ` await sleep(3000);`,
734
+ ` continue;`,
735
+ ` }`,
736
+ ` for (const update of updates) {`,
737
+ ` offset = update.update_id + 1;`,
738
+ ` const chat = (update.message || (update.callback_query || {}).message || {}).chat;`,
739
+ ` if (chat) chats.set(chat.id, chat);`,
740
+ ` if (update.message && update.message.text != null) {`,
741
+ ` await onText(update.message.chat.id, update.message.text);`,
742
+ ` } else if (update.callback_query && update.callback_query.data != null) {`,
743
+ ` await onCallback(update.callback_query.data, update.callback_query.message);`,
744
+ ` }`,
745
+ ` }`,
746
+ ` }`,
747
+ ` },`,
748
+ ` onCommand: (matcher, handler) => handlers.command.push({ matcher, handler }),`,
749
+ ` onPattern: (matcher, handler) => handlers.pattern.push({ matcher, handler }),`,
750
+ ` onCallback: (matcher, handler) => handlers.callback.push({ matcher, handler }),`,
751
+ ` };`,
752
+ ` }`,
753
+ ` return {`,
754
+ ` call, chats, handlers, keyboard, createTelegramBot,`,
755
+ ` sendMessage: async (chatId, text, rows) => call('sendMessage', {`,
756
+ ` chat_id: chatId,`,
757
+ ` text: String(text),`,
758
+ ` ...(rows ? keyboard(rows) : {}),`,
759
+ ` }),`,
760
+ ` sendPhoto: async (chatId, photo, caption) => call('sendPhoto', {`,
761
+ ` chat_id: chatId,`,
762
+ ` photo,`,
763
+ ` ...(caption ? { caption } : {}),`,
764
+ ` }),`,
765
+ ` getChat: async (chatId) => call('getChat', { chat_id: chatId }),`,
766
+ ` getMyChats: async () => {`,
767
+ ` const updates = await call('getUpdates', {});`,
768
+ ` for (const update of updates) {`,
769
+ ` const chat = (update.message || update.callback_query || {}).chat;`,
770
+ ` if (chat && !chats.has(chat.id)) chats.set(chat.id, chat);`,
771
+ ` }`,
772
+ ` return [...chats.values()];`,
773
+ ` },`,
774
+ ` editMessage: async (chatId, messageId, text) => call('editMessageText', {`,
775
+ ` chat_id: chatId,`,
776
+ ` message_id: messageId,`,
777
+ ` text: String(text),`,
778
+ ` }),`,
779
+ ` };`,
780
+ `})();`,
781
+ `let BOT;`,
782
+ ].join('\n'),
783
+ };
784
+
785
+ // Built-in stdlib functions: PlainScript name → JS code generator.
786
+ // v0.1–v0.4 original stdlib
787
+ const STDLIB = {
788
+ length: (args, context) => `(${generateExpr(args[0], context)}).length`,
789
+ uppercase: (args, context) => `(${generateExpr(args[0], context)}).toUpperCase()`,
790
+ lowercase: (args, context) => `(${generateExpr(args[0], context)}).toLowerCase()`,
791
+ random: (_args) => `Math.random()`,
792
+ round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
793
+ // Runtime constructors
794
+ sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
795
+ // v0.6 — runtime standard library
796
+ print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
797
+ readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
798
+ writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
799
+ fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
800
+ read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
801
+ sleep: (args, context) => `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${generateExpr(args[0], context)})`,
802
+ time: (_args) => `Date.now()`,
803
+ date: (_args) => `new Date().toISOString()`,
804
+ jsonEncode: (args, context) => `JSON.stringify(${generateExpr(args[0], context)})`,
805
+ jsonDecode: (args, context) => `JSON.parse(${generateExpr(args[0], context)})`,
806
+ env: (args, context) => `process.env[${generateExpr(args[0], context)}]`,
807
+ exit: (args, context) => `process.exit(${args.length ? generateExpr(args[0], context) : '0'})`,
808
+ uuid: (_args, context) => `crypto.randomUUID()`,
809
+ // v1.2 — Telegram runtime helpers
810
+ bot: (args, context) => {
811
+ ensureBuiltin(context, 'telegram');
812
+ if (!context.inFunction) context.needsAsync = true;
813
+ return `BOT = await Telegram.createTelegramBot(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
814
+ },
815
+ sendMessage: (args, context) => {
816
+ ensureBuiltin(context, 'telegram');
817
+ return `Telegram.sendMessage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
818
+ },
819
+ sendPhoto: (args, context) => {
820
+ ensureBuiltin(context, 'telegram');
821
+ return `Telegram.sendPhoto(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
822
+ },
823
+ getChat: (args, context) => {
824
+ ensureBuiltin(context, 'telegram');
825
+ return `Telegram.getChat(${generateExpr(args[0], context)})`;
826
+ },
827
+ getMyChats: (args, context) => {
828
+ ensureBuiltin(context, 'telegram');
829
+ return `Telegram.getMyChats()`;
830
+ },
831
+ editMessage: (args, context) => {
832
+ ensureBuiltin(context, 'telegram');
833
+ return `Telegram.editMessage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
834
+ },
835
+ // v2.1.0 — HTTP request accessors. Only meaningful inside a route handler,
836
+ // where Express provides req/res.
837
+ param: (args, context) => routeAccessor('param', 'params', args, context),
838
+ query: (args, context) => routeAccessor('query', 'query', args, context),
839
+ header: (args, context) => routeAccessor('header', 'headers', args, context),
840
+ // v2.1.0 — request validation. Returns the list of missing required fields.
841
+ validate: (args, context) => {
842
+ ensureBuiltin(context, 'validation');
843
+ return `__validate(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
844
+ },
845
+
846
+ // ── v2.1.0 — filesystem helpers (sync, matching readFile/writeFile style)
847
+
848
+ copyFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.copyFileSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
849
+ moveFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.renameSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
850
+ deleteFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.unlinkSync(${generateExpr(args[0], context)})`; },
851
+ makeFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.mkdirSync(${generateExpr(args[0], context)}, { recursive: true })`; },
852
+ deleteFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.rmSync(${generateExpr(args[0], context)}, { recursive: true, force: true })`; },
853
+ listFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.readdirSync(${generateExpr(args[0], context)})`; },
854
+ appendFile: (args, context) => {
855
+ ensureBuiltin(context, 'fs');
856
+ return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`;
857
+ },
858
+ readBytes: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.readFileSync(${generateExpr(args[0], context)})`; },
859
+ writeBytes: (args, context) => {
860
+ ensureBuiltin(context, 'fs');
861
+ return `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
862
+ },
863
+
864
+ // ── v2.1.0 — text, number and collection helpers
865
+
866
+ trim: (args, context) => `String(${generateExpr(args[0], context)}).trim()`,
867
+ replace: (args, context) => {
868
+ const [target, from, to] = args;
869
+ return `String(${generateExpr(target, context)}).split(${generateExpr(from, context)}).join(${generateExpr(to, context)})`;
870
+ },
871
+ split: (args, context) => {
872
+ const sep = args.length > 1 ? generateExpr(args[1], context) : '" "';
873
+ return `String(${generateExpr(args[0], context)}).split(${sep})`;
874
+ },
875
+ join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
876
+ number: (args, context) => `Number(${generateExpr(args[0], context)})`,
877
+ text: (args, context) => `String(${generateExpr(args[0], context)})`,
878
+ floor: (args, context) => `Math.floor(${generateExpr(args[0], context)})`,
879
+ ceiling: (args, context) => `Math.ceil(${generateExpr(args[0], context)})`,
880
+
881
+ // The shared comparator keeps sorting predictable for both text and
882
+ // numbers without a separate sort call per type.
883
+ sort: (args, context) => `[...${generateExpr(args[0], context)}].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))`,
884
+ reverse: (args, context) => `[...${generateExpr(args[0], context)}].reverse()`,
885
+ unique: (args, context) => `[...new Set(${generateExpr(args[0], context)})]`,
886
+ sum: (args, context) => `(${generateExpr(args[0], context)}).reduce((a, b) => a + b, 0)`,
887
+ smallest: (args, context) => `Math.min(...${generateExpr(args[0], context)})`,
888
+ largest: (args, context) => `Math.max(...${generateExpr(args[0], context)})`,
889
+
890
+ keys: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
891
+ values: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
892
+ hasKey: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
893
+ merge: (args, context) => `{ ...${generateExpr(args[0], context)}, ...${generateExpr(args[1], context)} }`,
894
+
895
+ // ── v2.1.0 — cache (Redis) accessors. All async.
896
+
897
+ cacheGet: (args, context) => {
898
+ ensureBuiltin(context, 'cache');
899
+ markAsync(context);
900
+ return `await __cacheClient().get(String(${generateExpr(args[0], context)}))`;
901
+ },
902
+ cacheSet: (args, context) => {
903
+ ensureBuiltin(context, 'cache');
904
+ markAsync(context);
905
+ const key = `String(${generateExpr(args[0], context)})`;
906
+ const value = `String(${generateExpr(args[1], context)})`;
907
+ if (args.length > 2) {
908
+ return `await __cacheClient().set(${key}, ${value}, { EX: ${generateExpr(args[2], context)} })`;
909
+ }
910
+ return `await __cacheClient().set(${key}, ${value})`;
911
+ },
912
+ cacheDelete: (args, context) => {
913
+ ensureBuiltin(context, 'cache');
914
+ markAsync(context);
915
+ return `await __cacheClient().del(String(${generateExpr(args[0], context)}))`;
916
+ },
917
+
918
+ // v2.1.0 — email sending helper (statement form uses this too).
919
+ sendMail: (args, context) => {
920
+ ensureBuiltin(context, 'mailer');
921
+ markAsync(context);
922
+ return `__mailSend(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
923
+ },
924
+
925
+ // ── v2.1.1 — uploads, cookies, passwords and tokens
926
+
927
+ // upload("field") / uploads("field") read files registered by
928
+ // "accept uploads". Single file → record or null; plural → array.
929
+ upload: (args, context) => {
930
+ routeOnly('upload', 'route post "/upload"\n accept uploads\n show upload("doc")');
931
+ requireOneArg('upload', args);
932
+ ensureBuiltin(context, 'uploads');
933
+ return `__uploadedFile(req, ${generateExpr(args[0], context)})`;
934
+ },
935
+ uploads: (args, context) => {
936
+ routeOnly('uploads', 'route post "/upload"\n accept uploads\n show uploads("docs")');
937
+ requireOneArg('uploads', args);
938
+ ensureBuiltin(context, 'uploads');
939
+ return `__uploadedFiles(req, ${generateExpr(args[0], context)})`;
940
+ },
941
+ // cookie("name") reads a request cookie.
942
+ cookie: (args, context) => {
943
+ routeOnly('cookie', 'route get "/me"\n show cookie("theme")');
944
+ requireOneArg('cookie', args);
945
+ ensureBuiltin(context, 'cookies');
946
+ return `__cookieValue(req, ${generateExpr(args[0], context)})`;
947
+ },
948
+ // Password hashing (scrypt, salted, constant-time comparison).
949
+ hashPassword: (args, context) => {
950
+ ensureBuiltin(context, 'auth');
951
+ return `hashPassword(${generateExpr(args[0], context)})`;
952
+ },
953
+ checkPassword: (args, context) => {
954
+ ensureBuiltin(context, 'auth');
955
+ return `checkPassword(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
956
+ },
957
+ // Signed tokens in HS256 JWT format; readToken returns null when the
958
+ // signature is invalid or the token has expired.
959
+ createToken: (args, context) => {
960
+ ensureBuiltin(context, 'auth');
961
+ return `createToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
962
+ },
963
+ readToken: (args, context) => {
964
+ ensureBuiltin(context, 'auth');
965
+ return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
966
+ },
967
+ };
968
+
969
+ // Mark the enclosing program async when a call awaits at the top level.
970
+ function markAsync(context) {
971
+ if (!context.inFunction) context.needsAsync = true;
972
+ }
973
+
974
+ // v2.1.0 — generate a request accessor (param/query/header). These compile to
975
+ // direct Express req.<bucket>[key] reads and are rejected outside routes so
976
+ // mistakes surface at compile time with a teaching error.
977
+ function routeAccessor(name, bucket, args, context) {
978
+ if (!_inRoute) {
979
+ throw new Error(
980
+ `"${name}(...)" can only be used inside a route handler.\n\nExample:\n route get "/users/:id"\n show ${name}("id")\n done`
981
+ );
982
+ }
983
+ if (args.length !== 1) {
984
+ throw new Error(`"${name}" takes exactly one argument: the ${name} name.\n\nExample:\n ${name}("id")`);
985
+ }
986
+ return `req.${bucket}[${generateExpr(args[0], context)}]`;
987
+ }
988
+
989
+ // v2.1.1 — compile-time guard shared by request-scoped accessors that do not
990
+ // follow the req.<bucket> shape (upload/uploads/cookie).
991
+ function routeOnly(name, example) {
992
+ if (!_inRoute) {
993
+ throw new Error(
994
+ `"${name}" can only be used inside a route handler.\n\nExample:\n ${example}\n done`
995
+ );
996
+ }
997
+ }
998
+
999
+ function requireOneArg(name, args) {
1000
+ if (args.length !== 1) {
1001
+ throw new Error(`"${name}" takes exactly one argument.\n\nExample:\n ${name}("field")`);
1002
+ }
1003
+ }
1004
+
1005
+ // Set to true while generating inside a route handler body.
1006
+ // Remaps PlainScript's "request" → "req" and "response" → "res".
1007
+ let _inRoute = false;
1008
+ // True while generating inside a Telegram handler body. Remaps PlainScript's
1009
+ // "reply" statement to send a chat message instead of an HTTP response.
1010
+ let _inTelegram = false;
1011
+ // v2.1.1 — true while generating inside a WhatsApp "on message" handler.
1012
+ // Remaps PlainScript's "reply" to a WhatsApp chat message and PlainScript's "message"
1013
+ // identifier to the normalized message record of the current delivery.
1014
+ let _inWhatsApp = false;
1015
+ // v2.1.0 — active "group" prefixes. Route paths are prefixed with the
1016
+ // concatenation of every enclosing group, innermost last.
1017
+ const _routePrefixes = [];
1018
+
1019
+ // v2.1.0 — active SQL driver. "sqlite" (default) targets better-sqlite3's
1020
+ // synchronous prepare/run/exec API; "pg" targets node-postgres pools and
1021
+ // makes every SQL statement async. Set by database/postgres declarations.
1022
+ let _sqlDriver = 'sqlite';
1023
+ // The object SQL statements call. "db" normally; a checked-out pool client
1024
+ // while generating inside a PostgreSQL transaction.
1025
+ let _sqlClientVar = 'db';
1026
+
1027
+ // Full path for a route, honouring enclosing group prefixes.
1028
+ function routePath(path) {
1029
+ return _routePrefixes.join('') + path;
1030
+ }
1031
+
1032
+ // v2.1.0 — render the JavaScript expression that executes one SQL statement
1033
+ // under the active driver. kind: query | write | execute.
1034
+ function emitSqlCall(kind, sql, params, indent, context) {
1035
+ const args = params.join(', ');
1036
+ if (_sqlDriver === 'pg') {
1037
+ // Convert the parser's anonymous "?" markers to PostgreSQL "$n" markers.
1038
+ // Only the markers we produced are converted; literal question marks in
1039
+ // the SQL survive untouched.
1040
+ let n = 0;
1041
+ const pgSql = String(sql).replace(/\?/g, () => (++n <= params.length ? `$${n}` : '?'));
1042
+ const call = `${_sqlClientVar}.query(\`${pgSql}\`, [${args}])`;
1043
+ return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
1044
+ }
1045
+ switch (kind) {
1046
+ case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
1047
+ case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
1048
+ case 'execute': return `db.exec(\`${sql}\`)`;
1049
+ default: throw new Error(`Unknown SQL kind "${kind}".`);
1050
+ }
1051
+ }
1052
+
1053
+ function createGenerationContext() {
1054
+ return {
1055
+ requires: new Set(),
1056
+ pendingPrelude: [],
1057
+ needsAsync: false, // true when top-level code emits await (js blocks / ask)
1058
+ inFunction: false, // true while generating inside a function-like scope
1059
+ };
1060
+ }
1061
+
1062
+ // Wraps a generated program so top-level `await` is legal (RFC-0011 §10).
1063
+ function wrapAsync(js) {
1064
+ return `(async () => {\n${js}\n})();`;
1065
+ }
1066
+
1067
+ function isValidIdentifier(name) {
1068
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && !JS_RESERVED.has(name);
1069
+ }
1070
+
1071
+ function npmPackageName(moduleName) {
1072
+ return NPM_NAME[moduleName] || moduleName;
1073
+ }
1074
+
1075
+ function emitRequire(context, moduleName, alias) {
1076
+ // A specifier may carry a version range ("left-pad@^1.3.0"). require() takes
1077
+ // the bare name only — the range is the installer's business (plain install).
1078
+ const { name: bareName } = splitPackageSpec(moduleName);
1079
+ const npmName = npmPackageName(bareName);
1080
+
1081
+ if (alias) {
1082
+ if (!isValidIdentifier(alias)) {
1083
+ throw new Error(
1084
+ `use ${npmName} as ${alias}: "${alias}" is not a valid JavaScript variable name.`
1085
+ );
1086
+ }
1087
+ const known = KNOWN_PACKAGES[bareName];
1088
+ if (known) {
1089
+ const boundAs = known.match(/const (\w+)/)[1];
1090
+ throw new Error(
1091
+ `"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
1092
+ );
1093
+ }
1094
+ const key = `${npmName}\0${alias}`;
1095
+ if (context.requires.has(key)) return '';
1096
+ context.requires.add(key);
1097
+ return `const ${alias} = require('${npmName}');`;
1098
+ }
1099
+
1100
+ if (context.requires.has(npmName)) return '';
1101
+ context.requires.add(npmName);
1102
+
1103
+ if (KNOWN_PACKAGES[bareName]) return KNOWN_PACKAGES[bareName];
1104
+
1105
+ // RFC-0011 §5.1 — arbitrary npm packages. A name that is not a valid JS
1106
+ // identifier (e.g. node-fetch) is required for its side effect only.
1107
+ if (isValidIdentifier(bareName)) {
1108
+ return `const ${bareName} = require('${npmName}');`;
1109
+ }
1110
+ return `require('${npmName}');`;
1111
+ }
1112
+
1113
+ function ensureBuiltin(context, moduleName) {
1114
+ if (context.requires.has(moduleName)) return;
1115
+ context.requires.add(moduleName);
1116
+ const declaration = BUILTIN_DECLARATIONS[moduleName];
1117
+ if (declaration && !context.pendingPrelude.includes(declaration)) {
1118
+ context.pendingPrelude.push(declaration);
1119
+ }
1120
+ }
1121
+
1122
+ // Builtins whose calls await. A statement containing one of these anywhere in
1123
+ // its expressions must compile into an async context.
1124
+ const ASYNC_CALL_NAMES = new Set([
1125
+ // v2.1.0 — cache and email
1126
+ 'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
1127
+ // v1.2 — Telegram helpers (await their API transport)
1128
+ 'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
1129
+ ]);
1130
+
1131
+ // Collect async builtin call names reachable from an AST fragment.
1132
+ function findAsyncCalls(node, found) {
1133
+ if (!node || typeof node !== 'object') return found;
1134
+ if (Array.isArray(node)) {
1135
+ for (const item of node) findAsyncCalls(item, found);
1136
+ return found;
1137
+ }
1138
+ if (node.type === 'CallExpression' && ASYNC_CALL_NAMES.has(node.name)) {
1139
+ found.add(node.name);
1140
+ }
1141
+ // v2.1.1 — HTTP client calls await; "wait for <expr>" awaits explicitly.
1142
+ if (node.type === 'HttpCall' || node.type === 'AwaitExpression') {
1143
+ found.add(node.type);
1144
+ }
1145
+ for (const value of Object.values(node)) {
1146
+ if (value && typeof value === 'object') findAsyncCalls(value, found);
1147
+ }
1148
+ return found;
1149
+ }
1150
+
1151
+ // True when any statement in the block emits `await` (a JavaScript block,
1152
+ // `ask`, or `ocr`), including inside nested if / loop bodies. Nested PlainScript
1153
+ // function declarations are handled independently, so they are not descended
1154
+ // into.
1155
+ function containsAsyncBlock(statements) {
1156
+ for (const stmt of statements || []) {
1157
+ if (stmt.type === 'AskStatement' || stmt.type === 'JavaScriptBlock' || stmt.type === 'OcrStatement') return true;
1158
+ // v2.1.0 — transactions always await; PostgreSQL SQL statements await;
1159
+ // mail sends, cache setup and websocket handlers await.
1160
+ if (stmt.type === 'TransactionStatement') return true;
1161
+ if (stmt.type === 'SendMailStatement' || stmt.type === 'CacheStatement') return true;
1162
+ // v2.1.1 — opening the database awaits (native/wasm engine probe);
1163
+ // retry loops pause between attempts; try/recover recurse.
1164
+ if (stmt.type === 'DatabaseStatement' || stmt.type === 'RetryStatement') return true;
1165
+ if (stmt.type === 'TryStatement') {
1166
+ if (containsAsyncBlock(stmt.tryBody)) return true;
1167
+ if (stmt.recoverBody && containsAsyncBlock(stmt.recoverBody)) return true;
1168
+ continue;
1169
+ }
1170
+ if (_sqlDriver === 'pg' && (
1171
+ stmt.type === 'QueryStatement' || stmt.type === 'InsertStatement' ||
1172
+ stmt.type === 'UpdateStatement' || stmt.type === 'DeleteStatement' ||
1173
+ stmt.type === 'ExecuteStatement' || stmt.type === 'RememberSqlStatement'
1174
+ )) return true;
1175
+ if (findAsyncCalls(stmt, new Set()).size > 0) return true;
1176
+ if (stmt.type === 'IfStatement') {
1177
+ if (containsAsyncBlock(stmt.consequent)) return true;
1178
+ if (stmt.alternate && containsAsyncBlock(stmt.alternate)) return true;
1179
+ } else if (stmt.type !== 'FunctionDeclaration' && stmt.body) {
1180
+ if (containsAsyncBlock(stmt.body)) return true;
1181
+ }
1182
+ }
1183
+ return false;
1184
+ }
1185
+
1186
+ function generate(ast, context = createGenerationContext()) {
1187
+ if (ast.type !== 'Program') {
1188
+ throw new Error(`Expected a Program node but got "${ast.type}".`);
1189
+ }
1190
+ const preludeStart = context.pendingPrelude.length;
1191
+ const body = ast.body.map(node => generateStatement(node, '', context)).filter(Boolean).join('\n');
1192
+ const lines = context.pendingPrelude.slice(preludeStart).concat(body).filter(Boolean);
1193
+ // Top-level functions are the module's public API: export them so a built
1194
+ // PlainScript file works as a normal CommonJS module (npm packages, require()).
1195
+ // Harmless for programs that are only executed.
1196
+ const exported = ast.body
1197
+ .filter(node => node.type === 'FunctionDeclaration')
1198
+ .map(node => node.name);
1199
+ if (exported.length > 0) {
1200
+ lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
1201
+ }
1202
+ return lines.join('\n');
1203
+ }
1204
+
1205
+ // ── Condition generation ────────────────────────────────────────────────────
1206
+
1207
+ function generateCondition(cond, context) {
1208
+ switch (cond.type) {
1209
+ case 'BinaryCondition':
1210
+ return `${generateExpr(cond.left, context)} ${cond.op} ${generateExpr(cond.right, context)}`;
1211
+
1212
+ case 'UnaryCondition':
1213
+ if (cond.op === 'isEmpty') return `(${generateExpr(cond.left, context)}).length === 0`;
1214
+ if (cond.op === 'isNotEmpty') return `(${generateExpr(cond.left, context)}).length > 0`;
1215
+ throw new Error(`Unknown unary condition op "${cond.op}".`);
1216
+
1217
+ case 'BetweenCondition': {
1218
+ const expr = generateExpr(cond.left, context);
1219
+ return `${expr} >= ${generateExpr(cond.low, context)} && ${expr} <= ${generateExpr(cond.high, context)}`;
1220
+ }
1221
+
1222
+ case 'StringCondition':
1223
+ return `(${generateExpr(cond.left, context)}).${cond.method}(${generateExpr(cond.right, context)})`;
1224
+
1225
+ // v2.1.1 — and / or / not combinators.
1226
+ case 'LogicalCondition': {
1227
+ if (cond.op === 'not') return `!(${generateCondition(cond.operand, context)})`;
1228
+ const jsOp = cond.op === 'and' ? '&&' : '||';
1229
+ return `${generateCondition(cond.left, context)} ${jsOp} ${generateCondition(cond.right, context)}`;
1230
+ }
1231
+
1232
+ default:
1233
+ throw new Error(`Unknown condition type "${cond.type}".`);
1234
+ }
1235
+ }
1236
+
1237
+ // ── Statement generation ────────────────────────────────────────────────────
1238
+
1239
+ function generateStatement(node, indent = '', context = createGenerationContext()) {
1240
+ switch (node.type) {
1241
+ case 'RememberStatement':
1242
+ return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
1243
+
1244
+ case 'ShowStatement':
1245
+ return `${indent}console.log(${generateExpr(node.value, context)});`;
1246
+
1247
+ case 'GiveStatement':
1248
+ return `${indent}return ${generateExpr(node.value, context)};`;
1249
+
1250
+ case 'BecomeStatement':
1251
+ return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
1252
+
1253
+ case 'ExpressionStatement':
1254
+ return `${indent}${generateExpr(node.expression, context)};`;
1255
+
1256
+ case 'ImportStatement':
1257
+ return ''; // resolved at bundle time by the bundler
1258
+
1259
+ case 'UseStatement': {
1260
+ const pkg = emitRequire(context, node.module, node.alias);
1261
+ return pkg ? `${indent}${pkg}` : '';
1262
+ }
1263
+
1264
+ // v1.1.1 — JavaScript Gateway (RFC-0011)
1265
+
1266
+ // remember <name> as javascript … done (named — always produces a value)
1267
+ // javascript … done (statement-level block)
1268
+ case 'JavaScriptBlock': {
1269
+ // Validate the raw JavaScript at compile time so JS syntax errors are
1270
+ // reported as such, with the PlainScript context that produced them.
1271
+ try {
1272
+ new vm.Script(`(async () => {\n${node.body}\n})`);
1273
+ } catch (e) {
1274
+ const label = node.name ? `assigned to "${node.name}"` : 'block';
1275
+ throw new Error(
1276
+ `JavaScript error inside the "javascript" ${label}: ${e.message}`
1277
+ );
1278
+ }
1279
+ // Does the body use top-level `await`? Top-level await only parses
1280
+ // inside an async function, so a plain Script rejects it. Synchronous
1281
+ // statement-level blocks need no wrapper; async ones do.
1282
+ let hasTopLevelAwait = false;
1283
+ try {
1284
+ new vm.Script(node.body);
1285
+ } catch (_) {
1286
+ hasTopLevelAwait = true;
1287
+ }
1288
+ // Named blocks always bind a value, so they keep the async IIFE. The
1289
+ // body is emitted verbatim: JavaScript indentation, template literals,
1290
+ // and line structure are preserved as written (RFC-0011 §31).
1291
+ if (node.name) {
1292
+ if (!context.inFunction) context.needsAsync = true;
1293
+ return `${indent}let ${node.name} = await (async () => {\n${node.body}\n${indent}})();`;
1294
+ }
1295
+ // Statement-level blocks inside functions/routes/loops, or that need
1296
+ // top-level await, retain the async-context wrapper.
1297
+ if (context.inFunction || hasTopLevelAwait) {
1298
+ if (!context.inFunction) context.needsAsync = true;
1299
+ return `${indent}await (async () => {\n${node.body}\n${indent}})();`;
1300
+ }
1301
+ // Synchronous statement-level block: emit its body directly/verbatim.
1302
+ return `${indent}${node.body}`;
1303
+ }
1304
+
1305
+ // ask name / ask "<prompt>" as name
1306
+ case 'AskStatement': {
1307
+ ensureBuiltin(context, 'ask');
1308
+ if (!context.inFunction) context.needsAsync = true;
1309
+ const prompt = node.prompt != null ? JSON.stringify(node.prompt) : '"> "';
1310
+ return `${indent}let ${node.variable} = await __ask(${prompt});`;
1311
+ }
1312
+
1313
+ // v2.0.1 — ocr "<image>" as <variable> [using "<lang>"]
1314
+ case 'OcrStatement': {
1315
+ ensureBuiltin(context, 'ocr');
1316
+ if (!context.inFunction) context.needsAsync = true;
1317
+ const image = generateExpr(node.image, context);
1318
+ const langArg = node.lang != null ? `, ${JSON.stringify(node.lang)}` : '';
1319
+ return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
1320
+ }
1321
+
1322
+ case 'FunctionDeclaration': {
1323
+ const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1324
+ const params = node.params.join(', ');
1325
+ const prevInFunction = context.inFunction;
1326
+ context.inFunction = true;
1327
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1328
+ context.inFunction = prevInFunction;
1329
+ return `${indent}${isAsync}function ${node.name}(${params}) {\n${body}\n${indent}}`;
1330
+ }
1331
+
1332
+ case 'IfStatement': {
1333
+ const condition = generateCondition(node.condition, context);
1334
+ const consequent = node.consequent.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1335
+ let out = `${indent}if (${condition}) {\n${consequent}\n${indent}}`;
1336
+ if (node.alternate) {
1337
+ const alternate = node.alternate.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1338
+ out += ` else {\n${alternate}\n${indent}}`;
1339
+ }
1340
+ return out;
1341
+ }
1342
+
1343
+ case 'ForEachStatement': {
1344
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1345
+ return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
1346
+ }
1347
+
1348
+ case 'WhileStatement': {
1349
+ const condition = generateCondition(node.condition, context);
1350
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1351
+ return `${indent}while (${condition}) {\n${body}\n${indent}}`;
1352
+ }
1353
+
1354
+ // v0.3 — Express runtime
1355
+
1356
+ case 'ListenStatement': {
1357
+ const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1358
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1359
+ return `${indent}app.listen(${generateExpr(node.port, context)}, ${handlerAsync}() => {\n${body}\n${indent}});`;
1360
+ }
1361
+
1362
+ case 'RouteStatement': {
1363
+ _inRoute = true;
1364
+ const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1365
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1366
+ _inRoute = false;
1367
+ return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
1368
+ }
1369
+
1370
+ case 'ReplyStatement':
1371
+ if (_inTelegram) {
1372
+ return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)});`;
1373
+ }
1374
+ if (_inWhatsApp) {
1375
+ ensureBuiltin(context, 'whatsapp');
1376
+ return `${indent}await __whatsappReply(__waCtx.chat, ${generateExpr(node.value, context)});`;
1377
+ }
1378
+ return `${indent}res.send(${generateExpr(node.value, context)});`;
1379
+
1380
+ case 'ReplyJsonStatement': {
1381
+ const props = node.properties
1382
+ .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
1383
+ .join(', ');
1384
+ if (_inTelegram) {
1385
+ return `${indent}await Telegram.sendMessage(ctx.chatId, JSON.stringify({ ${props} }));`;
1386
+ }
1387
+ if (_inWhatsApp) {
1388
+ ensureBuiltin(context, 'whatsapp');
1389
+ return `${indent}await __whatsappReply(__waCtx.chat, JSON.stringify({ ${props} }));`;
1390
+ }
1391
+ return `${indent}res.json({ ${props} });`;
1392
+ }
1393
+
1394
+ // v1.2 — reply <value> with buttons … done (Telegram inline keyboard).
1395
+ // The AST stores rows of { text, data } objects (parser.js). The Telegram
1396
+ // runtime's keyboard() expects a flat list of [text, data] pairs, so each
1397
+ // button is rendered as [text, data] and rows are merged into that list.
1398
+ case 'ReplyWithButtonsStatement': {
1399
+ ensureBuiltin(context, 'telegram');
1400
+ const pairs = node.buttons.flat().map(({ text, data }) => [text, data]);
1401
+ return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)}, ${JSON.stringify(pairs)});`;
1402
+ }
1403
+
1404
+ case 'ServeFolderStatement':
1405
+ return `${indent}app.use(express.static(${JSON.stringify(node.folder)}));`;
1406
+
1407
+ // v0.6 — Express DX
1408
+
1409
+ case 'WebAppStatement':
1410
+ return [
1411
+ emitRequire(context, 'express'),
1412
+ `${indent}const app = express();`,
1413
+ // v2.1.0 — parse JSON request bodies so POST/PUT handlers can read
1414
+ // "body of request". Harmless for GET-only v2.0.1 programs.
1415
+ `${indent}app.use(express.json());`,
1416
+ ]
1417
+ .filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
1418
+
1419
+ case 'SimpleRouteStatement': {
1420
+ _inRoute = true;
1421
+ const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1422
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1423
+ _inRoute = false;
1424
+ return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
1425
+ }
1426
+
1427
+ // v2.1.0 — group "<prefix>" ... done: composes routes under a shared
1428
+ // prefix. Groups nest; every enclosed route (either form) gets the
1429
+ // concatenated prefix. Non-route statements run in program order.
1430
+ case 'GroupStatement': {
1431
+ _routePrefixes.push(node.prefix);
1432
+ const body = node.body.map(s => generateStatement(s, indent, context)).join('\n');
1433
+ _routePrefixes.pop();
1434
+ return body;
1435
+ }
1436
+
1437
+ // v2.1.0 — status <expr>: sets the HTTP response status code. Only valid
1438
+ // inside a route handler (res is in scope there).
1439
+ case 'StatusStatement':
1440
+ if (!_inRoute) {
1441
+ throw new Error('"status" can only be used inside a route handler, where a response exists.\n\nExample:\n route get "/missing"\n status 404\n reply "Not found"\n done');
1442
+ }
1443
+ return `${indent}res.status(${generateExpr(node.value, context)});`;
1444
+
1445
+ // v2.1.0 — allow cors: enables cross-origin requests on the current app.
1446
+ // Applies to routes registered after this statement.
1447
+ case 'AllowCorsStatement':
1448
+ return [
1449
+ `${indent}app.use((req, res, next) => {`,
1450
+ `${indent} res.header('Access-Control-Allow-Origin', '*');`,
1451
+ `${indent} res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');`,
1452
+ `${indent} res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');`,
1453
+ `${indent} if (req.method === 'OPTIONS') return res.sendStatus(204);`,
1454
+ `${indent} next();`,
1455
+ `${indent}});`,
1456
+ ].join('\n');
1457
+
1458
+ // ── v2.1.1 — uploads, auth middleware, rate limiting, OAuth ────────────
1459
+ // These register Express middleware in program order; routes declared
1460
+ // after them are protected / wired accordingly.
1461
+
1462
+ case 'AcceptUploadsStatement': {
1463
+ ensureBuiltin(context, 'uploads');
1464
+ const options = [];
1465
+ if (node.limitBytes != null) options.push(`limitBytes: ${node.limitBytes}`);
1466
+ if (node.mimes != null) options.push(`mimes: ${JSON.stringify(node.mimes)}`);
1467
+ if (node.folder != null) options.push(`folder: ${JSON.stringify(node.folder)}`);
1468
+ return `${indent}app.use(__uploads({ ${options.join(', ')} }));`;
1469
+ }
1470
+
1471
+ // require api key from <expr> — rejects requests whose x-api-key header
1472
+ // does not match. The expected key may come from env("...") or anywhere.
1473
+ case 'RequireApiKeyStatement':
1474
+ return [
1475
+ `${indent}app.use((req, res, next) => {`,
1476
+ `${indent} const provided = req.get('x-api-key');`,
1477
+ `${indent} const expected = ${generateExpr(node.key, context)};`,
1478
+ `${indent} if (!expected || provided !== String(expected)) {`,
1479
+ `${indent} return res.status(401).json({ error: 'Unauthorized: a valid x-api-key header is required.' });`,
1480
+ `${indent} }`,
1481
+ `${indent} next();`,
1482
+ `${indent}});`,
1483
+ ].join('\n');
1484
+
1485
+ case 'EnableSessionsStatement':
1486
+ ensureBuiltin(context, 'cookies');
1487
+ ensureBuiltin(context, 'sessions');
1488
+ return `${indent}app.use(__enableSessions(${generateExpr(node.secret, context)}));`;
1489
+
1490
+ case 'RateLimitStatement':
1491
+ ensureBuiltin(context, 'ratelimit');
1492
+ return `${indent}app.use(__rateLimit({ max: ${node.max}, windowMs: ${node.windowMs} }));`;
1493
+
1494
+ case 'GoogleOAuthStatement': {
1495
+ ensureBuiltin(context, 'oauth');
1496
+ const options = {};
1497
+ for (const { key, value } of node.options) {
1498
+ if (key === 'id') options.clientId = generateExpr(value, context);
1499
+ else if (key === 'secret') options.clientSecret = generateExpr(value, context);
1500
+ else if (key === 'callback') options.callbackUrl = generateExpr(value, context);
1501
+ else if (key === 'landing') options.afterLogin = generateExpr(value, context);
1502
+ else throw new Error(`Unknown google oauth option "${key}". Known options: id, secret, callback, landing.`);
1503
+ }
1504
+ for (const [plainKey, jsKey] of [['id', 'clientId'], ['secret', 'clientSecret'], ['callback', 'callbackUrl']]) {
1505
+ if (!options[jsKey]) {
1506
+ throw new Error(`google oauth is missing its "${plainKey}" option.\n\nExample:\n google oauth\n id is env("GOOGLE_CLIENT_ID")\n secret is env("GOOGLE_CLIENT_SECRET")\n callback is "http://localhost:3000/auth/google/callback"\n done`);
1507
+ }
1508
+ }
1509
+ const parts = Object.entries(options).map(([k, v]) => `${k}: ${v}`).join(', ');
1510
+ return `${indent}__googleOAuth(app, { ${parts} });`;
1511
+ }
1512
+
1513
+ // ── v2.1.1 — route-scoped state: cookies and sessions
1514
+
1515
+ case 'DestroySessionStatement':
1516
+ if (!_inRoute) {
1517
+ throw new Error('"destroy session" can only be used inside a route handler.\n\nExample:\n route post "/logout"\n destroy session\n reply "Logged out"\n done');
1518
+ }
1519
+ ensureBuiltin(context, 'cookies');
1520
+ ensureBuiltin(context, 'sessions');
1521
+ return `${indent}__destroySession(req, res);`;
1522
+
1523
+ case 'SetCookieStatement': {
1524
+ if (!_inRoute) {
1525
+ throw new Error('"set cookie" can only be used inside a route handler.\n\nExample:\n route get "/login"\n set cookie "theme" to "dark"\n done');
1526
+ }
1527
+ const options = node.maxAgeSeconds != null
1528
+ ? `{ maxAge: ${node.maxAgeSeconds * 1000}, httpOnly: true, path: '/' }`
1529
+ : `{ httpOnly: true, path: '/' }`;
1530
+ return `${indent}res.cookie(${JSON.stringify(node.name)}, ${generateExpr(node.value, context)}, ${options});`;
1531
+ }
1532
+
1533
+ case 'ClearCookieStatement':
1534
+ if (!_inRoute) {
1535
+ throw new Error('"clear cookie" can only be used inside a route handler.\n\nExample:\n route post "/logout"\n clear cookie "theme"\n done');
1536
+ }
1537
+ return `${indent}res.clearCookie(${JSON.stringify(node.name)}, { path: '/' });`;
1538
+
1539
+ // when nothing matches … done — the 404 catch-all. Registered in source
1540
+ // position, so it must come after every route (Express matches handlers
1541
+ // in registration order).
1542
+ case 'NotFoundStatement': {
1543
+ _inRoute = true;
1544
+ const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1545
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1546
+ _inRoute = false;
1547
+ return `${indent}app.use((${handlerAsync}req, res) => {\n${body}\n${indent}});`;
1548
+ }
1549
+
1550
+ // ── v2.1.1 — error handling and retries
1551
+
1552
+ case 'TryStatement': {
1553
+ const tryBody = node.tryBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1554
+ let out = `${indent}try {\n${tryBody}\n${indent}}`;
1555
+ if (node.recoverBody) {
1556
+ const errorName = node.catchName || '__plainError';
1557
+ const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1558
+ out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
1559
+ } else {
1560
+ // A bare try {} is invalid JavaScript: without "recover", errors are
1561
+ // swallowed through an empty catch block.
1562
+ out += ' catch (__plainError) {}';
1563
+ }
1564
+ return out;
1565
+ }
1566
+
1567
+ case 'RetryStatement': {
1568
+ ensureBuiltin(context, 'retry');
1569
+ markAsync(context);
1570
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1571
+ return [
1572
+ `${indent}for (let __plainAttempt = 1; __plainAttempt <= ${node.attempts}; __plainAttempt++) {`,
1573
+ `${indent} try {`,
1574
+ body,
1575
+ `${indent} break;`,
1576
+ `${indent} } catch (__plainRetryError) {`,
1577
+ `${indent} if (__plainAttempt >= ${node.attempts}) console.error(__plainRetryError);`,
1578
+ `${indent} else await __retrySleep(${Math.round(node.delaySeconds * 1000)});`,
1579
+ `${indent} }`,
1580
+ `${indent}}`,
1581
+ ].join('\n');
1582
+ }
1583
+
1584
+ case 'StartStatement':
1585
+ return `${indent}app.listen(${generateExpr(node.port, context)});`;
1586
+
1587
+ // v0.6 — SQLite DX. v2.1.0 adds parameterized SQL, captured results and
1588
+ // transactions; the driver switches to PostgreSQL when a "postgres"
1589
+ // declaration is active.
1590
+
1591
+ // database "<file>" [using "<driver>"] — v2.1.1 opens through the
1592
+ // portable engine chain: better-sqlite3 when its native binding works on
1593
+ // this machine, sql.js otherwise ("using" forces one engine). The opened
1594
+ // handle exposes the same prepare/exec/transaction surface either way,
1595
+ // so every generated SQL statement below is unchanged.
1596
+ case 'DatabaseStatement': {
1597
+ _sqlDriver = 'sqlite';
1598
+ _sqlClientVar = 'db';
1599
+ ensureBuiltin(context, 'sqlite');
1600
+ markAsync(context);
1601
+ const driverArg = node.driver ? JSON.stringify(node.driver) : 'null';
1602
+ return `${indent}const db = await __dbOpen(${JSON.stringify(node.file)}, ${driverArg});`;
1603
+ }
1604
+
1605
+ // v2.1.0 — postgres "<connection>": node-postgres pool bound to "db".
1606
+ // Every SQL statement afterwards compiles to async pool queries.
1607
+ case 'PostgresStatement': {
1608
+ _sqlDriver = 'pg';
1609
+ _sqlClientVar = 'db';
1610
+ if (!context.inFunction) context.needsAsync = true;
1611
+ return [
1612
+ emitRequire(context, 'postgres'),
1613
+ `${indent}const db = new Pool({ connectionString: ${generateExpr(node.connection, context)} });`,
1614
+ ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
1615
+ }
1616
+
1617
+ case 'QueryStatement':
1618
+ return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
1619
+
1620
+ case 'InsertStatement':
1621
+ case 'UpdateStatement':
1622
+ case 'DeleteStatement':
1623
+ return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
1624
+
1625
+ case 'ExecuteStatement':
1626
+ return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
1627
+
1628
+ // v2.1.0 — remember <name> as query|insert|update|delete … done
1629
+ case 'RememberSqlStatement': {
1630
+ const kind = node.kind === 'query' ? 'query'
1631
+ : node.kind === 'execute' ? 'execute' : 'write';
1632
+ return `${indent}let ${node.name} = ${emitSqlCall(kind, node.sql, node.params, indent, context)};`;
1633
+ }
1634
+
1635
+ // v2.1.0 — transaction … done: all enclosed database statements run
1636
+ // atomically (all succeed or none are applied).
1637
+ case 'TransactionStatement': {
1638
+ if (_sqlDriver === 'pg') {
1639
+ const prevClient = _sqlClientVar;
1640
+ _sqlClientVar = '__txClient';
1641
+ if (!context.inFunction) context.needsAsync = true;
1642
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1643
+ _sqlClientVar = prevClient;
1644
+ return [
1645
+ `${indent}{`,
1646
+ `${indent} const __txClient = await db.connect();`,
1647
+ `${indent} try {`,
1648
+ `${indent} await __txClient.query('BEGIN');`,
1649
+ `${indent} try {`,
1650
+ body,
1651
+ `${indent} await __txClient.query('COMMIT');`,
1652
+ `${indent} } catch (__txError) {`,
1653
+ `${indent} await __txClient.query('ROLLBACK');`,
1654
+ `${indent} throw __txError;`,
1655
+ `${indent} }`,
1656
+ `${indent} } finally {`,
1657
+ `${indent} __txClient.release();`,
1658
+ `${indent} }`,
1659
+ `${indent}}`,
1660
+ ].join('\n');
1661
+ }
1662
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1663
+ return [
1664
+ `${indent}(db.transaction(() => {`,
1665
+ body,
1666
+ `${indent}}))();`,
1667
+ ].join('\n');
1668
+ }
1669
+
1670
+ // v1.2 — Telegram statements
1671
+
1672
+ case 'TelegramCommandStatement': {
1673
+ ensureBuiltin(context, 'telegram');
1674
+ if (!context.inFunction) context.needsAsync = true;
1675
+ _inTelegram = true;
1676
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1677
+ _inTelegram = false;
1678
+ if (node.isPattern) {
1679
+ return `${indent}BOT.onPattern(new RegExp(${JSON.stringify(node.command)}, 'i'), async (ctx) => {\n${body}\n${indent}});`;
1680
+ }
1681
+ return `${indent}BOT.onCommand(${JSON.stringify(node.command)}, async (ctx) => {\n${body}\n${indent}});`;
1682
+ }
1683
+
1684
+ case 'TelegramCallbackStatement': {
1685
+ ensureBuiltin(context, 'telegram');
1686
+ if (!context.inFunction) context.needsAsync = true;
1687
+ _inTelegram = true;
1688
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1689
+ _inTelegram = false;
1690
+ return `${indent}BOT.onCallback(${JSON.stringify(node.data)}, async (ctx) => {\n${body}\n${indent}});`;
1691
+ }
1692
+
1693
+ case 'TelegramStartStatement': {
1694
+ ensureBuiltin(context, 'telegram');
1695
+ if (!context.inFunction) context.needsAsync = true;
1696
+ return `${indent}await BOT.start();`;
1697
+ }
1698
+
1699
+ // ── v2.1.1 — WhatsApp statements ────────────────────────────────────────
1700
+
1701
+ // whatsapp bot … done — starts the Baileys runtime with the declared
1702
+ // auth folder and login mode, then registers every "on message" handler.
1703
+ case 'WhatsAppBotStatement': {
1704
+ ensureBuiltin(context, 'whatsapp');
1705
+ markAsync(context);
1706
+ // v2.1.2 — the pairing phone may be a compile-time literal or any
1707
+ // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
1708
+ // are normalized/validated by __waNormalizePhone at startup.
1709
+ let loginArg;
1710
+ if (node.login.mode === 'pairing') {
1711
+ loginArg = node.login.phoneExpr != null
1712
+ ? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
1713
+ : `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
1714
+ } else {
1715
+ loginArg = `{ mode: 'qr' }`;
1716
+ }
1717
+ const lines = [
1718
+ `${indent}await __whatsappStart({`,
1719
+ `${indent} folder: ${JSON.stringify(node.authFolder)},`,
1720
+ `${indent} login: ${loginArg},`,
1721
+ `${indent}});`,
1722
+ ];
1723
+ for (const handlerNode of node.handlers) {
1724
+ const generated = generateStatement(handlerNode, indent, context);
1725
+ if (generated) lines.push(generated);
1726
+ }
1727
+ return lines.join('\n');
1728
+ }
1729
+
1730
+ // on message … done — registers the handler that receives each incoming
1731
+ // WhatsApp message as a normalized PlainScript record on `message`.
1732
+ case 'WhatsAppOnMessageStatement': {
1733
+ ensureBuiltin(context, 'whatsapp');
1734
+ if (!context.inFunction) context.needsAsync = true;
1735
+ const prevInWhatsApp = _inWhatsApp;
1736
+ _inWhatsApp = true;
1737
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1738
+ _inWhatsApp = prevInWhatsApp;
1739
+ return [
1740
+ `${indent}__whatsappOnMessage(async (__waCtx) => {`,
1741
+ body,
1742
+ `${indent}});`,
1743
+ ].join('\n');
1744
+ }
1745
+
1746
+ // log message — prints the current message record. Handler-only by
1747
+ // design: outside "on message" there is no message to log.
1748
+ case 'WhatsAppLogStatement':
1749
+ if (!_inWhatsApp) {
1750
+ throw new Error('"log message" can only be used inside an "on message" block.\n\nExample:\n whatsapp bot\n on message\n log message\n done\n done');
1751
+ }
1752
+ ensureBuiltin(context, 'whatsapp');
1753
+ return `${indent}console.log(__waCtx.message);`;
1754
+
1755
+ // v2.1.0 — mail, cache, scheduling, background jobs, websocket
1756
+
1757
+ case 'MailTransportStatement': {
1758
+ ensureBuiltin(context, 'mailer');
1759
+ const options = {};
1760
+ let user = null;
1761
+ let pass = null;
1762
+ for (const { key, value } of node.options) {
1763
+ if (key === 'user') { user = generateExpr(value, context); continue; }
1764
+ if (key === 'pass') { pass = generateExpr(value, context); continue; }
1765
+ options[key] = generateExpr(value, context);
1766
+ }
1767
+ if (user != null || pass != null) {
1768
+ const pair = [
1769
+ user != null ? `user: ${user}` : null,
1770
+ pass != null ? `pass: ${pass}` : null,
1771
+ ].filter(Boolean).join(', ');
1772
+ options.auth = `{ ${pair} }`;
1773
+ }
1774
+ const parts = Object.entries(options)
1775
+ .map(([k, v]) => `${JSON.stringify(k)}: ${v}`)
1776
+ .join(', ');
1777
+ return `${indent}__mailCreate({ ${parts} });`;
1778
+ }
1779
+
1780
+ case 'SendMailStatement': {
1781
+ ensureBuiltin(context, 'mailer');
1782
+ markAsync(context);
1783
+ const fields = node.fields
1784
+ .map(f => `${JSON.stringify(f.key)}: ${generateExpr(f.value, context)}`)
1785
+ .join(', ');
1786
+ return `${indent}await __mailSend({ ${fields} });`;
1787
+ }
1788
+
1789
+ // cache "<redis-url>" — connects the shared Redis client. At the top
1790
+ // level the connect is awaited in program order; inside functions it is
1791
+ // connected fire-and-forget.
1792
+ case 'CacheStatement': {
1793
+ ensureBuiltin(context, 'cache');
1794
+ markAsync(context);
1795
+ const url = generateExpr(node.url, context);
1796
+ const lines = [
1797
+ `${indent}{`,
1798
+ `${indent} const { createClient } = require('redis');`,
1799
+ `${indent} __cache = createClient({ url: ${url} });`,
1800
+ `${indent} __cache.on('error', (error) => console.error('Cache error:', error.message));`,
1801
+ ];
1802
+ if (context.inFunction) {
1803
+ lines.push(`${indent} __cache.connect().catch((error) => console.error('Cache error:', error.message));`);
1804
+ lines.push(`${indent}}`);
1805
+ } else {
1806
+ lines.push(`${indent} await __cache.connect();`);
1807
+ lines.push(`${indent}}`);
1808
+ }
1809
+ return lines.join('\n');
1810
+ }
1811
+
1812
+ case 'EveryStatement': {
1813
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1814
+ return [
1815
+ `${indent}setInterval(async () => {`,
1816
+ `${indent} try {`,
1817
+ body,
1818
+ `${indent} } catch (error) { console.error(error); }`,
1819
+ `${indent}}, ${node.count * node.unit});`,
1820
+ ].join('\n');
1821
+ }
1822
+
1823
+ case 'ScheduleStatement': {
1824
+ ensureBuiltin(context, 'scheduler');
1825
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1826
+ return [
1827
+ `${indent}cron.schedule(${JSON.stringify(node.expression)}, async () => {`,
1828
+ `${indent} try {`,
1829
+ body,
1830
+ `${indent} } catch (error) { console.error(error); }`,
1831
+ `${indent}});`,
1832
+ ].join('\n');
1833
+ }
1834
+
1835
+ case 'RunBackgroundStatement':
1836
+ return [
1837
+ `${indent}setImmediate(() => {`,
1838
+ `${indent} try {`,
1839
+ `${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
1840
+ `${indent} } catch (error) { console.error(error); }`,
1841
+ `${indent}});`,
1842
+ ].join('\n');
1843
+
1844
+ case 'WebSocketServerStatement': {
1845
+ ensureBuiltin(context, 'websocket');
1846
+ const handler = (name, params, body) => {
1847
+ if (!body) return '';
1848
+ const js = body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1849
+ return `\n${indent} ${name}: async (${params}) => {\n${js}\n${indent} },`;
1850
+ };
1851
+ return [
1852
+ `${indent}const __wsServer = __wsServerCreate(${generateExpr(node.port, context)}, {` +
1853
+ handler('connect', 'socket', node.connectBody) +
1854
+ handler('message', 'socket, message', node.messageBody) +
1855
+ handler('disconnect', 'socket', node.disconnectBody),
1856
+ `${indent}});`,
1857
+ ].join('\n');
1858
+ }
1859
+
1860
+ case 'SendSocketStatement':
1861
+ ensureBuiltin(context, 'websocket');
1862
+ return `${indent}__wsSend(socket, ${generateExpr(node.value, context)});`;
1863
+
1864
+ case 'BroadcastStatement':
1865
+ ensureBuiltin(context, 'websocket');
1866
+ return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
1867
+
1868
+ default:
1869
+ throw new Error(`Unknown statement type "${node.type}".`);
1870
+ }
1871
+ }
1872
+
1873
+ // Generates a valid JS assignment target (left-hand side of =).
1874
+ function generateLValue(node, context) {
1875
+ if (node.type === 'Identifier') return node.name;
1876
+ if (node.type === 'IndexExpression') return `${generateExpr(node.object, context)}[${generateExpr(node.index, context)}]`;
1877
+ if (node.type === 'MemberExpression') return `${generateExpr(node.object, context)}.${node.property}`;
1878
+ if (node.type === 'OfExpression') return `${generateExpr(node.object, context)}.${generateExpr(node.property, context)}`;
1879
+ if (node.type === 'FirstItem') return `${generateExpr(node.collection, context)}[0]`;
1880
+ if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
1881
+ if (node.type === 'LastItem') return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
1882
+ throw new Error(`Invalid assignment target "${node.type}".`);
1883
+ }
1884
+
1885
+ function generateExpr(node, context = createGenerationContext()) {
1886
+ switch (node.type) {
1887
+ case 'StringLiteral': return JSON.stringify(node.value);
1888
+ case 'NumberLiteral': return String(node.value);
1889
+ // v2.1.1 — boolean and null literals are PlainScript keywords.
1890
+ case 'BooleanLiteral': return String(node.value);
1891
+ case 'NullLiteral': return 'null';
1892
+ // v2.1.1 — arithmetic: unary minus (binary + - * / % reuse
1893
+ // BinaryExpression). Binary operands need parentheses so that
1894
+ // -(2 + 3) does not flatten to -2 + 3.
1895
+ case 'UnaryExpression':
1896
+ return `${node.operator}${node.operand.type === 'BinaryExpression'
1897
+ ? `(${generateExpr(node.operand, context)})`
1898
+ : generateExpr(node.operand, context)}`;
1899
+ // v2.1.1 — wait for <expr>: awaits an async value (fetch promises,
1900
+ // async functions called from PlainScript, etc.).
1901
+ case 'AwaitExpression': {
1902
+ markAsync(context);
1903
+ return `(await ${generateExpr(node.value, context)})`;
1904
+ }
1905
+ // v2.1.1 — HTTP client: get/post/put/patch/delete "<url>" with clauses.
1906
+ case 'HttpCall': {
1907
+ ensureBuiltin(context, 'http');
1908
+ markAsync(context);
1909
+ const options = [];
1910
+ if (node.body != null) options.push(`body: ${generateExpr(node.body, context)}`);
1911
+ if (node.headers != null) options.push(`headers: ${generateExpr(node.headers, context)}`);
1912
+ if (node.timeout != null) options.push(`timeoutMs: ${generateExpr(node.timeout, context)}`);
1913
+ return `await __httpRequest('${node.method.toUpperCase()}', ${generateExpr(node.url, context)}, { ${options.join(', ')} })`;
1914
+ }
1915
+
1916
+ // Backtick template literal: emit as a JavaScript template literal.
1917
+ // Content is preserved verbatim (interpolation, whitespace, line breaks).
1918
+ // Only literal backtick characters inside the content need escaping.
1919
+ case 'TemplateLiteral': {
1920
+ const escaped = node.value.replace(/`/g, '\\`');
1921
+ return '`' + escaped + '`';
1922
+ }
1923
+
1924
+ case 'Identifier': {
1925
+ // Inside route handlers, remap PlainScript's request/response to req/res
1926
+ if (_inRoute && node.name === 'request') return 'req';
1927
+ if (_inRoute && node.name === 'response') return 'res';
1928
+ // Inside WhatsApp "on message" handlers, PlainScript's "message" is the
1929
+ // normalized record of the current delivery.
1930
+ if (_inWhatsApp && node.name === 'message') return '__waCtx.message';
1931
+ return node.name;
1932
+ }
1933
+
1934
+ // Nested binary operands get parentheses so (2 + 3) * 4 keeps its
1935
+ // grouping instead of flattening to 2 + 3 * 4.
1936
+ case 'BinaryExpression': {
1937
+ const left = node.left.type === 'BinaryExpression'
1938
+ ? `(${generateExpr(node.left, context)})`
1939
+ : generateExpr(node.left, context);
1940
+ const right = node.right.type === 'BinaryExpression'
1941
+ ? `(${generateExpr(node.right, context)})`
1942
+ : generateExpr(node.right, context);
1943
+ return `${left} ${node.operator} ${right}`;
1944
+ }
1945
+
1946
+ case 'ArrayLiteral':
1947
+ return `[${node.elements.map(element => generateExpr(element, context)).join(', ')}]`;
1948
+
1949
+ case 'ObjectLiteral': {
1950
+ const props = node.properties
1951
+ .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
1952
+ .join(', ');
1953
+ return `{ ${props} }`;
1954
+ }
1955
+
1956
+ // v1.2 — Inline object literal: { key: value, ... }
1957
+ case 'InlineObjectLiteral': {
1958
+ const props = node.properties
1959
+ .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
1960
+ .join(', ');
1961
+ return `{ ${props} }`;
1962
+ }
1963
+
1964
+ case 'IndexExpression':
1965
+ return `${generateExpr(node.object, context)}[${generateExpr(node.index, context)}]`;
1966
+
1967
+ case 'MemberExpression':
1968
+ return `${generateExpr(node.object, context)}.${node.property}`;
1969
+
1970
+ case 'CallExpression': {
1971
+ if (STDLIB[node.name]) {
1972
+ if (node.name === 'readFile' || node.name === 'writeFile' ||
1973
+ node.name === 'fileExists' || node.name === 'read') {
1974
+ ensureBuiltin(context, 'fs');
1975
+ } else if (node.name === 'uuid') {
1976
+ ensureBuiltin(context, 'crypto');
1977
+ }
1978
+ return STDLIB[node.name](node.args, context);
1979
+ }
1980
+ return `${node.name}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
1981
+ }
1982
+
1983
+ // v1.1 — Item expressions
1984
+ case 'FirstItem':
1985
+ return `${generateExpr(node.collection, context)}[0]`;
1986
+
1987
+ case 'LastItem':
1988
+ return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
1989
+
1990
+ case 'NumberedItem':
1991
+ return `${generateExpr(node.collection, context)}[${node.index}]`;
1992
+
1993
+ case 'LengthExpression':
1994
+ return `${generateExpr(node.object, context)}.length`;
1995
+
1996
+ // v1.1 — Property access
1997
+ case 'OfExpression': {
1998
+ // v2.1.1 — "session of request" / "user of request" read server-side
1999
+ // state managed by the session and OAuth runtimes.
2000
+ if (node.object.type === 'Identifier' && node.object.name === 'request' &&
2001
+ node.property.type === 'Identifier') {
2002
+ if (node.property.name === 'session') {
2003
+ routeOnly('session of request', 'route get "/me"\n show session of request');
2004
+ ensureBuiltin(context, 'sessions');
2005
+ return '__sessionOf(req)';
2006
+ }
2007
+ if (node.property.name === 'user') {
2008
+ routeOnly('user of request', 'route get "/me"\n show user of request');
2009
+ ensureBuiltin(context, 'sessions');
2010
+ return '__userOf(req)';
2011
+ }
2012
+ }
2013
+ return `${generateExpr(node.object, context)}.${generateExpr(node.property, context)}`;
2014
+ }
2015
+
2016
+ // v1.1 — Collection operations
2017
+ case 'AddCall':
2018
+ return `${generateExpr(node.collection, context)}.push(${generateExpr(node.value, context)})`;
2019
+
2020
+ case 'RemoveCall':
2021
+ return `${generateExpr(node.collection, context)}.splice(${generateExpr(node.collection, context)}.indexOf(${generateExpr(node.value, context)}), 1)`;
2022
+
2023
+ case 'WriteCall':
2024
+ ensureBuiltin(context, 'fs');
2025
+ return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
2026
+
2027
+ default:
2028
+ throw new Error(`Unknown expression type "${node.type}".`);
2029
+ }
2030
+ }
2031
+
2032
+ module.exports = { generate, createGenerationContext, wrapAsync };