plainscript-lang 1.0.0-beta → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -6
- package/compiler/cli.js +2 -0
- package/compiler/generator.js +203 -6
- package/compiler/parser.js +9 -0
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +60 -0
- package/docs/PLINJS_SPEC.md +3 -3
- package/docs/index.html +3 -3
- 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 +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
PlainScript is an Intent-Oriented Programming Language (IOPL). You describe **what** you want; the compiler decides **how** to implement it in JavaScript.
|
|
11
11
|
|
|
12
|
-
**Current version:** v1.0.0
|
|
12
|
+
**Current version:** v1.0.0 — the `plainscript` npm package with a TypeScript-style production build (`plainscript build` → `dist/`, source names preserved).
|
|
13
13
|
|
|
14
14
|
---
|
|
15
15
|
|
|
@@ -108,7 +108,7 @@ For projects that need custom output or source directories, add a
|
|
|
108
108
|
"build": "plainscript build",
|
|
109
109
|
"prepare": "plainscript build"
|
|
110
110
|
},
|
|
111
|
-
"devDependencies": { "plainscript": "^1.0.0
|
|
111
|
+
"devDependencies": { "plainscript": "^1.0.0" }
|
|
112
112
|
}
|
|
113
113
|
```
|
|
114
114
|
|
|
@@ -297,7 +297,7 @@ use node-fetch
|
|
|
297
297
|
use @scope/package-name
|
|
298
298
|
```
|
|
299
299
|
|
|
300
|
-
### TypeScript-parity capabilities (1.0.0
|
|
300
|
+
### TypeScript-parity capabilities (1.0.0)
|
|
301
301
|
|
|
302
302
|
The full capability-gap audit lives in [`docs/CAPABILITY_GAP_AUDIT.md`](docs/CAPABILITY_GAP_AUDIT.md).
|
|
303
303
|
These features close it in PlainScript's own grammar:
|
|
@@ -583,7 +583,9 @@ start env("PORT")
|
|
|
583
583
|
```
|
|
584
584
|
|
|
585
585
|
`param("id")`, `query("page")` and `header("x-token")` read request data;
|
|
586
|
-
`
|
|
586
|
+
`body()` / `body("field")` read the JSON request body; `group` composes path
|
|
587
|
+
prefixes; `status <n>` sets the response code and `redirect to "<url>"` issues a
|
|
588
|
+
redirect.
|
|
587
589
|
|
|
588
590
|
### Databases with parameters and transactions
|
|
589
591
|
|
|
@@ -645,15 +647,46 @@ websocket server on 8080
|
|
|
645
647
|
done
|
|
646
648
|
```
|
|
647
649
|
|
|
648
|
-
### Cache (Redis)
|
|
650
|
+
### Cache (Redis with in-memory fallback)
|
|
649
651
|
|
|
650
652
|
```plainscript
|
|
651
|
-
cache env("REDIS_URL")
|
|
653
|
+
cache env("REDIS_URL") // omit for an in-memory Map store with TTL
|
|
652
654
|
remember token as cacheGet("token")
|
|
653
655
|
cacheSet("greeting", "hi", 60)
|
|
654
656
|
cacheDelete("greeting")
|
|
655
657
|
```
|
|
656
658
|
|
|
659
|
+
Without a configured Redis, `cacheGet`/`cacheSet`/`cacheDelete` transparently fall
|
|
660
|
+
back to an in-memory store, so naive caching works out of the box.
|
|
661
|
+
|
|
662
|
+
### AI / ML
|
|
663
|
+
|
|
664
|
+
```plainscript
|
|
665
|
+
remember reply as chat("gpt-4o-mini", [
|
|
666
|
+
{ role: "user", content: "Say hello in two words" }
|
|
667
|
+
])
|
|
668
|
+
|
|
669
|
+
remember vec as embedText("text-embedding-3-small", "PlainScript rocks")
|
|
670
|
+
remember score as similarity(vec, embedText("text-embedding-3-small", "I love PlainScript"))
|
|
671
|
+
|
|
672
|
+
remember tags as ai_tags("PlainScript is an intent-oriented language")
|
|
673
|
+
remember article as ai_post("Welcome to PlainScript", ["why IOPL", "quick start"])
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
`chat` and `embedText` are async OpenAI-compatible calls (from `OPENAI_API_KEY`,
|
|
677
|
+
override with `options.apiKey`/`options.baseURL`); `similarity` returns -1..1.
|
|
678
|
+
|
|
679
|
+
### Pagination
|
|
680
|
+
|
|
681
|
+
```plainscript
|
|
682
|
+
remember page as paginate(allUsers, 2, 10)
|
|
683
|
+
show page.items # second page of 10
|
|
684
|
+
show page.hasNext # true if another page exists
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
`paginate(list, page, perPage)` returns
|
|
688
|
+
`{ items, count, page, pages, perPage, hasNext, hasPrev }`.
|
|
689
|
+
|
|
657
690
|
---
|
|
658
691
|
|
|
659
692
|
## Multi-file projects
|
package/compiler/cli.js
CHANGED
|
@@ -89,6 +89,8 @@ ${section('ALSO SHIPPED')}
|
|
|
89
89
|
WhatsApp bots (v2.1.1) ·
|
|
90
90
|
email · schedules · WebSocket · cache (v2.1) ·
|
|
91
91
|
sessions · uploads · cookies · rate limits · api keys · OAuth (v2.1.1)
|
|
92
|
+
JSON body · redirect · AI chat/embeddings · vector similarity ·
|
|
93
|
+
paginate · collection & string primitives (v2.2)
|
|
92
94
|
|
|
93
95
|
${section('FIRST RUN')}
|
|
94
96
|
plainscript new hello scaffolds hello/ with a live web app
|
package/compiler/generator.js
CHANGED
|
@@ -234,6 +234,49 @@ const BUILTIN_DECLARATIONS = {
|
|
|
234
234
|
mapset: [
|
|
235
235
|
`function __mapSet(map, key, value) { map.set(key, value); return map; }`,
|
|
236
236
|
].join('\n'),
|
|
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'),
|
|
237
280
|
// v1.0.0 — dynamic module loader.
|
|
238
281
|
loadmodule: [
|
|
239
282
|
`function __loadModule(spec) {`,
|
|
@@ -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,6 +1216,51 @@ 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
|
|
|
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
|
+
|
|
1100
1264
|
// ── v1.0.0 — nullable / regex / date helpers (IOPL-native).
|
|
1101
1265
|
// first non-null, non-undefined argument — IOPL null-coalescing.
|
|
1102
1266
|
coalesce: (args, context) =>
|
|
@@ -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).
|
|
@@ -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(', ')})`; },
|
|
@@ -1470,6 +1658,8 @@ function ensureBuiltin(context, moduleName) {
|
|
|
1470
1658
|
const ASYNC_CALL_NAMES = new Set([
|
|
1471
1659
|
// v2.1.0 — cache and email
|
|
1472
1660
|
'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
|
|
1661
|
+
// v2.2.0 — AI/ML calls await their model endpoint
|
|
1662
|
+
'chat', 'embedText',
|
|
1473
1663
|
// v1.2 — Telegram helpers (await their API transport)
|
|
1474
1664
|
'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
|
|
1475
1665
|
]);
|
|
@@ -1929,6 +2119,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1929
2119
|
}
|
|
1930
2120
|
return `${indent}res.status(${generateExpr(node.value, context)});`;
|
|
1931
2121
|
|
|
2122
|
+
// v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route.
|
|
2123
|
+
case 'RedirectStatement':
|
|
2124
|
+
if (!_inRoute) {
|
|
2125
|
+
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');
|
|
2126
|
+
}
|
|
2127
|
+
return `${indent}res.redirect(${generateExpr(node.url, context)});`;
|
|
2128
|
+
|
|
1932
2129
|
// v2.1.0 — allow cors: enables cross-origin requests on the current app.
|
|
1933
2130
|
// Applies to routes registered after this statement.
|
|
1934
2131
|
case 'AllowCorsStatement':
|
package/compiler/parser.js
CHANGED
|
@@ -492,6 +492,15 @@ function parse(tokens) {
|
|
|
492
492
|
return { type: 'StatusStatement', value };
|
|
493
493
|
}
|
|
494
494
|
|
|
495
|
+
// v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route
|
|
496
|
+
// handler. "redirect(...)" calls and "redirect becomes x" stay ordinary.
|
|
497
|
+
if (token.value === 'redirect' && peekAt(1).value === 'to') {
|
|
498
|
+
advance(); // redirect
|
|
499
|
+
advance(); // to
|
|
500
|
+
const url = parseExpression();
|
|
501
|
+
return { type: 'RedirectStatement', url };
|
|
502
|
+
}
|
|
503
|
+
|
|
495
504
|
// ── v2.1.1 statements (all contextual, following the v2.1.0 pattern) ──
|
|
496
505
|
|
|
497
506
|
// try … [recover [as <name>]] … done: deterministic error handling.
|
package/compiler/version.js
CHANGED
|
@@ -377,3 +377,63 @@ The audit is **complete** only when:
|
|
|
377
377
|
capability.
|
|
378
378
|
|
|
379
379
|
Until then the package version remains **below 1.0.0**.
|
|
380
|
+
|
|
381
|
+
---
|
|
382
|
+
|
|
383
|
+
## 22. v2.2.0 — AI/ML, data/storage & web additions
|
|
384
|
+
|
|
385
|
+
The v2.0–v2.2 releases close further gaps beyond the 1.0.0 audit across the
|
|
386
|
+
AI/ML, data/storage and web/full-stack surface. All features below are
|
|
387
|
+
IOPL-native (intent-oriented) rather than TypeScript-syntax clones.
|
|
388
|
+
|
|
389
|
+
### AI / ML (module `ai`)
|
|
390
|
+
|
|
391
|
+
| Capability | IOPL stdlib |
|
|
392
|
+
| -------------------------------------------- | --------------------------------------------------------------------------- |
|
|
393
|
+
| LLM chat completion | `chat(model, messages, {options})` → text, async, OpenAI-compatible API |
|
|
394
|
+
| Text embeddings | `embedText(model, text, {options})` → vector, async |
|
|
395
|
+
| Vector similarity (cosine) | `similarity(a, b)` → -1..1 (identical → 1, orthogonal → 0, opposite → -1) |
|
|
396
|
+
| Auto-tagging convenience | `ai_tags(text)` → topic/category tags |
|
|
397
|
+
| Post / content generation | `ai_post(subject, ideas, options)` → generated prose |
|
|
398
|
+
| Auth | `OPENAI_API_KEY` env (override via `options.apiKey`/`options.baseURL`) |
|
|
399
|
+
|
|
400
|
+
**Audit status:** chat, embeddings, similarity ship with runtime tests; tag/post
|
|
401
|
+
compose the same runtime. **Gap closed.**
|
|
402
|
+
|
|
403
|
+
### Data / storage
|
|
404
|
+
|
|
405
|
+
| Capability | IOPL stdlib |
|
|
406
|
+
| -------------------- | --------------------------------------------------------------------------- |
|
|
407
|
+
| SQLite persistence | `http`+`db` runtime, `sql` queries, `table`/`row`/`query` DSL (existing) |
|
|
408
|
+
| In-memory cache fallback | `cacheGet/cacheSet/cacheDelete` use a Map-based store with TTL when no Redis is configured |
|
|
409
|
+
| Server-managed cache | Redis-backed cache when configured (existing) |
|
|
410
|
+
| Redis cache | existing TTL semantics, now with graceful no-config fallback |
|
|
411
|
+
| Pagination | `paginate(list, page, perPage)` → `{items, count, page, pages, perPage, hasNext, hasPrev}` |
|
|
412
|
+
|
|
413
|
+
**Audit status:** paginate + in-memory cache fallback ship and are tested.
|
|
414
|
+
**Gap closed.**
|
|
415
|
+
|
|
416
|
+
### Web / full-stack
|
|
417
|
+
|
|
418
|
+
| Capability | IOPL stdlib |
|
|
419
|
+
| ------------- | ------------------------------------------------------------------ |
|
|
420
|
+
| Request body | route-scoped `body(...)` accessor: `body()` → raw, `body("field")` → field |
|
|
421
|
+
| Redirect | `redirect to "<url>"` statement inside a route handler (`res.redirect`) |
|
|
422
|
+
| (existing) | routes, status, sessions, uploads, cookies, WebSocket, OAuth, email, schedules |
|
|
423
|
+
|
|
424
|
+
**Audit status:** `body` + `redirect to` ship, route-guarded with teaching
|
|
425
|
+
errors, compile-verified. **Gap closed.**
|
|
426
|
+
|
|
427
|
+
### Core collections & string primitives (module `coll`)
|
|
428
|
+
|
|
429
|
+
`range`, `clamp`, `first`, `last`, `flatten`, `includes`, `pick`, `omit`,
|
|
430
|
+
`groupBy`, `startsWith`, `endsWith`, `truncate`, `padStart`, `padEnd` — all
|
|
431
|
+
runtime-tested. `contains` is a reserved lexer keyword, so the membership helper
|
|
432
|
+
is named `includes`.
|
|
433
|
+
|
|
434
|
+
**Audit status:** shipped + tested. **Gap closed.**
|
|
435
|
+
|
|
436
|
+
> **Note on v2.2.0 testing:** `npm test` may not fully run in constrained
|
|
437
|
+
> sandboxes where native deps (`express`, `sql.js`, `ws`) cannot be installed;
|
|
438
|
+
> web/HTTP features are therefore **compile-verified** there. Core language,
|
|
439
|
+
> collections, AI (with a live key), and cache fallback run with real tests.
|
package/docs/PLINJS_SPEC.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# PlainScript Language Specification (v1.0.0
|
|
1
|
+
# PlainScript Language Specification (v1.0.0)
|
|
2
2
|
|
|
3
3
|
Version: 2.1.1
|
|
4
4
|
Status: Stable
|
|
@@ -155,7 +155,7 @@ While:
|
|
|
155
155
|
|
|
156
156
|
---
|
|
157
157
|
|
|
158
|
-
## Record Kinds, Classes & Concurrency (v1.0.0
|
|
158
|
+
## Record Kinds, Classes & Concurrency (v1.0.0)
|
|
159
159
|
|
|
160
160
|
These features close the capability-gap audit (`docs/CAPABILITY_GAP_AUDIT.md`) in
|
|
161
161
|
PlainScript's own intent-oriented grammar.
|
|
@@ -1147,5 +1147,5 @@ If a package is missing, the compiler prints a friendly error and stops:
|
|
|
1147
1147
|
|
|
1148
1148
|
---
|
|
1149
1149
|
|
|
1150
|
-
This document is the single source of truth for PlainScript v1.0.0
|
|
1150
|
+
This document is the single source of truth for PlainScript v1.0.0.
|
|
1151
1151
|
Every compiler implementation must follow this specification.
|
package/docs/index.html
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
<a href="#" class="nav-logo">
|
|
36
36
|
<img src="logo.jpg" alt="PlainScript Logo">
|
|
37
37
|
<span class="logo-word">PlainScript</span>
|
|
38
|
-
<span class="logo-ver">v1.0.0
|
|
38
|
+
<span class="logo-ver">v1.0.0</span>
|
|
39
39
|
</a>
|
|
40
40
|
<div class="nav-links">
|
|
41
41
|
<a href="#language">Language</a>
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
<!-- Hero Section -->
|
|
86
86
|
<section class="hero">
|
|
87
87
|
<div class="hero-content">
|
|
88
|
-
<div class="hero-badge">v1.0.0
|
|
88
|
+
<div class="hero-badge">v1.0.0 — intent-oriented, TypeScript-capable</div>
|
|
89
89
|
<h1 class="hero-title">
|
|
90
90
|
Write code that<br>
|
|
91
91
|
reads like <span class="green">Plain English</span>
|
|
@@ -602,7 +602,7 @@ use dotenv</code></pre>
|
|
|
602
602
|
</div>
|
|
603
603
|
<div class="footer-bottom">
|
|
604
604
|
<p>© 2026 PlainScript. Built by Ayokunle.</p>
|
|
605
|
-
<span class="footer-badge">v1.0.0
|
|
605
|
+
<span class="footer-badge">v1.0.0</span>
|
|
606
606
|
</div>
|
|
607
607
|
</div>
|
|
608
608
|
</footer>
|
package/docs/website/script.js
CHANGED
|
@@ -766,7 +766,7 @@ var LIBRARY = [
|
|
|
766
766
|
{cat:"server",name:"404 Catch-All",desc:"Handle unmatched routes",ps:'when nothing matches\n status 404\n reply "Page not found"\ndone',js:'app.use((req, res) => {\n res.status(404);\n res.send("Page not found");\n});',skipRun:true},
|
|
767
767
|
{cat:"server",name:"Validate Request Body",desc:"Require specific fields in the request body",ps:'route post "/users"\n validate(body of request, ["name", "email"])\n reply "Created"\ndone',js:'app.post("/users", (req, res) => {\n __validate(req.body, ["name", "email"]);\n res.send("Created");\n});',skipRun:true},
|
|
768
768
|
{cat:"auth",name:"Google OAuth",desc:"Add Google login to your app",ps:'web app\ngoogle oauth\n id is env("GOOGLE_CLIENT_ID")\n secret is env("GOOGLE_CLIENT_SECRET")\n callback is "/auth/google/callback"\n landing is "/dashboard"\ndone',js:'__googleOAuth(app, {\n clientId: process.env["GOOGLE_CLIENT_ID"],\n clientSecret: process.env["GOOGLE_CLIENT_SECRET"],\n callbackUrl: "/auth/google/callback",\n afterLogin: "/dashboard"\n});'},
|
|
769
|
-
{cat:"cli",name:"CLI: version",desc:"Print the PlainScript version",ps:'plainscript version',js:'// Prints v1.0.0
|
|
769
|
+
{cat:"cli",name:"CLI: version",desc:"Print the PlainScript version",ps:'plainscript version',js:'// Prints v1.0.0',skipRun:true},
|
|
770
770
|
{cat:"cli",name:"CLI: help",desc:"Show available commands",ps:'plainscript help',js:'// Lists all CLI commands',skipRun:true},
|
|
771
771
|
{cat:"cli",name:"CLI: info",desc:"Display platform and runtime info",ps:'plainscript info',js:'// Shows version, Node version, OS',skipRun:true},
|
|
772
772
|
{cat:"cli",name:"CLI: clean",desc:"Remove compiled output",ps:'plainscript clean',js:'// Deletes dist/ folder',skipRun:true},
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — API key protection, rate limits and tokens
|
|
2
|
+
//
|
|
3
|
+
// Run with: API_KEY=my-secret plainscript run examples/auth-api.ps
|
|
4
|
+
// Then try:
|
|
5
|
+
// curl -H "x-api-key: my-secret" http://localhost:3000/status
|
|
6
|
+
// curl http://localhost:3000/status # 401 without the key
|
|
7
|
+
//
|
|
8
|
+
// Routes registered after "require api key" are guarded; the health route is
|
|
9
|
+
// registered first so uptime checks keep working.
|
|
10
|
+
|
|
11
|
+
web app
|
|
12
|
+
|
|
13
|
+
route get "/health"
|
|
14
|
+
reply "alive"
|
|
15
|
+
done
|
|
16
|
+
|
|
17
|
+
require api key from env("API_KEY")
|
|
18
|
+
limit requests to 60 per minute
|
|
19
|
+
|
|
20
|
+
remember secret as env("TOKEN_SECRET")
|
|
21
|
+
|
|
22
|
+
route get "/status"
|
|
23
|
+
reply json
|
|
24
|
+
status is "ok"
|
|
25
|
+
version is "1.0.0"
|
|
26
|
+
done
|
|
27
|
+
done
|
|
28
|
+
|
|
29
|
+
route post "/token"
|
|
30
|
+
remember payload as
|
|
31
|
+
sub is "user-1"
|
|
32
|
+
role is "admin"
|
|
33
|
+
done
|
|
34
|
+
remember issued as createToken(payload, secret, 1800)
|
|
35
|
+
reply json
|
|
36
|
+
token is issued
|
|
37
|
+
done
|
|
38
|
+
done
|
|
39
|
+
|
|
40
|
+
route get "/verify"
|
|
41
|
+
remember supplied as header("x-token")
|
|
42
|
+
remember claims as readToken(supplied, secret)
|
|
43
|
+
if claims is empty
|
|
44
|
+
status 401
|
|
45
|
+
reply json
|
|
46
|
+
error is "invalid or expired token"
|
|
47
|
+
done
|
|
48
|
+
otherwise
|
|
49
|
+
reply json
|
|
50
|
+
sub is sub of claims
|
|
51
|
+
role is role of claims
|
|
52
|
+
done
|
|
53
|
+
done
|
|
54
|
+
done
|
|
55
|
+
|
|
56
|
+
start 3000
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Concurrency: combinators, timeouts and workers
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/concurrency.ps
|
|
4
|
+
//
|
|
5
|
+
// all / any / settled run several promises in parallel; withTimeout bounds
|
|
6
|
+
// how long one may take; run background fires work without blocking.
|
|
7
|
+
|
|
8
|
+
make fetchUsers()
|
|
9
|
+
sleep(300)
|
|
10
|
+
give { source: "users", count: 42 }
|
|
11
|
+
done
|
|
12
|
+
|
|
13
|
+
make fetchOrders()
|
|
14
|
+
sleep(150)
|
|
15
|
+
give { source: "orders", count: 17 }
|
|
16
|
+
done
|
|
17
|
+
|
|
18
|
+
make flakyFetch()
|
|
19
|
+
remember data as jsonDecode("not json")
|
|
20
|
+
give data
|
|
21
|
+
done
|
|
22
|
+
|
|
23
|
+
// Every item must resolve — an array of results
|
|
24
|
+
remember dashboard as all of [fetchUsers(), fetchOrders()]
|
|
25
|
+
for each panel in dashboard
|
|
26
|
+
show source of panel + ": " + text(count of panel)
|
|
27
|
+
done
|
|
28
|
+
|
|
29
|
+
// First to settle wins
|
|
30
|
+
remember first as any of [fetchUsers(), fetchOrders()]
|
|
31
|
+
show "first: " + source of first
|
|
32
|
+
|
|
33
|
+
// Never throws; each outcome is a record with a status
|
|
34
|
+
remember results as settled of [fetchUsers(), flakyFetch()]
|
|
35
|
+
for each outcome in results
|
|
36
|
+
if status of outcome is "fulfilled"
|
|
37
|
+
show "ok: " + text(value of outcome)
|
|
38
|
+
otherwise
|
|
39
|
+
show "failed: " + message of reason of outcome
|
|
40
|
+
done
|
|
41
|
+
done
|
|
42
|
+
|
|
43
|
+
// Bound a slow call
|
|
44
|
+
remember bounded as withTimeout(fetchUsers(), 2000)
|
|
45
|
+
show "bounded result ready"
|
|
46
|
+
|
|
47
|
+
// Fire-and-forget background work
|
|
48
|
+
run background fetchUsers()
|
|
49
|
+
show "background job launched — this line prints immediately"
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Robust error handling
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/error-handling.ps
|
|
4
|
+
//
|
|
5
|
+
// Shows deterministic recovery: typed "recover" blocks, silent swallowing,
|
|
6
|
+
// and automatic retries with backoff for flaky operations.
|
|
7
|
+
|
|
8
|
+
make parseSettings(raw)
|
|
9
|
+
remember settings as jsonDecode(raw)
|
|
10
|
+
if settings is empty
|
|
11
|
+
give { theme: "light" }
|
|
12
|
+
otherwise
|
|
13
|
+
give settings
|
|
14
|
+
done
|
|
15
|
+
done
|
|
16
|
+
|
|
17
|
+
// Recover with the thrown value
|
|
18
|
+
try
|
|
19
|
+
remember settings as parseSettings("{ bad json")
|
|
20
|
+
show theme of settings
|
|
21
|
+
recover as err
|
|
22
|
+
show "falling back: " + message of err
|
|
23
|
+
remember settings as { theme: "dark" }
|
|
24
|
+
show theme of settings
|
|
25
|
+
done
|
|
26
|
+
|
|
27
|
+
// Multiple typed recover clauses win on error name
|
|
28
|
+
try
|
|
29
|
+
remember parsed as jsonDecode("also not json")
|
|
30
|
+
recover when err catches "SyntaxError"
|
|
31
|
+
show "JSON parse error caught: " + message of err
|
|
32
|
+
recover as err
|
|
33
|
+
show "some other error: " + message of err
|
|
34
|
+
done
|
|
35
|
+
|
|
36
|
+
// Swallow failures silently when no recover is present
|
|
37
|
+
try
|
|
38
|
+
remember probe as read("does-not-exist.txt")
|
|
39
|
+
done
|
|
40
|
+
show "survived the failed read"
|
|
41
|
+
|
|
42
|
+
// Automatic retry with a delay
|
|
43
|
+
remember logs as []
|
|
44
|
+
make fetchStatus()
|
|
45
|
+
add("trying…" to logs)
|
|
46
|
+
give read("status.db.json")
|
|
47
|
+
done
|
|
48
|
+
|
|
49
|
+
retry 3 times every 1 second
|
|
50
|
+
remember body as fetchStatus()
|
|
51
|
+
show body
|
|
52
|
+
done
|
|
53
|
+
|
|
54
|
+
show length(logs)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — File uploads
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/file-uploads.ps
|
|
4
|
+
// Then try:
|
|
5
|
+
// curl -F photo=@some-image.png http://localhost:3000/upload
|
|
6
|
+
// curl -F doc=@notes.txt http://localhost:3000/upload-many
|
|
7
|
+
//
|
|
8
|
+
// Uploaded files are kept in memory (no folder) so nothing touches the disk.
|
|
9
|
+
// A file over 5 MB is rejected with HTTP 413 and a non-image with HTTP 415.
|
|
10
|
+
|
|
11
|
+
web app
|
|
12
|
+
|
|
13
|
+
accept uploads limit "5 MB" allow ["image/png", "image/jpeg", "text/plain"]
|
|
14
|
+
|
|
15
|
+
route post "/upload"
|
|
16
|
+
remember file as upload("file")
|
|
17
|
+
if file is not empty
|
|
18
|
+
reply json
|
|
19
|
+
name is name of file
|
|
20
|
+
type is type of file
|
|
21
|
+
size is size of file
|
|
22
|
+
done
|
|
23
|
+
otherwise
|
|
24
|
+
reply json
|
|
25
|
+
error is "no file under the 'file' field"
|
|
26
|
+
done
|
|
27
|
+
done
|
|
28
|
+
done
|
|
29
|
+
|
|
30
|
+
route post "/upload-many"
|
|
31
|
+
remember files as uploads("docs")
|
|
32
|
+
gather each file in files giving name of file
|
|
33
|
+
reply json
|
|
34
|
+
received is length(files)
|
|
35
|
+
names is files
|
|
36
|
+
done
|
|
37
|
+
done
|
|
38
|
+
|
|
39
|
+
start 3000
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — File I/O, YAML and environment configuration
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/files-and-config.ps
|
|
4
|
+
//
|
|
5
|
+
// Writes and reads files, walks a folder, round-trips YAML and applies a
|
|
6
|
+
// .env file. Everything is deterministic and dependency-free.
|
|
7
|
+
|
|
8
|
+
makeFolder("example-output")
|
|
9
|
+
writeFile("example-output/greeting.txt", "Hello, files!")
|
|
10
|
+
writeLine("example-output/log.txt", "first line")
|
|
11
|
+
appendLine("example-output/log.txt", "second line")
|
|
12
|
+
|
|
13
|
+
show readFile("example-output/greeting.txt")
|
|
14
|
+
show readFile("example-output/log.txt")
|
|
15
|
+
show fileExists("example-output/greeting.txt")
|
|
16
|
+
show fileSize("example-output/greeting.txt")
|
|
17
|
+
show fileType("example-output") // directory
|
|
18
|
+
show lastModified("example-output/greeting.txt")
|
|
19
|
+
|
|
20
|
+
show listFolder("example-output")
|
|
21
|
+
show walkFolder("example-output")
|
|
22
|
+
|
|
23
|
+
remember settings as
|
|
24
|
+
app is "plainscript"
|
|
25
|
+
limits is { requests: 100, window: "hour" }
|
|
26
|
+
done
|
|
27
|
+
|
|
28
|
+
remember encoded as yamlEncode(settings)
|
|
29
|
+
show encoded
|
|
30
|
+
|
|
31
|
+
remember parsed as yamlDecode(encoded)
|
|
32
|
+
show app of parsed
|
|
33
|
+
remember limits as limits of parsed
|
|
34
|
+
show requests of limits
|
|
35
|
+
|
|
36
|
+
load env file ".env"
|
|
37
|
+
show env("APP_ENV")
|
|
38
|
+
|
|
39
|
+
// JSON round-trip stays convenient too
|
|
40
|
+
remember backup as jsonEncode(settings)
|
|
41
|
+
show jsonDecode(backup)
|
|
42
|
+
|
|
43
|
+
// Clean up after ourselves
|
|
44
|
+
deleteFile("example-output/greeting.txt")
|
|
45
|
+
deleteFile("example-output/log.txt")
|
|
46
|
+
deleteFolder("example-output")
|
|
47
|
+
show "cleanup done"
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — HTTP client: every method, headers and timeouts
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/http-client.ps
|
|
4
|
+
//
|
|
5
|
+
// Uses the public JSONPlaceholder API. Every call returns a record with
|
|
6
|
+
// ok / status / headers / data; JSON bodies are parsed automatically.
|
|
7
|
+
|
|
8
|
+
// GET with an explicit timeout
|
|
9
|
+
remember users as get "https://jsonplaceholder.typicode.com/users" timeout 8000
|
|
10
|
+
show "GET users -> " + text(status of users) + ", count " + text(length(data of users))
|
|
11
|
+
|
|
12
|
+
// POST an inline object, sent as JSON
|
|
13
|
+
remember created as post "https://jsonplaceholder.typicode.com/posts" with {
|
|
14
|
+
title: "Hello from PlainScript",
|
|
15
|
+
userId: 1
|
|
16
|
+
}
|
|
17
|
+
show "POST -> status " + text(status of created)
|
|
18
|
+
if ok of created is true
|
|
19
|
+
show "new post id " + text(id of data of created)
|
|
20
|
+
done
|
|
21
|
+
|
|
22
|
+
// PUT replaces the whole resource
|
|
23
|
+
remember replaced as put "https://jsonplaceholder.typicode.com/posts/1" with {
|
|
24
|
+
title: "Updated",
|
|
25
|
+
body: "new body",
|
|
26
|
+
userId: 1
|
|
27
|
+
}
|
|
28
|
+
show "PUT -> status " + text(status of replaced)
|
|
29
|
+
|
|
30
|
+
// PATCH merges into the resource
|
|
31
|
+
remember patched as patch "https://jsonplaceholder.typicode.com/posts/1" with {
|
|
32
|
+
title: "Patched title"
|
|
33
|
+
}
|
|
34
|
+
show "PATCH -> status " + text(status of patched)
|
|
35
|
+
|
|
36
|
+
// DELETE
|
|
37
|
+
remember removed as delete "https://jsonplaceholder.typicode.com/posts/1"
|
|
38
|
+
show "DELETE -> ok " + text(ok of removed)
|
|
39
|
+
|
|
40
|
+
// Custom headers and error surfacing
|
|
41
|
+
remember guarded as get "https://api.example.com/private" headers {
|
|
42
|
+
Authorization: "Bearer test"
|
|
43
|
+
} timeout 3000
|
|
44
|
+
show "guard called? " + text(ok of guarded) + " (status " + text(status of guarded) + ")"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Importing your own modules
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/modules/app.ps
|
|
4
|
+
//
|
|
5
|
+
// Files are compiled in dependency order (deepest first), so the helpers in
|
|
6
|
+
// math.ps are visible here before app.ps runs.
|
|
7
|
+
|
|
8
|
+
import "./math.ps"
|
|
9
|
+
|
|
10
|
+
show PI // 3.14
|
|
11
|
+
show double(21) // 42
|
|
12
|
+
show square(9) // 81
|
|
13
|
+
show circumference(10) // 62.8
|
|
14
|
+
|
|
15
|
+
remember radius as 2.5
|
|
16
|
+
show "circle area: " + text(square(radius) * PI)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — reusable module, imported by app.ps
|
|
2
|
+
|
|
3
|
+
remember PI as 3.14
|
|
4
|
+
|
|
5
|
+
make double(n)
|
|
6
|
+
give n * 2
|
|
7
|
+
done
|
|
8
|
+
|
|
9
|
+
make square(n)
|
|
10
|
+
give n * n
|
|
11
|
+
done
|
|
12
|
+
|
|
13
|
+
make circumference(radius)
|
|
14
|
+
give 2 * PI * radius
|
|
15
|
+
done
|
|
16
|
+
|
|
17
|
+
export PI
|
|
18
|
+
export double
|
|
19
|
+
export square
|
|
20
|
+
export circumference
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Record kinds, generators and the test DSL
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/record-kinds.ps
|
|
4
|
+
//
|
|
5
|
+
// Defines a schema, builds instances, composes records, streams values from
|
|
6
|
+
// generators, and verifies behaviour with the built-in test runner.
|
|
7
|
+
|
|
8
|
+
define a kind called "Book" with
|
|
9
|
+
title is ""
|
|
10
|
+
pages is 0
|
|
11
|
+
rating is 0
|
|
12
|
+
done
|
|
13
|
+
|
|
14
|
+
remember fav as create a Book with title "IOPL in Action" and pages 240
|
|
15
|
+
fav.rating becomes 4.5
|
|
16
|
+
|
|
17
|
+
show title of fav
|
|
18
|
+
show pages of fav
|
|
19
|
+
show rating of fav
|
|
20
|
+
|
|
21
|
+
remember extended as merge(fav, { author: "Ada" })
|
|
22
|
+
show author of extended
|
|
23
|
+
show fieldsOf(extended)
|
|
24
|
+
|
|
25
|
+
test "book schema"
|
|
26
|
+
check title of fav equals "IOPL in Action"
|
|
27
|
+
check rating of fav equals 4.5
|
|
28
|
+
check hasField(fav, "author") equals false
|
|
29
|
+
done
|
|
30
|
+
|
|
31
|
+
test "generator"
|
|
32
|
+
remember ids as spread of range(1, 4)
|
|
33
|
+
check length(ids) equals 3
|
|
34
|
+
check sum(ids) equals 6
|
|
35
|
+
done
|
|
36
|
+
|
|
37
|
+
make makeTitles(catalog)
|
|
38
|
+
for each book in catalog
|
|
39
|
+
yield title of book
|
|
40
|
+
done
|
|
41
|
+
done
|
|
42
|
+
|
|
43
|
+
show spread of makeTitles([fav, extended])
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Functional transformations
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/search-and-filter.ps
|
|
4
|
+
//
|
|
5
|
+
// gather / filter / total map, filter and reduce in place; match routes a
|
|
6
|
+
// value to behaviour.
|
|
7
|
+
|
|
8
|
+
remember scores as [70, 45, 92, 38, 60]
|
|
9
|
+
|
|
10
|
+
gather each score in scores giving score + 5
|
|
11
|
+
show scores // [ 75, 50, 97, 43, 65 ]
|
|
12
|
+
|
|
13
|
+
filter each score in scores when score is at least 60
|
|
14
|
+
show scores // [ 75, 97, 65 ]
|
|
15
|
+
|
|
16
|
+
remember prices as [19.99, 4.99, 29.99]
|
|
17
|
+
total each price in prices giving price
|
|
18
|
+
show prices // 54.97
|
|
19
|
+
|
|
20
|
+
// Pattern matching
|
|
21
|
+
remember day as "wed"
|
|
22
|
+
|
|
23
|
+
match day against
|
|
24
|
+
"mon" -> show "Start of the week"
|
|
25
|
+
"wed" -> show "Middle of the week"
|
|
26
|
+
"fri" -> show "Almost there"
|
|
27
|
+
otherwise -> show "Another day"
|
|
28
|
+
done
|
|
29
|
+
|
|
30
|
+
// Regex matching extracts a group into a variable
|
|
31
|
+
match pattern "^([0-9]+)$" in "2026" as digits
|
|
32
|
+
if digits is not empty
|
|
33
|
+
show "matched digits: " + first of digits
|
|
34
|
+
done
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// PlainScript v1.0.0 — Sessions, cookies and rate limiting
|
|
2
|
+
//
|
|
3
|
+
// Run with: plainscript run examples/sessions-and-cookies.ps
|
|
4
|
+
// Then try:
|
|
5
|
+
// curl -c cookies.txt -b cookies.txt http://localhost:3000/login
|
|
6
|
+
// curl -c cookies.txt -b cookies.txt http://localhost:3000/profile
|
|
7
|
+
// curl -c cookies.txt -b cookies.txt http://localhost:3000/logout
|
|
8
|
+
//
|
|
9
|
+
// The app shows login/logout flow backed by signed sessions, preference
|
|
10
|
+
// cookies, and a per-IP rate limit.
|
|
11
|
+
|
|
12
|
+
web app
|
|
13
|
+
|
|
14
|
+
limit requests to 100 per minute
|
|
15
|
+
enable sessions "a-long-random-secret-minimum"
|
|
16
|
+
|
|
17
|
+
allow cors
|
|
18
|
+
|
|
19
|
+
route get "/login"
|
|
20
|
+
user of session of request becomes "ada"
|
|
21
|
+
set cookie "theme" to "dark" expires in 7 days
|
|
22
|
+
reply json
|
|
23
|
+
welcome is true
|
|
24
|
+
who is user of session of request
|
|
25
|
+
done
|
|
26
|
+
done
|
|
27
|
+
|
|
28
|
+
route get "/profile"
|
|
29
|
+
remember who as user of session of request
|
|
30
|
+
if who is empty
|
|
31
|
+
status 401
|
|
32
|
+
reply "Please log in first via /login"
|
|
33
|
+
otherwise
|
|
34
|
+
reply json
|
|
35
|
+
user is who
|
|
36
|
+
theme is cookie("theme")
|
|
37
|
+
done
|
|
38
|
+
done
|
|
39
|
+
done
|
|
40
|
+
|
|
41
|
+
route post "/logout"
|
|
42
|
+
destroy session
|
|
43
|
+
clear cookie "theme"
|
|
44
|
+
reply "Logged out. Goodbye!"
|
|
45
|
+
done
|
|
46
|
+
|
|
47
|
+
when nothing matches
|
|
48
|
+
status 404
|
|
49
|
+
reply json
|
|
50
|
+
error is "no such road"
|
|
51
|
+
done
|
|
52
|
+
done
|
|
53
|
+
|
|
54
|
+
start 3000
|