plainscript-lang 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +173 -738
- package/compiler/bundler.js +83 -12
- package/compiler/cli.js +74 -27
- package/compiler/dependency-detector.js +11 -0
- package/compiler/generator.js +372 -35
- package/compiler/lexer.js +2 -0
- package/compiler/parser.js +410 -28
- package/compiler/sourcemap.js +142 -0
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +98 -534
- package/docs/PLAINSCRIPT-SPEC.md +304 -551
- package/docs/index.html +127 -598
- package/docs/website/script.js +185 -1006
- package/docs/website/style.css +220 -656
- package/examples/ai-providers.pln +7 -0
- package/examples/arrays.pln +4 -12
- package/examples/async-errors.pln +18 -0
- package/examples/auth-api.pln +3 -50
- package/examples/auth-sessions.pln +32 -0
- package/examples/basics.pln +14 -0
- package/examples/bots.pln +13 -0
- package/examples/cache-and-jobs.pln +6 -28
- package/examples/cache-schedule.pln +22 -0
- package/examples/collections.pln +15 -0
- package/examples/concurrency.pln +12 -43
- package/examples/conditions.pln +22 -0
- package/examples/database.pln +6 -39
- package/examples/day2.pln +6 -6
- package/examples/day3.pln +4 -10
- package/examples/deployment.pln +3 -9
- package/examples/email-send.pln +3 -22
- package/examples/error-handling.pln +6 -54
- package/examples/expressions.pln +7 -40
- package/examples/file-uploads.pln +5 -34
- package/examples/files-and-config.pln +5 -46
- package/examples/files.pln +12 -0
- package/examples/football-backend/app.pln +21 -20
- package/examples/functions.pln +17 -0
- package/examples/hello.pln +2 -3
- package/examples/http-client.pln +3 -44
- package/examples/http.pln +11 -0
- package/examples/id-verification/app.pln +4 -3
- package/examples/id-verification/make-sample-id.js +29 -42
- package/examples/json.pln +11 -0
- package/examples/loops.pln +13 -11
- package/examples/modules/app.pln +3 -16
- package/examples/modules/main.pln +4 -0
- package/examples/modules/math.pln +5 -16
- package/examples/mongo.pln +33 -0
- package/examples/objects.pln +3 -11
- package/examples/ocr.pln +22 -0
- package/examples/packages.pln +6 -0
- package/examples/record-kinds.pln +6 -42
- package/examples/records.pln +15 -0
- package/examples/rest-api-fetch.pln +6 -90
- package/examples/rest-api.pln +5 -65
- package/examples/scheduled-tasks.pln +4 -23
- package/examples/search-and-filter.pln +4 -34
- package/examples/server.pln +5 -24
- package/examples/sessions-and-cookies.pln +4 -50
- package/examples/sqlite.pln +23 -0
- package/examples/start.pln +2 -2
- package/examples/stdlib.pln +4 -41
- package/examples/string-verbs.pln +16 -0
- package/examples/telegram-ai-bot.pln +19 -0
- package/examples/telegram-bot.pln +4 -40
- package/examples/testing.pln +13 -0
- package/examples/web-api.pln +27 -0
- package/examples/web-app.pln +4 -16
- package/examples/websocket-server.pln +5 -26
- package/examples/websocket.pln +13 -0
- package/examples/whatsapp-bot/pairing.pln +4 -5
- package/examples/whatsapp-bot/qr.pln +7 -3
- package/package.json +3 -2
package/compiler/generator.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generator: converts a PlainScript AST into JavaScript source code.
|
|
2
2
|
|
|
3
3
|
const { splitPackageSpec } = require('./dependency-detector');
|
|
4
|
+
const { SourceMapGenerator } = require('./sourcemap');
|
|
4
5
|
|
|
5
6
|
// Known runtime packages and their require() statements.
|
|
6
7
|
const KNOWN_PACKAGES = {
|
|
@@ -12,6 +13,8 @@ const KNOWN_PACKAGES = {
|
|
|
12
13
|
chalk: `const chalk = require('chalk');`,
|
|
13
14
|
// v2.1.0 — PostgreSQL driver behind the friendly "postgres" name.
|
|
14
15
|
postgres: `const { Pool } = require('pg');`,
|
|
16
|
+
// v2.2.0 — MongoDB driver.
|
|
17
|
+
mongodb: `const { MongoClient } = require('mongodb');`,
|
|
15
18
|
};
|
|
16
19
|
|
|
17
20
|
// PlainScript module names whose npm package name differs from the PlainScript name.
|
|
@@ -575,21 +578,32 @@ const BUILTIN_DECLARATIONS = {
|
|
|
575
578
|
` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
|
|
576
579
|
`}`,
|
|
577
580
|
].join('\n'),
|
|
578
|
-
// v2.2.0 — AI
|
|
579
|
-
//
|
|
580
|
-
//
|
|
581
|
+
// v2.2.0 — provider-neutral AI runtime. `chat` and `embedText` speak
|
|
582
|
+
// OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
|
|
583
|
+
// and DeepSeek. A custom `base` and `key` can be supplied per call.
|
|
581
584
|
ai: [
|
|
582
|
-
`function __aiTags() {`,
|
|
583
|
-
`
|
|
585
|
+
`function __aiTags(options = {}) {`,
|
|
586
|
+
` const provider = String(options.provider || process.env.PLAINSCRIPT_AI_PROVIDER || 'openai').toLowerCase();`,
|
|
587
|
+
` const providers = {`,
|
|
588
|
+
` openai: { key: process.env.OPENAI_API_KEY, base: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1' },`,
|
|
589
|
+
` groq: { key: process.env.GROQ_API_KEY, base: process.env.GROQ_BASE_URL || 'https://api.groq.com/openai/v1' },`,
|
|
590
|
+
` openrouter: { key: process.env.OPENROUTER_API_KEY, base: process.env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api/v1' },`,
|
|
591
|
+
` together: { key: process.env.TOGETHER_API_KEY, base: process.env.TOGETHER_BASE_URL || 'https://api.together.xyz/v1' },`,
|
|
592
|
+
` fireworks: { key: process.env.FIREWORKS_API_KEY, base: process.env.FIREWORKS_BASE_URL || 'https://api.fireworks.ai/inference/v1' },`,
|
|
593
|
+
` deepseek: { key: process.env.DEEPSEEK_API_KEY, base: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1' },`,
|
|
594
|
+
` };`,
|
|
595
|
+
` const selected = providers[provider] || { key: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY'], base: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_BASE_URL'] };`,
|
|
596
|
+
` return { provider, key: options.key || selected.key, base: (options.base || selected.base || '').replace(/\\/$/, '') };`,
|
|
584
597
|
`}`,
|
|
585
|
-
`async function __aiPost(tags, path, body) {`,
|
|
598
|
+
`async function __aiPost(tags, path, body, options = {}) {`,
|
|
586
599
|
` if (typeof fetch !== 'function') {`,
|
|
587
600
|
` throw new Error('AI calls need Node.js 18 or newer (global fetch is missing): ' + process.version);`,
|
|
588
601
|
` }`,
|
|
589
|
-
` if (!tags.key) throw new Error('No API key for AI. Set
|
|
602
|
+
` if (!tags.key) throw new Error('No API key for AI provider ' + tags.provider + '. Set ' + tags.provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY or pass key in chat options.');`,
|
|
603
|
+
` const headers = Object.assign({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key }, options.headers || {});`,
|
|
590
604
|
` const response = await fetch(tags.base + path, {`,
|
|
591
605
|
` method: 'POST',`,
|
|
592
|
-
` headers
|
|
606
|
+
` headers,`,
|
|
593
607
|
` body: JSON.stringify(body),`,
|
|
594
608
|
` });`,
|
|
595
609
|
` const text = await response.text();`,
|
|
@@ -599,19 +613,21 @@ const BUILTIN_DECLARATIONS = {
|
|
|
599
613
|
` return data;`,
|
|
600
614
|
`}`,
|
|
601
615
|
`async function __aiChat(model, messages, options) {`,
|
|
602
|
-
`
|
|
603
|
-
`
|
|
604
|
-
` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
|
|
616
|
+
` options = options || {};`,
|
|
617
|
+
` const tags = __aiTags(options);`,
|
|
605
618
|
` if (typeof messages === 'string') messages = [{ role: 'user', content: messages }];`,
|
|
606
|
-
` const
|
|
619
|
+
` const body = { model: model, messages: messages };`,
|
|
620
|
+
` if (options.temperature != null) body.temperature = options.temperature;`,
|
|
621
|
+
` if (options.maxTokens != null) body.max_tokens = options.maxTokens;`,
|
|
622
|
+
` if (options.responseFormat != null) body.response_format = options.responseFormat;`,
|
|
623
|
+
` const data = await __aiPost(tags, '/chat/completions', body, options);`,
|
|
607
624
|
` const choice = data.choices && data.choices[0];`,
|
|
608
625
|
` return choice && choice.message ? choice.message.content : '';`,
|
|
609
626
|
`}`,
|
|
610
627
|
`async function __aiEmbed(model, text, options) {`,
|
|
611
|
-
`
|
|
612
|
-
`
|
|
613
|
-
`
|
|
614
|
-
` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) });`,
|
|
628
|
+
` options = options || {};`,
|
|
629
|
+
` const tags = __aiTags(options);`,
|
|
630
|
+
` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) }, options);`,
|
|
615
631
|
` return (data.data && data.data[0] && data.data[0].embedding) || [];`,
|
|
616
632
|
`}`,
|
|
617
633
|
`function __aiSimilarity(a, b) {`,
|
|
@@ -976,7 +992,60 @@ const BUILTIN_DECLARATIONS = {
|
|
|
976
992
|
` };`,
|
|
977
993
|
`}`,
|
|
978
994
|
].join('\n'),
|
|
979
|
-
//
|
|
995
|
+
// v2.2.0 -- MongoDB runtime. Connects to MongoDB and provides a
|
|
996
|
+
// collection-oriented surface compatible with the existing SQL statement
|
|
997
|
+
// forms (query, insert, update, delete, execute, transaction).
|
|
998
|
+
mongodb: [
|
|
999
|
+
`let __mongoClient = null;`,
|
|
1000
|
+
`let __mongoDb = null;`,
|
|
1001
|
+
`function __mongoCollection(name) {`,
|
|
1002
|
+
` if (!__mongoDb) throw new Error('MongoDB: not connected. Use "database <uri> using "mongo" [db <name>]" first.');`,
|
|
1003
|
+
` return __mongoDb.collection(name);`,
|
|
1004
|
+
`}`,
|
|
1005
|
+
`async function __mongoOpen(uri, dbName) {`,
|
|
1006
|
+
` if (__mongoClient) return __mongoDb;`,
|
|
1007
|
+
` const { MongoClient } = require('mongodb');`,
|
|
1008
|
+
` __mongoClient = new MongoClient(uri);`,
|
|
1009
|
+
` await __mongoClient.connect();`,
|
|
1010
|
+
` __mongoDb = __mongoClient.db(dbName || undefined);`,
|
|
1011
|
+
` __mongoDb.__query = async function(sql, params) {`,
|
|
1012
|
+
` const m = String(sql).match(/^\\s*SELECT\\s+(.+?)\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
|
|
1013
|
+
` if (!m) throw new Error('MongoDB query: use SELECT fields FROM collection [WHERE condition]');`,
|
|
1014
|
+
` const [, fields, collection, where] = m;`,
|
|
1015
|
+
` const coll = __mongoCollection(collection);`,
|
|
1016
|
+
` let filter = {};`,
|
|
1017
|
+
` if (where) {`,
|
|
1018
|
+
` const parts = where.split('=').map(s => s.trim());`,
|
|
1019
|
+
` if (parts.length === 2) filter[parts[0]] = params[0];`,
|
|
1020
|
+
` }`,
|
|
1021
|
+
` const projection = fields.trim() === '*' ? {} : Object.fromEntries(fields.split(',').map(f => [f.trim(), 1]));`,
|
|
1022
|
+
` return coll.find(filter).project(projection).toArray();`,
|
|
1023
|
+
` };`,
|
|
1024
|
+
` __mongoDb.__write = async function(sql, params) {`,
|
|
1025
|
+
` const m = String(sql).match(/^\\s*INSERT\\s+INTO\\s+(\\w+)\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)/i);`,
|
|
1026
|
+
` if (!m) throw new Error('MongoDB insert: use INSERT INTO collection (fields) VALUES (?, ...)');`,
|
|
1027
|
+
` const [, collection, fieldsStr, valuesStr] = m;`,
|
|
1028
|
+
` const fields = fieldsStr.split(',').map(f => f.trim());`,
|
|
1029
|
+
` const values = params;`,
|
|
1030
|
+
` const doc = {}; fields.forEach((f, i) => doc[f] = values[i]);`,
|
|
1031
|
+
` const coll = __mongoCollection(collection);`,
|
|
1032
|
+
` const result = await coll.insertOne(doc);`,
|
|
1033
|
+
` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
|
|
1034
|
+
` };`,
|
|
1035
|
+
` __mongoDb.__execute = async function(sql, params) {`,
|
|
1036
|
+
` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
|
|
1037
|
+
` };`,
|
|
1038
|
+
` return __mongoDb;`,
|
|
1039
|
+
`}`,
|
|
1040
|
+
`async function __mongoClose() {`,
|
|
1041
|
+
` if (__mongoClient) {`,
|
|
1042
|
+
` await __mongoClient.close();`,
|
|
1043
|
+
` __mongoClient = null;`,
|
|
1044
|
+
` __mongoDb = null;`,
|
|
1045
|
+
` }`,
|
|
1046
|
+
`}`,
|
|
1047
|
+
].join('\n'),
|
|
1048
|
+
// v1.2 -- Telegram runtime. Polling-based: no webhook endpoint needed.
|
|
980
1049
|
// Exposes `Telegram` (the raw API client) plus a `createTelegramBot(token)`
|
|
981
1050
|
// factory that registers handlers and polls getUpdates in a loop. `BOT` is
|
|
982
1051
|
// assigned by `bot "<token>"`. The token also falls back to the
|
|
@@ -1013,15 +1082,16 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1013
1082
|
` if (!resolved) throw new Error('Telegram: bot token is missing. Use: bot "YOUR_BOT_TOKEN"');`,
|
|
1014
1083
|
` token = resolved; // bind the API transport to this bot's credential`,
|
|
1015
1084
|
` let offset = 0;`,
|
|
1016
|
-
` const onText = async (chatId, text) => {`,
|
|
1085
|
+
` const onText = async (chatId, text, rawMessage = {}) => {`,
|
|
1086
|
+
` const baseContext = { chatId, chat: rawMessage.chat || { id: chatId }, message: rawMessage, text, args: text.split(' ').slice(1), matches: [] };`,
|
|
1017
1087
|
` for (const { matcher, handler } of handlers.pattern) {`,
|
|
1018
1088
|
` const match = text.match(matcher);`,
|
|
1019
|
-
` if (match) { await handler({
|
|
1089
|
+
` if (match) { await handler({ ...baseContext, matches: match }); return; }`,
|
|
1020
1090
|
` }`,
|
|
1021
1091
|
` const first = text.split(' ')[0];`,
|
|
1022
1092
|
` for (const { matcher, handler } of handlers.command) {`,
|
|
1023
1093
|
` if (first === matcher) {`,
|
|
1024
|
-
` await handler(
|
|
1094
|
+
` await handler(baseContext);`,
|
|
1025
1095
|
` return;`,
|
|
1026
1096
|
` }`,
|
|
1027
1097
|
` }`,
|
|
@@ -1029,7 +1099,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1029
1099
|
` const onCallback = async (data, message) => {`,
|
|
1030
1100
|
` for (const { matcher, handler } of handlers.callback) {`,
|
|
1031
1101
|
` if (data === matcher) {`,
|
|
1032
|
-
` await handler({ data, message, chatId: message.chat.id });`,
|
|
1102
|
+
` await handler({ data, message, chatId: message.chat.id, chat: message.chat, text: message.text || '', args: [], matches: [] });`,
|
|
1033
1103
|
` return;`,
|
|
1034
1104
|
` }`,
|
|
1035
1105
|
` }`,
|
|
@@ -1049,7 +1119,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1049
1119
|
` const chat = (update.message || (update.callback_query || {}).message || {}).chat;`,
|
|
1050
1120
|
` if (chat) chats.set(chat.id, chat);`,
|
|
1051
1121
|
` if (update.message && update.message.text != null) {`,
|
|
1052
|
-
` await onText(update.message.chat.id, update.message.text);`,
|
|
1122
|
+
` await onText(update.message.chat.id, update.message.text, update.message);`,
|
|
1053
1123
|
` } else if (update.callback_query && update.callback_query.data != null) {`,
|
|
1054
1124
|
` await onCallback(update.callback_query.data, update.callback_query.message);`,
|
|
1055
1125
|
` }`,
|
|
@@ -1161,6 +1231,22 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1161
1231
|
ensureBuiltin(context, 'telegram');
|
|
1162
1232
|
return `Telegram.editMessage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1163
1233
|
},
|
|
1234
|
+
telegramCall: (args, context) => {
|
|
1235
|
+
ensureBuiltin(context, 'telegram');
|
|
1236
|
+
requireArgs('telegramCall', args, 1, 'telegramCall("getMe", {})');
|
|
1237
|
+
markAsync(context);
|
|
1238
|
+
const method = generateExpr(args[0], context);
|
|
1239
|
+
const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
|
|
1240
|
+
return `await Telegram.call(${method}, ${params})`;
|
|
1241
|
+
},
|
|
1242
|
+
telegramApi: (args, context) => {
|
|
1243
|
+
ensureBuiltin(context, 'telegram');
|
|
1244
|
+
requireArgs('telegramApi', args, 1, 'telegramApi("getMe", {})');
|
|
1245
|
+
markAsync(context);
|
|
1246
|
+
const method = generateExpr(args[0], context);
|
|
1247
|
+
const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
|
|
1248
|
+
return `await Telegram.call(${method}, ${params})`;
|
|
1249
|
+
},
|
|
1164
1250
|
// v2.1.0 — HTTP request accessors. Only meaningful inside a route handler,
|
|
1165
1251
|
// where Express provides req/res.
|
|
1166
1252
|
param: (args, context) => routeAccessor('param', 'params', args, context),
|
|
@@ -1600,20 +1686,42 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1600
1686
|
// offline cosine similarity over any two equal-length numeric vectors.
|
|
1601
1687
|
chat: (args, context) => {
|
|
1602
1688
|
ensureBuiltin(context, 'ai');
|
|
1689
|
+
requireArgs('chat', args, 2, 'chat("model", "message")');
|
|
1603
1690
|
markAsync(context);
|
|
1604
1691
|
const model = generateExpr(args[0], context);
|
|
1605
1692
|
const messages = generateExpr(args[1], context);
|
|
1606
1693
|
const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
|
|
1607
1694
|
return `await __aiChat(${model}, ${messages}, ${options})`;
|
|
1608
1695
|
},
|
|
1696
|
+
chatWith: (args, context) => {
|
|
1697
|
+
ensureBuiltin(context, 'ai');
|
|
1698
|
+
requireArgs('chatWith', args, 3, 'chatWith("groq", "model", "message")');
|
|
1699
|
+
markAsync(context);
|
|
1700
|
+
const provider = generateExpr(args[0], context);
|
|
1701
|
+
const model = generateExpr(args[1], context);
|
|
1702
|
+
const messages = generateExpr(args[2], context);
|
|
1703
|
+
const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
|
|
1704
|
+
return `await __aiChat(${model}, ${messages}, Object.assign({}, ${options}, { provider: ${provider} }))`;
|
|
1705
|
+
},
|
|
1609
1706
|
embedText: (args, context) => {
|
|
1610
1707
|
ensureBuiltin(context, 'ai');
|
|
1708
|
+
requireArgs('embedText', args, 2, 'embedText("model", "text")');
|
|
1611
1709
|
markAsync(context);
|
|
1612
1710
|
const model = generateExpr(args[0], context);
|
|
1613
1711
|
const text = generateExpr(args[1], context);
|
|
1614
1712
|
const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
|
|
1615
1713
|
return `await __aiEmbed(${model}, ${text}, ${options})`;
|
|
1616
1714
|
},
|
|
1715
|
+
embedWith: (args, context) => {
|
|
1716
|
+
ensureBuiltin(context, 'ai');
|
|
1717
|
+
requireArgs('embedWith', args, 3, 'embedWith("groq", "model", "text")');
|
|
1718
|
+
markAsync(context);
|
|
1719
|
+
const provider = generateExpr(args[0], context);
|
|
1720
|
+
const model = generateExpr(args[1], context);
|
|
1721
|
+
const text = generateExpr(args[2], context);
|
|
1722
|
+
const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
|
|
1723
|
+
return `await __aiEmbed(${model}, ${text}, Object.assign({}, ${options}, { provider: ${provider} }))`;
|
|
1724
|
+
},
|
|
1617
1725
|
similarity: (args, context) => {
|
|
1618
1726
|
ensureBuiltin(context, 'ai');
|
|
1619
1727
|
return `__aiSimilarity(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
|
|
@@ -2122,6 +2230,14 @@ function requireOneArg(name, args) {
|
|
|
2122
2230
|
}
|
|
2123
2231
|
}
|
|
2124
2232
|
|
|
2233
|
+
function requireArgs(name, args, minimum, example) {
|
|
2234
|
+
if (args.length < minimum) {
|
|
2235
|
+
throw new Error(
|
|
2236
|
+
`"${name}" needs at least ${minimum} argument${minimum === 1 ? '' : 's'}.\n\nExample:\n ${example}`
|
|
2237
|
+
);
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2125
2241
|
// Set to true while generating inside a route handler body.
|
|
2126
2242
|
// Remaps PlainScript's "request" → "req" and "response" → "res".
|
|
2127
2243
|
let _inRoute = false;
|
|
@@ -2163,6 +2279,13 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
2163
2279
|
markAsync(context);
|
|
2164
2280
|
return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
|
|
2165
2281
|
}
|
|
2282
|
+
if (_sqlDriver === 'mongo') {
|
|
2283
|
+
markAsync(context);
|
|
2284
|
+
// For MongoDB, we delegate to helper functions that parse SQL-like syntax
|
|
2285
|
+
// into MongoDB operations. This is a simplified approach.
|
|
2286
|
+
// All MongoDB operations are async, so always await them.
|
|
2287
|
+
return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
|
|
2288
|
+
}
|
|
2166
2289
|
switch (kind) {
|
|
2167
2290
|
case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
|
|
2168
2291
|
case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
|
|
@@ -2171,7 +2294,14 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
2171
2294
|
}
|
|
2172
2295
|
}
|
|
2173
2296
|
|
|
2174
|
-
function createGenerationContext() {
|
|
2297
|
+
function createGenerationContext(options = {}) {
|
|
2298
|
+
const sourceMap = options.sourceMap || false;
|
|
2299
|
+
const sourceFile = options.sourceFile || 'source.pln';
|
|
2300
|
+
const sourceContent = options.sourceContent || null;
|
|
2301
|
+
const builder = sourceMap ? new SourceMapGenerator({ file: options.outputFile || (sourceFile ? sourceFile.replace(/\.pln$/, '.js') : 'output.js') }) : null;
|
|
2302
|
+
if (builder && sourceFile) {
|
|
2303
|
+
builder.addSource(sourceFile, sourceContent);
|
|
2304
|
+
}
|
|
2175
2305
|
return {
|
|
2176
2306
|
requires: new Set(),
|
|
2177
2307
|
pendingPrelude: [],
|
|
@@ -2180,6 +2310,11 @@ function createGenerationContext() {
|
|
|
2180
2310
|
inFunction: false, // true while generating inside a function-like scope
|
|
2181
2311
|
inHandler: false, // true while generating a route/listener/404 response body
|
|
2182
2312
|
loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
|
|
2313
|
+
sourceMap,
|
|
2314
|
+
sourceFile,
|
|
2315
|
+
sourceContent,
|
|
2316
|
+
sourceMapBuilder: builder,
|
|
2317
|
+
currentLine: 1,
|
|
2183
2318
|
};
|
|
2184
2319
|
}
|
|
2185
2320
|
|
|
@@ -2211,9 +2346,11 @@ function emitRequire(context, moduleName, alias) {
|
|
|
2211
2346
|
const known = KNOWN_PACKAGES[bareName];
|
|
2212
2347
|
if (known) {
|
|
2213
2348
|
const boundAs = known.match(/const (\w+)/)[1];
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2349
|
+
if (alias !== boundAs) {
|
|
2350
|
+
throw new Error(
|
|
2351
|
+
`"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
|
|
2352
|
+
);
|
|
2353
|
+
}
|
|
2217
2354
|
}
|
|
2218
2355
|
const key = `${npmName}\0${alias}`;
|
|
2219
2356
|
if (context.requires.has(key)) return '';
|
|
@@ -2259,9 +2396,30 @@ function containsYield(statements) {
|
|
|
2259
2396
|
return false;
|
|
2260
2397
|
}
|
|
2261
2398
|
|
|
2262
|
-
function
|
|
2399
|
+
function recordMapping(node, context) {
|
|
2400
|
+
if (context && context.sourceMapBuilder && node && typeof node === 'object' && node.line) {
|
|
2401
|
+
context.sourceMapBuilder.addMapping({
|
|
2402
|
+
generated: { line: context.currentLine, column: 0 },
|
|
2403
|
+
original: { line: node.line, column: node.col || 1 },
|
|
2404
|
+
source: context.sourceFile,
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
function generate(ast, contextOrOptions = createGenerationContext(), options = {}) {
|
|
2410
|
+
if (ast.type !== 'Program') {
|
|
2263
2411
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
2264
2412
|
}
|
|
2413
|
+
|
|
2414
|
+
let context;
|
|
2415
|
+
let opts = options;
|
|
2416
|
+
if (contextOrOptions && contextOrOptions.requires instanceof Set) {
|
|
2417
|
+
context = contextOrOptions;
|
|
2418
|
+
} else {
|
|
2419
|
+
opts = contextOrOptions || {};
|
|
2420
|
+
context = createGenerationContext(opts);
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2265
2423
|
// v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
|
|
2266
2424
|
// (build pipeline) start clean.
|
|
2267
2425
|
__testCount = 0;
|
|
@@ -2269,8 +2427,27 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2269
2427
|
__inTest = false;
|
|
2270
2428
|
|
|
2271
2429
|
const preludeStart = context.pendingPrelude.length;
|
|
2272
|
-
|
|
2273
|
-
const
|
|
2430
|
+
|
|
2431
|
+
const bodyParts = [];
|
|
2432
|
+
for (const node of ast.body) {
|
|
2433
|
+
recordMapping(node, context);
|
|
2434
|
+
const js = generateStatement(node, '', context);
|
|
2435
|
+
if (js) {
|
|
2436
|
+
bodyParts.push(js);
|
|
2437
|
+
context.currentLine += js.split('\n').length;
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
const preludeLines = context.pendingPrelude.slice(preludeStart);
|
|
2442
|
+
if (preludeLines.length > 0 && context.sourceMapBuilder) {
|
|
2443
|
+
for (const m of context.sourceMapBuilder.mappings) {
|
|
2444
|
+
m.generatedLine += preludeLines.length;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
const body = bodyParts.join('\n');
|
|
2449
|
+
const lines = preludeLines.concat(body).filter(Boolean);
|
|
2450
|
+
|
|
2274
2451
|
// Top-level functions are the module's public API: export them so a built
|
|
2275
2452
|
// PlainScript file works as a normal CommonJS module (npm packages, require()).
|
|
2276
2453
|
// Harmless for programs that are only executed.
|
|
@@ -2316,7 +2493,16 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2316
2493
|
lines.push(`__runTests();`);
|
|
2317
2494
|
}
|
|
2318
2495
|
|
|
2319
|
-
|
|
2496
|
+
const jsCode = lines.join('\n');
|
|
2497
|
+
if (context.sourceMap && context.sourceMapBuilder) {
|
|
2498
|
+
return {
|
|
2499
|
+
code: jsCode,
|
|
2500
|
+
map: context.sourceMapBuilder,
|
|
2501
|
+
mapObject: context.sourceMapBuilder.toJSON(),
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
return jsCode;
|
|
2320
2506
|
}
|
|
2321
2507
|
|
|
2322
2508
|
// ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
|
|
@@ -2469,9 +2655,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2469
2655
|
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
2470
2656
|
}
|
|
2471
2657
|
|
|
2472
|
-
//
|
|
2473
|
-
case 'ExportStatement':
|
|
2474
|
-
|
|
2658
|
+
// Enterprise & Intent-Oriented Exporting
|
|
2659
|
+
case 'ExportStatement': {
|
|
2660
|
+
if (node.exportAll && node.fromPath) {
|
|
2661
|
+
return `${indent}Object.assign(module.exports, require(${JSON.stringify(node.fromPath)}));`;
|
|
2662
|
+
}
|
|
2663
|
+
const names = node.names || (node.name ? [node.name] : []);
|
|
2664
|
+
if (node.fromPath) {
|
|
2665
|
+
const exports = names.map(n => `module.exports.${n} = require(${JSON.stringify(node.fromPath)}).${n};`);
|
|
2666
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
2667
|
+
}
|
|
2668
|
+
const exports = names.map(n => `module.exports.${n} = ${n};`);
|
|
2669
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
2670
|
+
}
|
|
2475
2671
|
|
|
2476
2672
|
// v1.0.1 — generators: `yield <expr>` (or bare `yield`).
|
|
2477
2673
|
case 'YieldStatement': {
|
|
@@ -2483,11 +2679,53 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2483
2679
|
: `${indent}yield;`;
|
|
2484
2680
|
}
|
|
2485
2681
|
|
|
2682
|
+
case 'PutStatement': {
|
|
2683
|
+
const target = generateExpr(node.mapVar, context);
|
|
2684
|
+
const key = generateExpr(node.key, context);
|
|
2685
|
+
const val = generateExpr(node.value, context);
|
|
2686
|
+
return `${indent}${target}.set(${key}, ${val});`;
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
case 'UnpackStatement': {
|
|
2690
|
+
const tuple = generateExpr(node.tupleExpr, context);
|
|
2691
|
+
const vars = node.variables.join(', ');
|
|
2692
|
+
return `${indent}let [${vars}] = ${tuple};`;
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2486
2695
|
case 'ExpressionStatement':
|
|
2487
2696
|
return `${indent}${generateExpr(node.expression, context)};`;
|
|
2488
2697
|
|
|
2489
|
-
|
|
2490
|
-
|
|
2698
|
+
// Enterprise & Intent-Oriented Importing
|
|
2699
|
+
case 'ImportStatement': {
|
|
2700
|
+
if (!node.path) return '';
|
|
2701
|
+
const isLocalFile = node.path.startsWith('.') || node.path.startsWith('/') || node.path.startsWith('\\') || node.path.startsWith('@/') || node.path.endsWith('.pln');
|
|
2702
|
+
if (!isLocalFile) {
|
|
2703
|
+
// Third-party npm package import
|
|
2704
|
+
if (node.namespace) {
|
|
2705
|
+
const pkg = emitRequire(context, node.path, node.namespace);
|
|
2706
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2707
|
+
}
|
|
2708
|
+
if (node.defaultImport) {
|
|
2709
|
+
const pkg = emitRequire(context, node.path, node.defaultImport);
|
|
2710
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2711
|
+
}
|
|
2712
|
+
if (node.names && node.names.length > 0) {
|
|
2713
|
+
const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
2714
|
+
emitRequire(context, node.path, `__pkg_${reqName}`);
|
|
2715
|
+
const destructuring = `const { ${node.names.join(', ')} } = __pkg_${reqName};`;
|
|
2716
|
+
return `${indent}${destructuring}`;
|
|
2717
|
+
}
|
|
2718
|
+
const pkg = emitRequire(context, node.path, null);
|
|
2719
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
// Local PlainScript module import
|
|
2723
|
+
if (node.namespace) {
|
|
2724
|
+
const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
2725
|
+
return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
|
|
2726
|
+
}
|
|
2727
|
+
return '';
|
|
2728
|
+
}
|
|
2491
2729
|
|
|
2492
2730
|
case 'UseStatement': {
|
|
2493
2731
|
const pkg = emitRequire(context, node.module, node.alias);
|
|
@@ -2683,6 +2921,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2683
2921
|
}
|
|
2684
2922
|
return `${indent}res.send(${generateExpr(node.value, context)});`;
|
|
2685
2923
|
|
|
2924
|
+
case 'ReplyFileStatement':
|
|
2925
|
+
if (!_inRoute) {
|
|
2926
|
+
throw new Error('"reply file" can only be used inside a route handler.\n\nExample:\n route get "/"\n reply file "public/index.html"\n done');
|
|
2927
|
+
}
|
|
2928
|
+
// Use path.resolve to handle relative paths correctly
|
|
2929
|
+
return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
|
|
2930
|
+
|
|
2686
2931
|
case 'ReplyJsonStatement': {
|
|
2687
2932
|
const props = node.properties
|
|
2688
2933
|
.map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
|
|
@@ -2971,6 +3216,21 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2971
3216
|
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
2972
3217
|
}
|
|
2973
3218
|
|
|
3219
|
+
// v2.2.0 — mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
|
|
3220
|
+
// Uses the mongodb driver; subsequent query/insert/update/delete/execute
|
|
3221
|
+
// statements compile to MongoDB collection operations.
|
|
3222
|
+
case 'MongoStatement': {
|
|
3223
|
+
_sqlDriver = 'mongo';
|
|
3224
|
+
_sqlClientVar = 'db';
|
|
3225
|
+
markAsync(context);
|
|
3226
|
+
ensureBuiltin(context, 'mongodb');
|
|
3227
|
+
const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
|
|
3228
|
+
return [
|
|
3229
|
+
emitRequire(context, 'mongodb'),
|
|
3230
|
+
`${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
|
|
3231
|
+
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
3232
|
+
}
|
|
3233
|
+
|
|
2974
3234
|
case 'QueryStatement':
|
|
2975
3235
|
return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
|
|
2976
3236
|
|
|
@@ -3198,6 +3458,20 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3198
3458
|
`${indent}});`,
|
|
3199
3459
|
].join('\n');
|
|
3200
3460
|
|
|
3461
|
+
case 'StringTransformStatement': {
|
|
3462
|
+
const method = { lowercase: 'toLowerCase', uppercase: 'toUpperCase', trim: 'trim' }[node.kind];
|
|
3463
|
+
return `${indent}${node.target} = String(${node.target}).${method}();`;
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
case 'CapitalizeWordsStatement':
|
|
3467
|
+
return `${indent}${node.target} = (${node.target}).map(w => String(w).charAt(0).toUpperCase() + String(w).slice(1));`;
|
|
3468
|
+
|
|
3469
|
+
case 'SplitStatement':
|
|
3470
|
+
return `${indent}${node.target} = String(${node.target}).split(${generateExpr(node.separator, context)});`;
|
|
3471
|
+
|
|
3472
|
+
case 'JoinStatement':
|
|
3473
|
+
return `${indent}(${node.target}) = (${node.target}).join(${generateExpr(node.separator, context)});`;
|
|
3474
|
+
|
|
3201
3475
|
case 'WebSocketServerStatement': {
|
|
3202
3476
|
ensureBuiltin(context, 'websocket');
|
|
3203
3477
|
const handler = (name, params, body) => {
|
|
@@ -3218,6 +3492,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3218
3492
|
ensureBuiltin(context, 'websocket');
|
|
3219
3493
|
return `${indent}__wsSend(socket, ${generateExpr(node.value, context)});`;
|
|
3220
3494
|
|
|
3495
|
+
case 'SendToStatement':
|
|
3496
|
+
ensureBuiltin(context, 'websocket');
|
|
3497
|
+
return `${indent}__wsSend(${generateExpr(node.connection, context)}, ${generateExpr(node.value, context)});`;
|
|
3498
|
+
|
|
3221
3499
|
case 'BroadcastStatement':
|
|
3222
3500
|
ensureBuiltin(context, 'websocket');
|
|
3223
3501
|
return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
|
|
@@ -3317,6 +3595,53 @@ function generateLValue(node, context) {
|
|
|
3317
3595
|
|
|
3318
3596
|
function generateExpr(node, context = createGenerationContext()) {
|
|
3319
3597
|
switch (node.type) {
|
|
3598
|
+
case 'DictionaryLiteral': {
|
|
3599
|
+
if (!node.pairs || node.pairs.length === 0) return 'new Map()';
|
|
3600
|
+
const pairs = node.pairs.map(p => `[${generateExpr(p.key, context)}, ${generateExpr(p.value, context)}]`);
|
|
3601
|
+
return `new Map([${pairs.join(', ')}])`;
|
|
3602
|
+
}
|
|
3603
|
+
case 'SetLiteral': {
|
|
3604
|
+
if (!node.elements || node.elements.length === 0) return 'new Set()';
|
|
3605
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3606
|
+
return `new Set([${elements.join(', ')}])`;
|
|
3607
|
+
}
|
|
3608
|
+
case 'SetFromExpression': {
|
|
3609
|
+
return `new Set(${generateExpr(node.iterable, context)})`;
|
|
3610
|
+
}
|
|
3611
|
+
case 'TupleLiteral': {
|
|
3612
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3613
|
+
return `Object.freeze([${elements.join(', ')}])`;
|
|
3614
|
+
}
|
|
3615
|
+
case 'SetAlgebraExpression': {
|
|
3616
|
+
const left = generateExpr(node.left, context);
|
|
3617
|
+
const right = generateExpr(node.right, context);
|
|
3618
|
+
if (node.op === 'union') {
|
|
3619
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3620
|
+
}
|
|
3621
|
+
if (node.op === 'intersection' || node.op === 'intersect') {
|
|
3622
|
+
return `new Set([...${left}].filter(__x => ${right}.has(__x)))`;
|
|
3623
|
+
}
|
|
3624
|
+
if (node.op === 'difference') {
|
|
3625
|
+
return `new Set([...${left}].filter(__x => !${right}.has(__x)))`;
|
|
3626
|
+
}
|
|
3627
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3628
|
+
}
|
|
3629
|
+
case 'CollectionReflectExpression': {
|
|
3630
|
+
const target = generateExpr(node.target, context);
|
|
3631
|
+
if (node.accessor === 'keys') {
|
|
3632
|
+
return `Array.from(${target}.keys())`;
|
|
3633
|
+
}
|
|
3634
|
+
if (node.accessor === 'values') {
|
|
3635
|
+
return `Array.from(${target}.values())`;
|
|
3636
|
+
}
|
|
3637
|
+
if (node.accessor === 'entries') {
|
|
3638
|
+
return `Array.from(${target}.entries())`;
|
|
3639
|
+
}
|
|
3640
|
+
if (node.accessor === 'size') {
|
|
3641
|
+
return `(${target} instanceof Map || ${target} instanceof Set ? ${target}.size : (${target} && ${target}.size !== undefined ? ${target}.size : ${target}?.length))`;
|
|
3642
|
+
}
|
|
3643
|
+
return `${target}.${node.accessor}`;
|
|
3644
|
+
}
|
|
3320
3645
|
case 'StringLiteral': return JSON.stringify(node.value);
|
|
3321
3646
|
case 'NumberLiteral': return String(node.value);
|
|
3322
3647
|
// v2.1.1 — boolean and null literals are PlainScript keywords.
|
|
@@ -3358,6 +3683,18 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
3358
3683
|
// Inside route handlers, remap PlainScript's request/response to req/res
|
|
3359
3684
|
if (_inRoute && node.name === 'request') return 'req';
|
|
3360
3685
|
if (_inRoute && node.name === 'response') return 'res';
|
|
3686
|
+
if (_inTelegram) {
|
|
3687
|
+
const telegramContext = {
|
|
3688
|
+
message: 'ctx.message',
|
|
3689
|
+
chat: 'ctx.chat',
|
|
3690
|
+
chatId: 'ctx.chatId',
|
|
3691
|
+
text: 'ctx.text',
|
|
3692
|
+
args: 'ctx.args',
|
|
3693
|
+
matches: 'ctx.matches',
|
|
3694
|
+
data: 'ctx.data',
|
|
3695
|
+
};
|
|
3696
|
+
if (telegramContext[node.name]) return telegramContext[node.name];
|
|
3697
|
+
}
|
|
3361
3698
|
// Inside WhatsApp "on message" handlers, PlainScript's "message" is the
|
|
3362
3699
|
// normalized record of the current delivery.
|
|
3363
3700
|
if (_inWhatsApp && node.name === 'message') return '__waCtx.message';
|
package/compiler/lexer.js
CHANGED
|
@@ -49,6 +49,7 @@ const TOKEN = {
|
|
|
49
49
|
RESPOND: 'RESPOND', // alias for reply
|
|
50
50
|
SEND_BACK: 'SEND_BACK', // alias for reply
|
|
51
51
|
JSON_KW: 'JSON_KW',
|
|
52
|
+
FILE_KW: 'FILE_KW', // for "reply file" and "serve file"
|
|
52
53
|
SERVE: 'SERVE',
|
|
53
54
|
SERVE_STATIC: 'SERVE_STATIC', // alias for serve folder
|
|
54
55
|
SERVE_PUBLIC: 'SERVE_PUBLIC', // alias for serve folder
|
|
@@ -209,6 +210,7 @@ const KEYWORDS = {
|
|
|
209
210
|
respond: TOKEN.RESPOND,
|
|
210
211
|
send_back: TOKEN.SEND_BACK,
|
|
211
212
|
json: TOKEN.JSON_KW,
|
|
213
|
+
file: TOKEN.FILE_KW,
|
|
212
214
|
serve: TOKEN.SERVE,
|
|
213
215
|
serve_static: TOKEN.SERVE_STATIC,
|
|
214
216
|
serve_public: TOKEN.SERVE_PUBLIC,
|