plainscript-lang 1.0.0-beta → 1.0.0-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.
- package/README.md +41 -8
- package/compiler/cli.js +127 -18
- package/compiler/generator.js +276 -30
- package/compiler/lexer.js +1 -1
- package/compiler/parser.js +139 -12
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +68 -8
- package/docs/PLINJS_SPEC.md +3 -3
- package/docs/index.html +25 -20
- package/docs/website/script.js +1 -1
- package/examples/auth-api.ps +56 -0
- package/examples/concurrency.ps +49 -0
- package/examples/error-handling.ps +54 -0
- package/examples/file-uploads.ps +39 -0
- package/examples/files-and-config.ps +47 -0
- package/examples/http-client.ps +44 -0
- package/examples/modules/app.ps +16 -0
- package/examples/modules/math.ps +20 -0
- package/examples/record-kinds.ps +43 -0
- package/examples/search-and-filter.ps +34 -0
- package/examples/sessions-and-cookies.ps +54 -0
- package/package.json +2 -2
package/compiler/generator.js
CHANGED
|
@@ -40,7 +40,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
40
40
|
fs: `const fs = require('fs');`,
|
|
41
41
|
path: `const path = require('path');`,
|
|
42
42
|
crypto: `const crypto = require('crypto');`,
|
|
43
|
-
// v1.0.0 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
|
|
43
|
+
// v1.0.0-latest — env-file runtime. Applies KEY=VALUE pairs from a .env file to
|
|
44
44
|
// process.env. Blank lines and `#` comment lines are skipped.
|
|
45
45
|
dotenv: [
|
|
46
46
|
`function __loadEnvFile(path) {`,
|
|
@@ -86,7 +86,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
86
86
|
` }`,
|
|
87
87
|
`}`,
|
|
88
88
|
].join('\n'),
|
|
89
|
-
// v1.0.0 — shared runtime helpers for reflection, binary-size, YAML subset
|
|
89
|
+
// v1.0.0-latest — shared runtime helpers for reflection, binary-size, YAML subset
|
|
90
90
|
// parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
|
|
91
91
|
// when any feature that needs them is used.
|
|
92
92
|
core: [
|
|
@@ -219,7 +219,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
219
219
|
` });`,
|
|
220
220
|
`}`,
|
|
221
221
|
].join('\n'),
|
|
222
|
-
// v1.0.0 — process execution (child processes).
|
|
222
|
+
// v1.0.0-latest — process execution (child processes).
|
|
223
223
|
process: [
|
|
224
224
|
`const { execFile } = require('child_process');`,
|
|
225
225
|
`function __runCommand(command, args) {`,
|
|
@@ -230,11 +230,54 @@ const BUILTIN_DECLARATIONS = {
|
|
|
230
230
|
` });`,
|
|
231
231
|
`}`,
|
|
232
232
|
].join('\n'),
|
|
233
|
-
// v1.0.0 — Map helpers.
|
|
233
|
+
// v1.0.0-latest — Map helpers.
|
|
234
234
|
mapset: [
|
|
235
235
|
`function __mapSet(map, key, value) { map.set(key, value); return map; }`,
|
|
236
236
|
].join('\n'),
|
|
237
|
-
//
|
|
237
|
+
// v2.2.0 — collection primitives (flatten / pick / omit / groupBy).
|
|
238
|
+
coll: [
|
|
239
|
+
`function __flatten(list) {`,
|
|
240
|
+
` const out = [];`,
|
|
241
|
+
` (function rec(x) {`,
|
|
242
|
+
` if (Array.isArray(x)) { for (const i of x) rec(i); }`,
|
|
243
|
+
` else out.push(x);`,
|
|
244
|
+
` })(list);`,
|
|
245
|
+
` return out;`,
|
|
246
|
+
`}`,
|
|
247
|
+
`function __pick(obj) {`,
|
|
248
|
+
` const out = {};`,
|
|
249
|
+
` for (let i = 1; i < arguments.length; i++) {`,
|
|
250
|
+
` const k = arguments[i];`,
|
|
251
|
+
` if (obj != null && Object.prototype.hasOwnProperty.call(obj, k)) out[k] = obj[k];`,
|
|
252
|
+
` }`,
|
|
253
|
+
` return out;`,
|
|
254
|
+
`}`,
|
|
255
|
+
`function __omit(obj) {`,
|
|
256
|
+
` const skip = new Set([].slice.call(arguments, 1));`,
|
|
257
|
+
` const out = {};`,
|
|
258
|
+
` if (obj != null) for (const k of Object.keys(obj)) if (!skip.has(k)) out[k] = obj[k];`,
|
|
259
|
+
` return out;`,
|
|
260
|
+
`}`,
|
|
261
|
+
`function __groupBy(list, keyFn) {`,
|
|
262
|
+
` const out = {};`,
|
|
263
|
+
` for (const item of (list || [])) {`,
|
|
264
|
+
` const k = typeof keyFn === 'function' ? keyFn(item) : (item == null ? undefined : item[keyFn]);`,
|
|
265
|
+
` (out[k] = out[k] || []).push(item);`,
|
|
266
|
+
` }`,
|
|
267
|
+
` return out;`,
|
|
268
|
+
`}`,
|
|
269
|
+
`function __paginate(list, page, perPage) {`,
|
|
270
|
+
` const items = (list || []);`,
|
|
271
|
+
` const total = items.length;`,
|
|
272
|
+
` perPage = Math.max(1, perPage == null ? 10 : Number(perPage));`,
|
|
273
|
+
` const pages = Math.max(1, Math.ceil(total / perPage));`,
|
|
274
|
+
` page = Math.min(Math.max(1, page == null ? 1 : Number(page)), pages);`,
|
|
275
|
+
` const start = (page - 1) * perPage;`,
|
|
276
|
+
` const slice = items.slice(start, start + perPage);`,
|
|
277
|
+
` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
|
|
278
|
+
`}`,
|
|
279
|
+
].join('\n'),
|
|
280
|
+
// v1.0.0-latest — dynamic module loader.
|
|
238
281
|
loadmodule: [
|
|
239
282
|
`function __loadModule(spec) {`,
|
|
240
283
|
` const path = require('path');`,
|
|
@@ -243,7 +286,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
243
286
|
` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
|
|
244
287
|
`}`,
|
|
245
288
|
].join('\n'),
|
|
246
|
-
// v1.0.0 — recursive directory walker (returns full paths, files first).
|
|
289
|
+
// v1.0.0-latest — recursive directory walker (returns full paths, files first).
|
|
247
290
|
walk: [
|
|
248
291
|
`function __walkFolder(dir) {`,
|
|
249
292
|
` const fs = require('fs');`,
|
|
@@ -315,11 +358,28 @@ const BUILTIN_DECLARATIONS = {
|
|
|
315
358
|
// created by the "cache" statement; accessors fail with a teaching error
|
|
316
359
|
// when no cache was configured.
|
|
317
360
|
cache: [
|
|
318
|
-
`let __cache = null
|
|
361
|
+
`let __cache = null; // optional Redis client, set by the "cache" statement`,
|
|
362
|
+
`const __memCache = new Map(); // in-memory fallback cache: key -> { value, exp }`,
|
|
319
363
|
`function __cacheClient() {`,
|
|
320
|
-
` if (!__cache) throw new Error('Cache: no cache configured. Add a cache "<redis-url>" statement first.');`,
|
|
321
364
|
` return __cache;`,
|
|
322
365
|
`}`,
|
|
366
|
+
`async function __cacheGet(key) {`,
|
|
367
|
+
` if (__cache) return __cache.get(key);`,
|
|
368
|
+
` const entry = __memCache.get(key);`,
|
|
369
|
+
` if (!entry) return null;`,
|
|
370
|
+
` if (entry.exp != null && Date.now() > entry.exp) { __memCache.delete(key); return null; }`,
|
|
371
|
+
` return entry.value;`,
|
|
372
|
+
`}`,
|
|
373
|
+
`async function __cacheSet(key, value, ttlSeconds) {`,
|
|
374
|
+
` if (__cache) return __cache.set(key, value, ttlSeconds == null ? undefined : { EX: ttlSeconds });`,
|
|
375
|
+
` const exp = ttlSeconds == null ? null : Date.now() + ttlSeconds * 1000;`,
|
|
376
|
+
` __memCache.set(key, { value, exp });`,
|
|
377
|
+
` return 'OK';`,
|
|
378
|
+
`}`,
|
|
379
|
+
`async function __cacheDelete(key) {`,
|
|
380
|
+
` if (__cache) return __cache.del(key);`,
|
|
381
|
+
` return __memCache.delete(key) ? 1 : 0;`,
|
|
382
|
+
`}`,
|
|
323
383
|
].join('\n'),
|
|
324
384
|
// v2.1.1 — WhatsApp runtime (@whiskeysockets/baileys behind the
|
|
325
385
|
// "whatsapp bot" block). Everything Baileys-shaped stays in here: socket
|
|
@@ -516,6 +576,53 @@ const BUILTIN_DECLARATIONS = {
|
|
|
516
576
|
` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
|
|
517
577
|
`}`,
|
|
518
578
|
].join('\n'),
|
|
579
|
+
// v2.2.0 — AI/ML runtime. `chat` and `embeddings` talk to any OpenAI-compatible
|
|
580
|
+
// completions/embeddings endpoint (API key and base URL from options or env),
|
|
581
|
+
// while `similarity` is pure vector math and runs fully offline.
|
|
582
|
+
ai: [
|
|
583
|
+
`function __aiTags() {`,
|
|
584
|
+
` return { key: process.env.OPENAI_API_KEY, base: (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\\/$/, '') };`,
|
|
585
|
+
`}`,
|
|
586
|
+
`async function __aiPost(tags, path, body) {`,
|
|
587
|
+
` if (typeof fetch !== 'function') {`,
|
|
588
|
+
` throw new Error('AI calls need Node.js 18 or newer (global fetch is missing): ' + process.version);`,
|
|
589
|
+
` }`,
|
|
590
|
+
` if (!tags.key) throw new Error('No API key for AI. Set env OPENAI_API_KEY.');`,
|
|
591
|
+
` const response = await fetch(tags.base + path, {`,
|
|
592
|
+
` method: 'POST',`,
|
|
593
|
+
` headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key },`,
|
|
594
|
+
` body: JSON.stringify(body),`,
|
|
595
|
+
` });`,
|
|
596
|
+
` const text = await response.text();`,
|
|
597
|
+
` let data = text;`,
|
|
598
|
+
` try { data = JSON.parse(text); } catch (_) {}`,
|
|
599
|
+
` if (!response.ok) throw new Error('AI request failed (' + response.status + '): ' + (data && data.error && data.error.message ? data.error.message : text));`,
|
|
600
|
+
` return data;`,
|
|
601
|
+
`}`,
|
|
602
|
+
`async function __aiChat(model, messages, options) {`,
|
|
603
|
+
` const tags = __aiTags();`,
|
|
604
|
+
` if (options && options.key) tags.key = options.key;`,
|
|
605
|
+
` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
|
|
606
|
+
` if (typeof messages === 'string') messages = [{ role: 'user', content: messages }];`,
|
|
607
|
+
` const data = await __aiPost(tags, '/chat/completions', { model: model, messages: messages });`,
|
|
608
|
+
` const choice = data.choices && data.choices[0];`,
|
|
609
|
+
` return choice && choice.message ? choice.message.content : '';`,
|
|
610
|
+
`}`,
|
|
611
|
+
`async function __aiEmbed(model, text, options) {`,
|
|
612
|
+
` const tags = __aiTags();`,
|
|
613
|
+
` if (options && options.key) tags.key = options.key;`,
|
|
614
|
+
` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
|
|
615
|
+
` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) });`,
|
|
616
|
+
` return (data.data && data.data[0] && data.data[0].embedding) || [];`,
|
|
617
|
+
`}`,
|
|
618
|
+
`function __aiSimilarity(a, b) {`,
|
|
619
|
+
` if (!Array.isArray(a) || !Array.isArray(b) || !a.length || a.length !== b.length) return 0;`,
|
|
620
|
+
` let dot = 0, na = 0, nb = 0;`,
|
|
621
|
+
` for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }`,
|
|
622
|
+
` if (na === 0 || nb === 0) return 0;`,
|
|
623
|
+
` return dot / (Math.sqrt(na) * Math.sqrt(nb));`,
|
|
624
|
+
`}`,
|
|
625
|
+
].join('\n'),
|
|
519
626
|
// v2.1.1 — file upload runtime (multer behind "accept uploads"). Files are
|
|
520
627
|
// held in memory by default or written to disk when a folder is given.
|
|
521
628
|
// Normalised records expose: name, type, size, data (buffer) and path.
|
|
@@ -1042,6 +1149,18 @@ const STDLIB = {
|
|
|
1042
1149
|
param: (args, context) => routeAccessor('param', 'params', args, context),
|
|
1043
1150
|
query: (args, context) => routeAccessor('query', 'query', args, context),
|
|
1044
1151
|
header: (args, context) => routeAccessor('header', 'headers', args, context),
|
|
1152
|
+
// The parsed JSON request body (from `web app`'s express.json()). With no
|
|
1153
|
+
// argument returns the whole body record; with one, that field's value.
|
|
1154
|
+
body: (args, context) => {
|
|
1155
|
+
if (!_inRoute) {
|
|
1156
|
+
throw new Error(
|
|
1157
|
+
`"body(...)" can only be used inside a route handler.\n\nExample:\n route post "/items"\n show body("name")\n done`
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
const base = 'req.body';
|
|
1161
|
+
if (!args || args.length === 0) return base;
|
|
1162
|
+
return `${base}[${generateExpr(args[0], context)}]`;
|
|
1163
|
+
},
|
|
1045
1164
|
// v2.1.0 — request validation. Returns the list of missing required fields.
|
|
1046
1165
|
validate: (args, context) => {
|
|
1047
1166
|
ensureBuiltin(context, 'validation');
|
|
@@ -1097,7 +1216,52 @@ const STDLIB = {
|
|
|
1097
1216
|
hasKey: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
|
|
1098
1217
|
merge: (args, context) => `{ ...${generateExpr(args[0], context)}, ...${generateExpr(args[1], context)} }`,
|
|
1099
1218
|
|
|
1100
|
-
// ──
|
|
1219
|
+
// ── v2.2.0 — collection & string primitives (IOPL-native, dependency-free).
|
|
1220
|
+
// A numeric range [start..end], stepping by 1 (or `step` when given).
|
|
1221
|
+
range: (args, context) => {
|
|
1222
|
+
const start = generateExpr(args[0], context);
|
|
1223
|
+
const end = args.length > 1 ? generateExpr(args[1], context) : null;
|
|
1224
|
+
const step = args.length > 2 ? generateExpr(args[2], context) : null;
|
|
1225
|
+
if (end === null) return `Array.from({ length: Math.max(0, ${start}) }, (_, i) => i)`;
|
|
1226
|
+
const s = step === null ? `(${start} <= ${end} ? 1 : -1)` : `Math.abs(${step}) * (${start} <= ${end} ? 1 : -1)`;
|
|
1227
|
+
return `Array.from((() => { const __r = []; for (let __i = ${start}; ${start} <= ${end} ? __i < ${end} : __i > ${end}; __i += ${s}) __r.push(__i); return __r; })())`;
|
|
1228
|
+
},
|
|
1229
|
+
clamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
|
|
1230
|
+
first: (args, context) => `(${generateExpr(args[0], context)})[0]`,
|
|
1231
|
+
last: (args, context) => `(${generateExpr(args[0], context)})[(${generateExpr(args[0], context)}).length - 1]`,
|
|
1232
|
+
flatten: (args, context) => {
|
|
1233
|
+
ensureBuiltin(context, 'coll');
|
|
1234
|
+
return `__flatten(${generateExpr(args[0], context)})`;
|
|
1235
|
+
},
|
|
1236
|
+
includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)})`,
|
|
1237
|
+
paginate: (args, context) => {
|
|
1238
|
+
ensureBuiltin(context, 'coll');
|
|
1239
|
+
return `__paginate(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${args.length > 2 ? generateExpr(args[2], context) : '10'})`;
|
|
1240
|
+
},
|
|
1241
|
+
pick: (args, context) => {
|
|
1242
|
+
ensureBuiltin(context, 'coll');
|
|
1243
|
+
return `__pick(${generateExpr(args[0], context)}, ${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`;
|
|
1244
|
+
},
|
|
1245
|
+
omit: (args, context) => {
|
|
1246
|
+
ensureBuiltin(context, 'coll');
|
|
1247
|
+
return `__omit(${generateExpr(args[0], context)}, ${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`;
|
|
1248
|
+
},
|
|
1249
|
+
groupBy: (args, context) => {
|
|
1250
|
+
ensureBuiltin(context, 'coll');
|
|
1251
|
+
return `__groupBy(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
|
|
1252
|
+
},
|
|
1253
|
+
startsWith: (args, context) => `String(${generateExpr(args[0], context)}).startsWith(String(${generateExpr(args[1], context)}))`,
|
|
1254
|
+
endsWith: (args, context) => `String(${generateExpr(args[0], context)}).endsWith(String(${generateExpr(args[1], context)}))`,
|
|
1255
|
+
truncate: (args, context) => {
|
|
1256
|
+
const text = `String(${generateExpr(args[0], context)})`;
|
|
1257
|
+
const n = generateExpr(args[1], context);
|
|
1258
|
+
const suffix = args.length > 2 ? generateExpr(args[2], context) : '"…"';
|
|
1259
|
+
return `(${text}.length <= ${n} ? ${text} : ${text}.slice(0, ${n}) + ${suffix})`;
|
|
1260
|
+
},
|
|
1261
|
+
padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
|
|
1262
|
+
padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
|
|
1263
|
+
|
|
1264
|
+
// ── v1.0.0-latest — nullable / regex / date helpers (IOPL-native).
|
|
1101
1265
|
// first non-null, non-undefined argument — IOPL null-coalescing.
|
|
1102
1266
|
coalesce: (args, context) =>
|
|
1103
1267
|
`(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
|
|
@@ -1119,7 +1283,7 @@ const STDLIB = {
|
|
|
1119
1283
|
cacheGet: (args, context) => {
|
|
1120
1284
|
ensureBuiltin(context, 'cache');
|
|
1121
1285
|
markAsync(context);
|
|
1122
|
-
return `await
|
|
1286
|
+
return `await __cacheGet(String(${generateExpr(args[0], context)}))`;
|
|
1123
1287
|
},
|
|
1124
1288
|
cacheSet: (args, context) => {
|
|
1125
1289
|
ensureBuiltin(context, 'cache');
|
|
@@ -1127,14 +1291,14 @@ const STDLIB = {
|
|
|
1127
1291
|
const key = `String(${generateExpr(args[0], context)})`;
|
|
1128
1292
|
const value = `String(${generateExpr(args[1], context)})`;
|
|
1129
1293
|
if (args.length > 2) {
|
|
1130
|
-
return `await
|
|
1294
|
+
return `await __cacheSet(${key}, ${value}, ${generateExpr(args[2], context)})`;
|
|
1131
1295
|
}
|
|
1132
|
-
return `await
|
|
1296
|
+
return `await __cacheSet(${key}, ${value})`;
|
|
1133
1297
|
},
|
|
1134
1298
|
cacheDelete: (args, context) => {
|
|
1135
1299
|
ensureBuiltin(context, 'cache');
|
|
1136
1300
|
markAsync(context);
|
|
1137
|
-
return `await
|
|
1301
|
+
return `await __cacheDelete(String(${generateExpr(args[0], context)}))`;
|
|
1138
1302
|
},
|
|
1139
1303
|
|
|
1140
1304
|
// v2.1.0 — email sending helper (statement form uses this too).
|
|
@@ -1187,7 +1351,7 @@ const STDLIB = {
|
|
|
1187
1351
|
return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1188
1352
|
},
|
|
1189
1353
|
|
|
1190
|
-
// ── v1.0.0 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
|
|
1354
|
+
// ── v1.0.0-latest — capability-gap stdlib (reflection, binary, concurrency, ...) ──
|
|
1191
1355
|
|
|
1192
1356
|
// Reflection
|
|
1193
1357
|
typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
|
|
@@ -1248,7 +1412,7 @@ const STDLIB = {
|
|
|
1248
1412
|
// Generators / iterables
|
|
1249
1413
|
spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
|
|
1250
1414
|
|
|
1251
|
-
// v1.0.0 — dynamic module loading (the runtime companion to `import "./x.ps"`).
|
|
1415
|
+
// v1.0.0-latest — dynamic module loading (the runtime companion to `import "./x.ps"`).
|
|
1252
1416
|
// Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
|
|
1253
1417
|
// `require.resolve` from the program root.
|
|
1254
1418
|
loadModule: (args, context) => {
|
|
@@ -1256,6 +1420,30 @@ const STDLIB = {
|
|
|
1256
1420
|
return `__loadModule(${generateExpr(args[0], context)})`;
|
|
1257
1421
|
},
|
|
1258
1422
|
|
|
1423
|
+
// ── v2.2.0 — AI/ML. `chat`/`embedText` call an OpenAI-compatible endpoint
|
|
1424
|
+
// (key from OPENAI_API_KEY, base from OPENAI_BASE_URL); `similarity` runs
|
|
1425
|
+
// offline cosine similarity over any two equal-length numeric vectors.
|
|
1426
|
+
chat: (args, context) => {
|
|
1427
|
+
ensureBuiltin(context, 'ai');
|
|
1428
|
+
markAsync(context);
|
|
1429
|
+
const model = generateExpr(args[0], context);
|
|
1430
|
+
const messages = generateExpr(args[1], context);
|
|
1431
|
+
const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
|
|
1432
|
+
return `await __aiChat(${model}, ${messages}, ${options})`;
|
|
1433
|
+
},
|
|
1434
|
+
embedText: (args, context) => {
|
|
1435
|
+
ensureBuiltin(context, 'ai');
|
|
1436
|
+
markAsync(context);
|
|
1437
|
+
const model = generateExpr(args[0], context);
|
|
1438
|
+
const text = generateExpr(args[1], context);
|
|
1439
|
+
const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
|
|
1440
|
+
return `await __aiEmbed(${model}, ${text}, ${options})`;
|
|
1441
|
+
},
|
|
1442
|
+
similarity: (args, context) => {
|
|
1443
|
+
ensureBuiltin(context, 'ai');
|
|
1444
|
+
return `__aiSimilarity(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
|
|
1445
|
+
},
|
|
1446
|
+
|
|
1259
1447
|
// Map / Set
|
|
1260
1448
|
keyMap: (_args) => `new Map()`,
|
|
1261
1449
|
mapSet: (args, context) => { ensureBuiltin(context, 'mapset'); return `__mapSet(${args.map(a => generateExpr(a, context)).join(', ')})`; },
|
|
@@ -1402,6 +1590,7 @@ function createGenerationContext() {
|
|
|
1402
1590
|
pendingPrelude: [],
|
|
1403
1591
|
needsAsync: false, // true when top-level code emits await (js blocks / ask)
|
|
1404
1592
|
inFunction: false, // true while generating inside a function-like scope
|
|
1593
|
+
loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
|
|
1405
1594
|
};
|
|
1406
1595
|
}
|
|
1407
1596
|
|
|
@@ -1470,6 +1659,8 @@ function ensureBuiltin(context, moduleName) {
|
|
|
1470
1659
|
const ASYNC_CALL_NAMES = new Set([
|
|
1471
1660
|
// v2.1.0 — cache and email
|
|
1472
1661
|
'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
|
|
1662
|
+
// v2.2.0 — AI/ML calls await their model endpoint
|
|
1663
|
+
'chat', 'embedText',
|
|
1473
1664
|
// v1.2 — Telegram helpers (await their API transport)
|
|
1474
1665
|
'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
|
|
1475
1666
|
]);
|
|
@@ -1522,7 +1713,7 @@ function containsAsyncBlock(statements) {
|
|
|
1522
1713
|
if (stmt.type === 'IfStatement') {
|
|
1523
1714
|
if (containsAsyncBlock(stmt.consequent)) return true;
|
|
1524
1715
|
if (stmt.alternate && containsAsyncBlock(stmt.alternate)) return true;
|
|
1525
|
-
} else if (stmt.type !== 'FunctionDeclaration' && stmt.body) {
|
|
1716
|
+
} else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
|
|
1526
1717
|
if (containsAsyncBlock(stmt.body)) return true;
|
|
1527
1718
|
}
|
|
1528
1719
|
}
|
|
@@ -1548,7 +1739,7 @@ function containsYield(statements) {
|
|
|
1548
1739
|
function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
|
|
1549
1740
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
1550
1741
|
}
|
|
1551
|
-
// v1.0.0 — reset per-program test bookkeeping so repeated generate() calls
|
|
1742
|
+
// v1.0.0-latest — reset per-program test bookkeeping so repeated generate() calls
|
|
1552
1743
|
// (build pipeline) start clean.
|
|
1553
1744
|
__testCount = 0;
|
|
1554
1745
|
__testCatchers = [];
|
|
@@ -1570,7 +1761,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
1570
1761
|
lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
|
|
1571
1762
|
}
|
|
1572
1763
|
|
|
1573
|
-
// v1.0.0 — native test runner. When any "test ... done" block exists, emit
|
|
1764
|
+
// v1.0.0-latest — native test runner. When any "test ... done" block exists, emit
|
|
1574
1765
|
// the runner helper, register each test after its function declaration, and
|
|
1575
1766
|
// execute them. Each failure prints a message and sets process.exitCode = 1.
|
|
1576
1767
|
if (__testCatchers.length > 0) {
|
|
@@ -1605,7 +1796,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
1605
1796
|
return lines.join('\n');
|
|
1606
1797
|
}
|
|
1607
1798
|
|
|
1608
|
-
// ── v1.0.0 — test DSL bookkeeping ───────────────────────────────────────────
|
|
1799
|
+
// ── v1.0.0-latest — test DSL bookkeeping ───────────────────────────────────────────
|
|
1609
1800
|
let __testCount = 0;
|
|
1610
1801
|
let __testCatchers = [];
|
|
1611
1802
|
let __inTest = false;
|
|
@@ -1658,7 +1849,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1658
1849
|
case 'BecomeStatement':
|
|
1659
1850
|
return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
|
|
1660
1851
|
|
|
1661
|
-
// v1.0.0 — record kinds: `define a kind called "Person" with ... done`.
|
|
1852
|
+
// v1.0.0-latest — record kinds: `define a kind called "Person" with ... done`.
|
|
1662
1853
|
// Names are emitted as a JS factory that returns a fresh plain object with
|
|
1663
1854
|
// declared defaults. Constructors prompt for required fields at compile
|
|
1664
1855
|
// time via `create a Person with ...` (see GenerateExpr CreateKind).
|
|
@@ -1682,14 +1873,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1682
1873
|
].join('\n');
|
|
1683
1874
|
}
|
|
1684
1875
|
|
|
1685
|
-
// v1.0.0 — load env file "<path>": apply KEY=VALUE pairs to process.env.
|
|
1876
|
+
// v1.0.0-latest — load env file "<path>": apply KEY=VALUE pairs to process.env.
|
|
1686
1877
|
// Blank lines and `#` comments are skipped; values keep their text.
|
|
1687
1878
|
case 'LoadEnvFileStatement': {
|
|
1688
1879
|
ensureBuiltin(context, 'dotenv');
|
|
1689
1880
|
return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
|
|
1690
1881
|
}
|
|
1691
1882
|
|
|
1692
|
-
// v1.0.0 — native test DSL. `test "<name>" ... done` registers a runnable
|
|
1883
|
+
// v1.0.0-latest — native test DSL. `test "<name>" ... done` registers a runnable
|
|
1693
1884
|
// unit; all tests are executed after the program body with a tiny runner.
|
|
1694
1885
|
case 'TestStatement': {
|
|
1695
1886
|
__testCount++;
|
|
@@ -1702,7 +1893,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1702
1893
|
return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
|
|
1703
1894
|
}
|
|
1704
1895
|
|
|
1705
|
-
// v1.0.0 — assertion `check <a> (equals|is|contains|raises) <b>`.
|
|
1896
|
+
// v1.0.0-latest — assertion `check <a> (equals|is|contains|raises) <b>`.
|
|
1706
1897
|
// For `raises`, `a` is wrapped in a thunk so the expression is evaluated
|
|
1707
1898
|
// inside the runner's try/catch (its thrown error is the subject).
|
|
1708
1899
|
case 'CheckStatement': {
|
|
@@ -1716,11 +1907,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1716
1907
|
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
1717
1908
|
}
|
|
1718
1909
|
|
|
1719
|
-
// v1.0.0 — export <name>: mark a top-level symbol for module.exports.
|
|
1910
|
+
// v1.0.0-latest — export <name>: mark a top-level symbol for module.exports.
|
|
1720
1911
|
case 'ExportStatement':
|
|
1721
1912
|
return `${indent}module.exports.${node.name} = ${node.name};`;
|
|
1722
1913
|
|
|
1723
|
-
// v1.0.0 — generators: `yield <expr>` (or bare `yield`).
|
|
1914
|
+
// v1.0.0-latest — generators: `yield <expr>` (or bare `yield`).
|
|
1724
1915
|
case 'YieldStatement': {
|
|
1725
1916
|
if (!context.inFunction) {
|
|
1726
1917
|
throw new Error('"yield" can only be used inside a function created with "make".\n\nExample:\n make countUp(n)\n let i = 0\n while i less than n\n i = i + 1\n yield i\n done\n done');
|
|
@@ -1828,16 +2019,58 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1828
2019
|
}
|
|
1829
2020
|
|
|
1830
2021
|
case 'ForEachStatement': {
|
|
2022
|
+
context.loopDepth++;
|
|
1831
2023
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2024
|
+
context.loopDepth--;
|
|
1832
2025
|
return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
|
|
1833
2026
|
}
|
|
1834
2027
|
|
|
2028
|
+
case 'ForIndexStatement': {
|
|
2029
|
+
context.loopDepth++;
|
|
2030
|
+
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2031
|
+
context.loopDepth--;
|
|
2032
|
+
// for index <name> in <collection> — zero-based index over a list.
|
|
2033
|
+
if (node.over != null) {
|
|
2034
|
+
const coll = generateExpr(node.over, context);
|
|
2035
|
+
return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
|
|
2036
|
+
}
|
|
2037
|
+
const start = generateExpr(node.start, context);
|
|
2038
|
+
const end = generateExpr(node.end, context);
|
|
2039
|
+
// Explicit step uses the user's sign; otherwise the increment follows
|
|
2040
|
+
// the direction of the bounds (from 5 to 1 counts down automatically).
|
|
2041
|
+
const inc = node.step ? generateExpr(node.step, context)
|
|
2042
|
+
: `(${start} <= ${end} ? 1 : -1)`;
|
|
2043
|
+
// Direction-aware: "from 5 to 1" counts down even without an explicit
|
|
2044
|
+
// "by", while "from 1 to 5" counts up.
|
|
2045
|
+
const test = `(${start} <= ${end} ? ${node.name} <= ${end} : ${node.name} >= ${end})`;
|
|
2046
|
+
return `${indent}for (let ${node.name} = ${start}; ${test}; ${node.name} += ${inc}) {\n${body}\n${indent}}`;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
1835
2049
|
case 'WhileStatement': {
|
|
1836
2050
|
const condition = generateCondition(node.condition, context);
|
|
1837
|
-
|
|
2051
|
+
context.loopDepth++;
|
|
2052
|
+
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2053
|
+
context.loopDepth--;
|
|
1838
2054
|
return `${indent}while (${condition}) {\n${body}\n${indent}}`;
|
|
1839
2055
|
}
|
|
1840
2056
|
|
|
2057
|
+
case 'BreakStatement': {
|
|
2058
|
+
if (context.loopDepth <= 0) {
|
|
2059
|
+
throw new Error('"break" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if done(item)\n break\n done\n done');
|
|
2060
|
+
}
|
|
2061
|
+
return `${indent}break;`;
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
case 'ContinueStatement': {
|
|
2065
|
+
if (context.loopDepth <= 0) {
|
|
2066
|
+
throw new Error('"continue" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if skip(item)\n continue\n done\n done');
|
|
2067
|
+
}
|
|
2068
|
+
return `${indent}continue;`;
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
case 'ThrowStatement':
|
|
2072
|
+
return `${indent}throw ${generateExpr(node.value, context)};`;
|
|
2073
|
+
|
|
1841
2074
|
// v0.3 — Express runtime
|
|
1842
2075
|
|
|
1843
2076
|
case 'ListenStatement': {
|
|
@@ -1929,6 +2162,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1929
2162
|
}
|
|
1930
2163
|
return `${indent}res.status(${generateExpr(node.value, context)});`;
|
|
1931
2164
|
|
|
2165
|
+
// v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route.
|
|
2166
|
+
case 'RedirectStatement':
|
|
2167
|
+
if (!_inRoute) {
|
|
2168
|
+
throw new Error('"redirect to" can only be used inside a route handler.\n\nExample:\n route get "/old"\n redirect to "/new"\n done');
|
|
2169
|
+
}
|
|
2170
|
+
return `${indent}res.redirect(${generateExpr(node.url, context)});`;
|
|
2171
|
+
|
|
1932
2172
|
// v2.1.0 — allow cors: enables cross-origin requests on the current app.
|
|
1933
2173
|
// Applies to routes registered after this statement.
|
|
1934
2174
|
case 'AllowCorsStatement':
|
|
@@ -2351,7 +2591,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2351
2591
|
|
|
2352
2592
|
case 'RunBackgroundStatement':
|
|
2353
2593
|
return [
|
|
2354
|
-
`${indent}setImmediate(() => {`,
|
|
2594
|
+
`${indent}setImmediate(async () => {`,
|
|
2355
2595
|
`${indent} try {`,
|
|
2356
2596
|
`${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
|
|
2357
2597
|
`${indent} } catch (error) { console.error(error); }`,
|
|
@@ -2558,6 +2798,12 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2558
2798
|
return `${generateExpr(node.object, context)}.${node.property}`;
|
|
2559
2799
|
|
|
2560
2800
|
case 'CallExpression': {
|
|
2801
|
+
// Method call: receiver.method(args). Member access invoked with parens —
|
|
2802
|
+
// e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
|
|
2803
|
+
if (node.callee) {
|
|
2804
|
+
const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
|
|
2805
|
+
return `${generateExpr(node.callee, context)}(${args})`;
|
|
2806
|
+
}
|
|
2561
2807
|
if (STDLIB[node.name]) {
|
|
2562
2808
|
if (node.name === 'readFile' || node.name === 'writeFile' ||
|
|
2563
2809
|
node.name === 'fileExists' || node.name === 'read') {
|
|
@@ -2614,7 +2860,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2614
2860
|
ensureBuiltin(context, 'fs');
|
|
2615
2861
|
return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
|
|
2616
2862
|
|
|
2617
|
-
// v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`
|
|
2863
|
+
// v1.0.0-latest — record constructor: `create a Person with name "Ada" and age 17`
|
|
2618
2864
|
// calls the kind factory that `define a kind called "Person"` registered.
|
|
2619
2865
|
case 'CreateKindExpression': {
|
|
2620
2866
|
const fields = node.pairs
|
|
@@ -2623,7 +2869,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2623
2869
|
return `${node.kind}({ ${fields} })`;
|
|
2624
2870
|
}
|
|
2625
2871
|
|
|
2626
|
-
// v1.0.0 — concurrency combinators: `all of [...]` / `any of [...]` /
|
|
2872
|
+
// v1.0.0-latest — concurrency combinators: `all of [...]` / `any of [...]` /
|
|
2627
2873
|
// `settled of [...]`. All are awaited; `settled` returns status records.
|
|
2628
2874
|
case 'ConcurrencyExpression': {
|
|
2629
2875
|
markAsync(context);
|
|
@@ -2633,7 +2879,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2633
2879
|
return `(await Promise.all(${rhs}))`;
|
|
2634
2880
|
}
|
|
2635
2881
|
|
|
2636
|
-
// v1.0.0 — `spread of <collection>` → a fresh array from an iterable.
|
|
2882
|
+
// v1.0.0-latest — `spread of <collection>` → a fresh array from an iterable.
|
|
2637
2883
|
case 'SpreadExpression':
|
|
2638
2884
|
return `[...${generateExpr(node.collection, context)}]`;
|
|
2639
2885
|
|
package/compiler/lexer.js
CHANGED
|
@@ -76,7 +76,7 @@ const TOKEN = {
|
|
|
76
76
|
EMIT: 'EMIT', // emit "event.name" with data (event emitter)
|
|
77
77
|
HAPPENS: 'HAPPENS', // when "event.name" happens as data (event listener)
|
|
78
78
|
CATCHES: 'CATCHES', // recover when err catches "TypeError" (typed error recovery)
|
|
79
|
-
// v1.0.0 — generators. "yield" is a JavaScript reserved word, so it becomes a
|
|
79
|
+
// v1.0.0-latest — generators. "yield" is a JavaScript reserved word, so it becomes a
|
|
80
80
|
// real keyword token (a variable named `yield` is illegal in JS anyway).
|
|
81
81
|
YIELD: 'YIELD',
|
|
82
82
|
// Punctuation
|