plainscript-lang 1.0.2 → 1.0.3-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +194 -736
  2. package/compiler/cli.js +13 -17
  3. package/compiler/generator.js +93 -21
  4. package/compiler/version.js +1 -1
  5. package/docs/CAPABILITY_GAP_AUDIT.md +98 -536
  6. package/docs/PLAINSCRIPT-SPEC.md +308 -557
  7. package/docs/index.html +101 -599
  8. package/docs/website/script.js +59 -1029
  9. package/docs/website/style.css +74 -656
  10. package/examples/ai-providers.pln +7 -0
  11. package/examples/arrays.pln +4 -12
  12. package/examples/async-errors.pln +18 -0
  13. package/examples/auth-api.pln +3 -50
  14. package/examples/auth-sessions.pln +32 -0
  15. package/examples/basics.pln +14 -0
  16. package/examples/bots.pln +13 -0
  17. package/examples/cache-and-jobs.pln +6 -28
  18. package/examples/cache-schedule.pln +22 -0
  19. package/examples/collections.pln +15 -0
  20. package/examples/concurrency.pln +12 -43
  21. package/examples/conditions.pln +22 -0
  22. package/examples/database.pln +6 -39
  23. package/examples/day2.pln +6 -6
  24. package/examples/day3.pln +4 -10
  25. package/examples/deployment.pln +3 -9
  26. package/examples/email-send.pln +3 -22
  27. package/examples/error-handling.pln +6 -54
  28. package/examples/expressions.pln +7 -40
  29. package/examples/file-uploads.pln +5 -34
  30. package/examples/files-and-config.pln +5 -46
  31. package/examples/files.pln +12 -0
  32. package/examples/football-backend/app.pln +21 -20
  33. package/examples/functions.pln +17 -0
  34. package/examples/hello.pln +2 -3
  35. package/examples/http-client.pln +3 -44
  36. package/examples/http.pln +11 -0
  37. package/examples/id-verification/app.pln +4 -3
  38. package/examples/id-verification/make-sample-id.js +29 -42
  39. package/examples/json.pln +11 -0
  40. package/examples/loops.pln +13 -11
  41. package/examples/modules/app.pln +3 -16
  42. package/examples/modules/main.pln +4 -0
  43. package/examples/modules/math.pln +5 -16
  44. package/examples/objects.pln +3 -11
  45. package/examples/ocr.pln +22 -0
  46. package/examples/packages.pln +6 -0
  47. package/examples/record-kinds.pln +6 -42
  48. package/examples/records.pln +15 -0
  49. package/examples/rest-api-fetch.pln +6 -90
  50. package/examples/rest-api.pln +5 -65
  51. package/examples/scheduled-tasks.pln +4 -23
  52. package/examples/search-and-filter.pln +4 -34
  53. package/examples/server.pln +5 -24
  54. package/examples/sessions-and-cookies.pln +4 -50
  55. package/examples/sqlite.pln +23 -0
  56. package/examples/start.pln +2 -2
  57. package/examples/stdlib.pln +4 -41
  58. package/examples/telegram-ai-bot.pln +19 -0
  59. package/examples/telegram-bot.pln +4 -40
  60. package/examples/testing.pln +13 -0
  61. package/examples/web-api.pln +27 -0
  62. package/examples/web-app.pln +4 -16
  63. package/examples/websocket-server.pln +5 -26
  64. package/examples/websocket.pln +13 -0
  65. package/examples/whatsapp-bot/pairing.pln +4 -5
  66. package/examples/whatsapp-bot/qr.pln +7 -3
  67. package/package.json +2 -2
package/README.md CHANGED
@@ -1,880 +1,338 @@
1
1
  # PlainScript
2
2
 
3
3
  [![CI](https://github.com/ayoistooslick/plainscript/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/ayoistooslick/plainscript/actions/workflows/npm-publish.yml)
4
- [![npm version](https://badge.fury.io/js/plainscript-lang.svg?icon=si%3Anpm)](https://www.npmjs.com/package/plainscript-lang)
5
- [![Downloads](https://img.shields.io/badge/downloads-1.1GB/month-green)](https://www.npmjs.com/package/plainscript-lang)
6
-
7
- <p align="center">
8
- <img src="https://github.com/ayoistooslick/plainscript/blob/main/docs/logo.jpg" alt="PlainScript Logo" width="200" />
9
- </p>
10
-
11
- > "When even a simple sentence can be code."
12
- > Don't forget to star the repo
13
-
14
- PlainScript is an Intent-Oriented Programming Language (IOPL). You describe **what** you want; the compiler decides **how** to implement it in JavaScript.
15
-
16
- **Current version:** v1.0.2 — the `plainscript` npm package with a TypeScript-style production build (`plainscript build` → `dist/`, source names preserved).
17
-
18
- ---
4
+ [![npm version](https://badge.fury.io/js/plainscript-lang.svg)](https://www.npmjs.com/package/plainscript-lang)
5
+ PlainScript is an intent-oriented language that compiles `.pln` source to
6
+ readable Node.js. The compiler and parser in `compiler/` are the source of
7
+ truth for version `1.0.3-beta`.
19
8
 
20
9
  ## Quick start
21
10
 
22
11
  ```bash
23
- npx plainscript new myapp # scaffolds src/app.pln and package.json
24
- cd myapp
25
- npm install # installs plainscript as a devDependency plus runtime packages
26
- npm run build # compiles src/ -> dist/ (plainscript build)
27
- node dist/app.js # or: npm start
12
+ npx plainscript new hello
13
+ cd hello
14
+ npm install
15
+ npx plainscript check
16
+ npm run build
17
+ npm start
28
18
  ```
29
19
 
30
- Adding PlainScript to an existing project:
20
+ Run a single source file without writing build output:
31
21
 
32
22
  ```bash
33
- npm install --save-dev plainscript-lang
34
- # start writing src/*.pln files — plainscript build auto-discovers them
23
+ npx plainscript run examples/basics.pln
35
24
  ```
36
25
 
37
- No global install is needed anywhere — everything runs through npm scripts
38
- and `npx`.
39
-
40
- ---
41
-
42
26
  ## CLI
43
27
 
28
+ ```text
29
+ plainscript new [name] Create an npm-ready project
30
+ plainscript check [target] Validate one file, a directory, or the project
31
+ plainscript build [file] Compile source files to dist/
32
+ plainscript run <file> Validate, install missing packages, and run
33
+ plainscript start Build src/app.pln and start it
34
+ plainscript fmt <file> Format a source file in place
35
+ plainscript install Install packages detected in source
36
+ plainscript add <package> Add an npm package
37
+ plainscript remove <package> Remove an npm package
38
+ plainscript update Update installed packages
39
+ plainscript doctor Inspect the local project setup
40
+ plainscript version Print 1.0.3-beta
44
41
  ```
45
- plainscript run <file.pln> Install missing dependencies, compile and execute
46
- (executes from a scratch dir — nothing is written
47
- into your project)
48
- plainscript build [file.pln] Compile to dist/. With no argument, builds every
49
- .pln file under the source root, preserving names
50
- and folder structure
51
- plainscript check <file.pln> Check syntax only (no output, no execution)
52
- plainscript fmt <file.pln> Format a PlainScript file in-place
53
- plainscript new [name] Create a new PlainScript project (npm-ready)
54
- plainscript install Install dependencies detected in the project's sources
55
- plainscript start Build src/app.pln and run its dist/ output
56
- plainscript doctor Check the PlainScript project environment
57
- plainscript add <package> Install a package into the project
58
- plainscript remove <package> Uninstall a package from the project
59
- plainscript update Update all installed npm packages
60
- plainscript version Print the compiler version
61
- plainscript help Print help text
62
- ```
63
-
64
- ---
65
-
66
- ## Building and configuration
67
-
68
- `plainscript build` is a deterministic production build, TypeScript-style but for
69
- `.pln` sources — **zero configuration required**:
70
42
 
71
- - `plainscript build` (no argument) discovers every `.pln` file under `src/` and
72
- compiles each to `dist/` **preserving source file names and folder structure**:
73
- `src/messi.pln` → `dist/messi.js`,
74
- `src/helpers/math.pln` → `dist/helpers/math.js`.
75
- - `plainscript build <file.pln>` compiles a single file into `dist/`.
76
- - Imports are bundled into each output, so every file in `dist/` runs
77
- standalone under Node.
78
- - Rebuilds are byte-identical — safe to commit, diff, and cache.
43
+ `plainscript check` resolves imports, parses every file, generates JavaScript,
44
+ and verifies the generated output with Node's JavaScript parser. Use it after
45
+ every source change.
79
46
 
80
- Source discovery skips `node_modules`, hidden directories, and the output
81
- directory itself. When no `src/` directory exists, the project root is scanned
82
- instead.
47
+ ## Core syntax
83
48
 
84
- ### Optional `plainscript.config.json`
85
-
86
- For projects that need custom output or source directories, add a
87
- `plainscript.config.json` with a `compilerOptions` block (like `tsconfig.json`):
88
-
89
- ```json
90
- {
91
- "compilerOptions": {
92
- "outDir": "./build",
93
- "rootDir": "./lib",
94
- "exclude": ["vendor"]
95
- }
96
- }
97
- ```
98
-
99
- ### Publishing a library written in PlainScript
100
-
101
- ```json
102
- {
103
- "name": "my-plainscript-library",
104
- "main": "dist/index.js",
105
- "scripts": {
106
- "build": "plainscript build",
107
- "prepare": "plainscript build"
108
- },
109
- "devDependencies": { "plainscript-lang": "^1.0.2" }
110
- }
111
- ```
112
-
113
- `src/index.pln` builds to `dist/index.js`; consumers install and `require()`
114
- it like any Node package. There is no PlainScript-specific registry or format —
115
- standard `package.json` semantics apply.
116
-
117
- ---
118
-
119
- ## Language features
120
-
121
- ### Variables
49
+ ### Variables and output
122
50
 
123
51
  ```plainscript
124
- let name be "Ayokunle"
125
- let age be 16
126
- set age to 17
127
- ```
128
-
129
- ### String Templates
130
-
131
- Backtick-delimited strings preserve whitespace and support `${expression}` interpolation:
132
-
133
- ```plainscript
134
- let name be "World"
135
- let greeting be `Hello ${name}!`
52
+ remember name as "Ada"
53
+ let count is 3
54
+ let greeting is `Hello, ${name}!`
136
55
  show greeting
137
-
138
- let email be `Dear ${customer},
139
-
140
- Thank you for your order #${orderId}.
141
-
142
- Best regards,
143
- The Team`
56
+ count becomes count + 1
144
57
  ```
145
58
 
146
- Interpolation compiles directly to JavaScript template literals — it is not evaluated at compile time. Literal dollar signs without `{` are preserved as-is.
59
+ `remember name as value` is the standard declaration form. `let name be value`
60
+ is an English alias. `show`, `print`, and `display` write a value.
147
61
 
148
62
  ### Conditions
149
63
 
150
64
  ```plainscript
151
- when age is at least 18
152
- show "Adult"
65
+ if score is at least 80 and status is not "blocked"
66
+ show "accepted"
153
67
  otherwise
154
- show "Teenager"
155
- done
156
-
157
- when name contains "PlainScript"
158
- show "Found it"
159
- done
160
-
161
- when score between 90 and 100
162
- show "A grade"
68
+ show "review"
163
69
  done
164
70
  ```
165
71
 
166
- English alternatives: `same as` (`===`), `different from` (`!==`), `more than` (`>`), `fewer than` (`<`).
167
-
168
- All comparison operators:
169
-
170
- | PlainScript | JavaScript |
171
- |------------------------|--------------------|
172
- | `is` / `is equal to` | `===` |
173
- | `same as` | `===` |
174
- | `is not` | `!==` |
175
- | `different from` | `!==` |
176
- | `is greater than` / `is above` | `>` |
177
- | `more than` | `>` |
178
- | `is less than` / `is below` | `<` |
179
- | `fewer than` | `<` |
180
- | `is at least` | `>=` |
181
- | `is at most` | `<=` |
182
- | `is empty` | `.length === 0` |
183
- | `is not empty` | `.length > 0` |
184
- | `contains "x"` | `.includes("x")` |
185
- | `made of "x"` | `.includes("x")` |
186
- | `starts with "x"` | `.startsWith("x")` |
187
- | `starts as "x"` | `.startsWith("x")` |
188
- | `ends with "x"` | `.endsWith("x")` |
189
- | `ends as "x"` | `.endsWith("x")` |
190
- | `between A and B` | `>= A && <= B` |
191
- | `has field "x"` | `"x" in obj` |
192
- | `at position key` | `obj[key]` |
193
-
194
- ### Functions
195
-
196
- ```plainscript
197
- to add a and b together
198
- give back a + b
199
- done
200
- show add(5, 7)
72
+ Supported readable comparisons include `is`, `same as`, `different from`,
73
+ `more than`, `fewer than`, `is at least`, `is less than`, `contains`,
74
+ `starts with`, `ends with`, `between`, `and`, `or`, and `not`.
201
75
 
202
- to multiply x and y together
203
- give back x * y
204
- done
205
- ```
206
-
207
- ### Arrays & Objects
76
+ ### Lists and records
208
77
 
209
78
  ```plainscript
210
- let players be list with "Haaland", "Foden", "Rodri"
211
- show players[0]
212
- set players[1] to "Palmer"
79
+ remember players as list with "Ada", "Grace", "Lin"
80
+ show players at position 1
213
81
 
214
- let user be record with
215
- name "Ayokunle"
216
- age 17
217
- done
82
+ remember user as record with name "Ada" and active true done
218
83
  show user.name
219
84
  ```
220
85
 
221
- ### Loops
222
-
223
- ```plainscript
224
- for each player in players
225
- show player
226
- done
227
-
228
- for every item in basket // alias for "for each"
229
- show item
230
- done
231
-
232
- while age is less than 18
233
- set age to age + 1
234
- done
235
- ```
236
-
237
- ### PlainScript Expressions
238
-
239
- Collections, properties, and files read like sentences.
86
+ Inline JavaScript array and object literals are also supported:
87
+ `[1, 2, 3]` and `{name: "Ada", active: true}`.
240
88
 
241
- **Items**
242
-
243
- ```plainscript
244
- let players be list with "Haaland", "Foden", "Rodri"
245
-
246
- show first player from players // players[0]
247
- show last player from players // players[players.length - 1]
248
- show player two from players // players[1]
249
- first player from players is now "Haaland" // players[0] = "Haaland"
250
- ```
251
-
252
- Number words from `one` to `twenty` map to one-based positions: `player one` is the first item.
253
-
254
- **Collections**
255
-
256
- ```plainscript
257
- show players length // players.length
258
- add("Palmer" to players) // players.push("Palmer")
259
- remove("Rodri" from players) // players.splice(players.indexOf("Rodri"), 1)
260
-
261
- when players contains "Foden" // players.includes("Foden")
262
- show "Found"
263
- done
264
- ```
265
-
266
- English alternatives: `made of` (`.includes()`), `starts as` (`.startsWith()`), `ends as` (`.endsWith()`), `has field` (`in`), `at position` (`[]`).
267
-
268
- **Properties**
269
-
270
- ```plainscript
271
- show name of user // user.name
272
- show city of address of customer // customer.address.city
273
- name of user is now "Ayo" // user.name = "Ayo"
274
- ```
275
-
276
- `of` chains right-to-left: `city of address of customer` reads the city of the address of the customer.
277
-
278
- **Files**
279
-
280
- ```plainscript
281
- let data be read("users.txt") // fs.readFileSync("users.txt", 'utf8')
282
- write(data to "users.txt") // fs.writeFileSync(data, "users.txt", 'utf8')
283
- ```
284
-
285
- The older `readFile()` / `writeFile()` forms still work and are unchanged.
286
-
287
- ### Logical Assignment
288
-
289
- ```plainscript
290
- let flag be false
291
- flag or is now true
292
- show flag
293
-
294
- let val be null
295
- val nullish is now "default"
296
- show val
297
- ```
298
-
299
- ### TypeScript-parity capabilities (1.0.2)
300
-
301
- The full capability-gap audit lives in [`docs/CAPABILITY_GAP_AUDIT.md`](https://github.com/ayoistooslick/plainscript/blob/main/docs/CAPABILITY_GAP_AUDIT.md).
302
- These features close it in PlainScript's own grammar:
303
-
304
- - **Record kinds (classes):** `to define a kind called "Person" with name "" end`
305
- + `create a Person with name "Ada" and age 17`. Plain-object instances; unknown
306
- fields throw.
307
- - **Concurrency:** `all of [...]`, `any of [...]`, `settled of [...]`,
308
- `withTimeout(promise, ms)`.
309
- - **Generators:** `yield` inside `define ... end`; consumed with `for each` or
310
- `spread of`.
311
- - **Reflection:** `typeOf`, `fieldsOf`, `valueOf`, `hasField`, `sizeOf`.
312
- - **Binary:** `base64Encode/Decode`, `textToBytes/bytesToText`, `sha256/sha1/md5`.
313
- - **Config:** `yamlDecode/yamlEncode`, `load env file ".env"`.
314
- - **CLI & processes:** `args()`, `runCommand(cmd, [args])`.
315
- - **Filesystem & paths:** `fileSize`, `fileType`, `lastModified`, `walkFolder`,
316
- `joinPath`, `baseName`, `folderOf`, `extensionOf`.
317
- - **Streams:** `writeLine`, `appendLine`.
318
- - **Collections:** `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet`.
319
- - **Dynamic modules:** `loadModule("./m")`.
320
- - **Native tests:** `test "name" ... end` with `check a equals b`,
321
- `check a contains b`, `check a is b`, `check <expr> raises "msg"`.
322
- - **Exports:** `export <name>`.
323
-
324
- ---
325
-
326
- ## Backend Services
327
-
328
- Everything below is compiled by the deterministic compiler — no rules, no AI,
329
- no hidden codegen.
330
-
331
- ### Portable databases (SQLite native or WebAssembly)
332
-
333
- ```plainscript
334
- database "app.db" // probes better-sqlite3, falls back to sql.js
335
- ```
336
-
337
- `plainscript install` verifies that `better-sqlite3` actually loads; if the native
338
- module cannot be used, PlainScript warns and continues on the pure-JavaScript
339
- WebAssembly engine (`sql.js`) — the same program runs unchanged. Force an
340
- engine explicitly:
341
-
342
- ```plainscript
343
- database "app.db" using "native" // hard requirement: better-sqlite3
344
- database "app.db" using "wasm" // hard requirement: sql.js
345
- ```
346
-
347
- The WebAssembly engine persists the whole database to disk after every write,
348
- so data survives restarts either way.
349
-
350
- ### HTTP client
89
+ ### Functions
351
90
 
352
91
  ```plainscript
353
- let r be get "https://api.example.com/users"
354
- when ok of r
355
- show status of r
356
- show data of r
92
+ make add(a, b)
93
+ give a + b
357
94
  done
358
95
 
359
- let created be post url with body
360
- headers record with accept "application/json" done
361
- timeout 5000
96
+ show add(2, 3)
362
97
  ```
363
98
 
364
- Methods: `get`, `post … with <body>`, `put`, `patch`, `delete "<url>"`.
365
- Responses are records: `ok`, `status`, `headers`, `data` (JSON is parsed
366
- automatically). The default timeout is 30 seconds. `wait for fetch(...)`
367
- awaits raw promises when you need it.
368
-
369
- ### Passwords and tokens (built-in auth)
99
+ Defaults use `as` in the parameter list:
370
100
 
371
101
  ```plainscript
372
- let hash be hashPassword("correct horse")
373
- when checkPassword(password of body of request, hash)
374
- let token be createToken(user, env("TOKEN_SECRET"), 3600)
102
+ make greet(name as "friend")
103
+ give `Hello, ${name}`
375
104
  done
376
-
377
- let payload be readToken(token, env("TOKEN_SECRET"))
378
105
  ```
379
106
 
380
- `hashPassword`/`checkPassword` use scrypt; tokens are HMAC-signed with an
381
- expiry and fail closed on tampering or timeout.
107
+ The readable declaration form is `to add a and b together`, with `give` as
108
+ the return statement and `together` as the closing marker.
382
109
 
383
- ### Sessions
110
+ ### Loops
384
111
 
385
112
  ```plainscript
386
- web app
387
- enable sessions "a-long-random-secret"
388
-
389
- route post "/login"
390
- user of session of request is username of body of request
391
- show "welcome"
113
+ for each player in players
114
+ show player
392
115
  done
393
116
 
394
- route get "/me"
395
- show user of session of request
117
+ for index position from 0 to 2
118
+ show position
396
119
  done
397
120
 
398
- route post "/logout"
399
- destroy session
400
- show "bye"
121
+ while attempts is less than 3
122
+ attempts becomes attempts + 1
401
123
  done
402
124
  ```
403
125
 
404
- Sessions ride an HMAC-signed `HttpOnly` cookie (`plainscript.sid`). The store is
405
- in-memory: restarting the server signs everyone out.
406
-
407
- ### File uploads
126
+ ### Record kinds
408
127
 
409
128
  ```plainscript
410
- accept uploads limit "5 MB" allow list with "image/png", "image/jpeg" folder "uploads"
411
-
412
- route post "/scan"
413
- let file be upload("doc")
414
- ocr path of file as text
415
- show "scanned: " + text
129
+ define a kind called "Player" with
130
+ name is ""
131
+ goals is 0
416
132
  done
417
- ```
418
-
419
- Files arrive as records with `name`, `type`, `size`, `data` (buffer) and
420
- `path` (string, when a folder is set). Oversized files get HTTP 413, wrong
421
- types 415. `uploads("docs")` returns every file under a field name.
422
-
423
- ### Cookies
424
-
425
- ```plainscript
426
- set cookie "theme" to "dark" expires in 7 days
427
- show cookie("theme")
428
- clear cookie "theme"
429
- ```
430
-
431
- ### Rate limiting
432
133
 
433
- ```plainscript
434
- rate limit 100 requests per minute
134
+ remember player as create a Player with name "Ada" and goals 4
435
135
  ```
436
136
 
437
- Sliding window per client IP; the quota-exceeded response is HTTP 429.
137
+ ## AI providers and Telegram
438
138
 
439
- ### Google OAuth
139
+ AI helpers work across command-line programs, web routes, scheduled jobs, and
140
+ bot handlers. `chat` uses the OpenAI-compatible API shape; choose a built-in
141
+ provider or pass a custom endpoint. API keys stay in environment variables.
440
142
 
441
143
  ```plainscript
442
- google oauth
443
- id is env("GOOGLE_ID")
444
- secret is env("GOOGLE_SECRET")
445
- callback is "https://myapp.dev/auth/google/callback"
446
- landing is "/dashboard"
447
- done
144
+ remember answer as chat("llama-3.3-70b-versatile", "Summarize PlainScript", {
145
+ provider: "groq",
146
+ key: env("GROQ_API_KEY"),
147
+ temperature: 0.2
148
+ })
149
+ show answer
448
150
  ```
449
151
 
450
- Registers `/auth/google` (redirect) and `/auth/google/callback`
451
- (code-for-token exchange + profile fetch); after login the session holds the
452
- user and the browser lands on `landing`.
152
+ `groq`, `openai`, `openrouter`, `together`, `fireworks`, and `deepseek` are
153
+ supported provider presets. `chatWith("groq", model, messages)` and
154
+ `embedWith("groq", model, text)` are explicit provider-first forms. For any
155
+ OpenAI-compatible service, pass `base`, `key`, and optionally `headers`.
453
156
 
454
- ### Custom 404
157
+ Telegram supports fixed replies, command arguments, regex captures, callbacks,
158
+ inline buttons, and the complete raw Bot API:
455
159
 
456
160
  ```plainscript
457
- when nothing matches
458
- status 404
459
- show json
460
- error is "No such road"
461
- done
161
+ bot env("TELEGRAM_BOT_TOKEN")
162
+ when someone sends "/start"
163
+ reply "Welcome"
462
164
  done
463
- ```
464
-
465
- ### Error handling and retries
466
-
467
- ```plainscript
468
- try
469
- let data be jsonDecode(raw)
470
- recover as err
471
- show "bad json: " + message of err
472
- done
473
-
474
- retry 3 times every 5 seconds
475
- wait for fetch("https://flaky.api")
165
+ when someone sends matching "/ask (.+)"
166
+ remember answer as chatWith("groq", "llama-3.3-70b-versatile", message)
167
+ reply answer
476
168
  done
169
+ start telegram bot
477
170
  ```
478
171
 
479
- ---
480
-
481
- ## Runtime Standard Library
482
-
483
- No imports needed. These functions are built into the compiler:
484
-
485
- | PlainScript | Description |
486
- |--------------------------|------------------------------------|
487
- | `show(x)` | Print a value (`console.log`) |
488
- | `readFile("path")` | Read a file as UTF-8 text |
489
- | `writeFile("path", data)` | Write text to a file |
490
- | `read("path")` | Read a file as UTF-8 text |
491
- | `fileExists("path")` | Check if a file exists |
492
- | `sleep(ms)` | Sleep synchronously |
493
- | `time()` | Current Unix timestamp (`Date.now()`) |
494
- | `date()` | ISO date string |
495
- | `jsonEncode(value)` | `JSON.stringify` |
496
- | `jsonDecode(string)` | `JSON.parse` |
497
- | `env("KEY")` | Read environment variable |
498
- | `exit(code)` | Exit the process |
499
- | `uuid()` | Generate a UUID v4 |
500
- | `length(x)` | Length of array/string |
501
- | `uppercase(x)` | Convert to uppercase |
502
- | `lowercase(x)` | Convert to lowercase |
503
- | `random()` | Random number 0–1 |
504
- | `round(x)` | Round to nearest integer |
505
-
506
- ---
507
-
508
- ## Web Apps
509
-
510
- ```plainscript
511
- web app
512
-
513
- route "/"
514
- show "Hello from PlainScript!"
515
- done
516
-
517
- route "/api/status"
518
- show json
519
- status is "ok"
520
- version is "2.0"
521
- done
522
- done
523
-
524
- start 3000
525
- ```
172
+ Inside a Telegram handler, `message`, `text`, `args`, `matches`, `chat`,
173
+ `chatId`, and callback `data` refer to the current update. Use
174
+ `telegramCall("sendChatAction", {chat_id: chatId, action: "typing"})` for API
175
+ methods not wrapped by a named helper.
526
176
 
527
- ---
177
+ ## Standard library
528
178
 
529
- ## SQLite Database
179
+ No import is needed for built-ins such as:
530
180
 
531
181
  ```plainscript
532
- database "app.db"
533
-
534
- execute
535
- CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)
536
- done
537
-
538
- insert
539
- INSERT INTO users (name) VALUES ('Alice')
540
- done
541
-
542
- let rows be query
543
- SELECT * FROM users
544
- done
182
+ remember encoded as jsonEncode(user)
183
+ remember decoded as jsonDecode(encoded)
184
+ remember contents as readFile("notes.txt")
185
+ writeFile("notes.txt", contents)
186
+ remember digest as sha256("plain text")
187
+ remember currentTime as time()
188
+ remember identifier as uuid()
545
189
  ```
546
190
 
547
- ---
548
-
549
- ## Backend Capabilities
550
-
551
- Everything a backend needs, as first-class deterministic language features —
552
- no rules, no AI, no hidden codegen.
191
+ Important groups include string and collection helpers, path and file
192
+ operations, JSON, time, environment variables, crypto, passwords and tokens,
193
+ HTTP accessors, cache, and async helpers. The generated runtime is in
194
+ `compiler/generator.js`; do not invent a built-in that is not implemented
195
+ there.
553
196
 
554
- ### HTTP routing
197
+ ## Web applications
555
198
 
556
199
  ```plainscript
557
200
  web app
558
201
  allow cors
559
202
 
560
- group "/api"
561
-
562
- route get "/users"
563
- let users be query
564
- SELECT * FROM users
565
- done
566
- show users
203
+ route get "/health"
204
+ reply json
205
+ ok is true
567
206
  done
207
+ done
568
208
 
569
- route post "/users"
570
- let missing be validate(body of request, list with "name", "email")
571
- when length of missing is greater than 0
572
- status 400
573
- show missing
574
- otherwise
575
- show "created"
576
- done
209
+ route post "/echo"
210
+ remember body as body of request
211
+ reply json
212
+ received is body
577
213
  done
578
-
579
214
  done
580
215
 
581
- start env("PORT")
216
+ start 3000
582
217
  ```
583
218
 
584
- `param("id")`, `query("page")` and `header("x-token")` read request data;
585
- `body()` / `body("field")` read the JSON request body; `group` composes path
586
- prefixes; `status <n>` sets the response code and `redirect to "<url>"` issues a
587
- redirect.
588
-
589
- ### Databases with parameters and transactions
590
-
591
- ```plainscript
592
- database "app.db" // or: postgres env("DATABASE_URL")
219
+ Routes support `get`, `post`, `put`, `patch`, and `delete`. Request values use
220
+ `body of request`, `param("id")`, `query("page")`, `header("x-name")`,
221
+ `upload("field")`, and `uploads("field")`. Use `status 404`, `redirect to
222
+ "..."`, and `when nothing matches` for common response behavior.
593
223
 
594
- transaction
595
- insert
596
- INSERT INTO users (name) VALUES ({who})
597
- done
598
- done
599
- ```
224
+ Backend declarations include `enable sessions "secret"`, `set cookie "name"
225
+ to value`, `limit requests to 100 per minute`, `require api key from key`, and
226
+ `accept uploads limit "5 MB" allow list with "image/png" folder "uploads"`.
600
227
 
601
- Placeholders `{likeThis}` bind to PlainScript variables. `postgres "..."` switches
602
- every SQL statement to node-postgres pool queries (`$n`, awaited).
603
-
604
- ### Email
228
+ ## HTTP client
605
229
 
606
230
  ```plainscript
607
- mail transport
608
- host is "smtp.gmail.com"
609
- port is 587
610
- user is env("EMAIL_USER")
611
- pass is env("EMAIL_PASS")
612
- done
613
-
614
- send mail
615
- from is "hello@plainscript.dev"
616
- to is "you@example.com"
617
- subject is "Hello from PlainScript"
618
- text is "Sent from a PlainScript program."
619
- done
231
+ remember response as get "https://example.com/data" timeout 5000
232
+ remember created as post "https://example.com/data" with {name: "Ada"} headers {contentType: "application/json"}
233
+ show response.status
620
234
  ```
621
235
 
622
- ### Cron and background jobs
236
+ ## SQLite and SQL
623
237
 
624
238
  ```plainscript
625
- every 5 minutes
626
- show "heartbeat"
627
- done
239
+ database "app.db" using "wasm"
240
+ remember name as "Ada"
628
241
 
629
- schedule "0 2 * * *"
630
- show "nightly cleanup"
242
+ execute
243
+ CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER)
631
244
  done
632
245
 
633
- to resize name
634
- show `resizing ${name}`
246
+ insert
247
+ INSERT INTO people (name, age) VALUES ({name}, 36)
635
248
  done
636
249
 
637
- run background resize("photo.png")
638
- ```
639
-
640
- ### WebSocket servers
641
-
642
- ```plainscript
643
- websocket server on 8080
644
- when socket connects
645
- send socket "Welcome!"
646
- done
647
- when socket sends message
648
- broadcast message
649
- done
250
+ remember people as query
251
+ SELECT name, age FROM people
650
252
  done
651
253
  ```
652
254
 
653
- ### Cache (Redis with in-memory fallback)
255
+ `database` accepts `using "native"` or `using "wasm"`. A SQL placeholder
256
+ `{name}` is bound to the PlainScript variable rather than interpolated.
257
+ `transaction ... done` groups writes.
654
258
 
655
- ```plainscript
656
- cache env("REDIS_URL") // omit for an in-memory Map store with TTL
657
- let token be cacheGet("token")
658
- cacheSet("greeting", "hi", 60)
659
- cacheDelete("greeting")
660
- ```
661
-
662
- Without a configured Redis, `cacheGet`/`cacheSet`/`cacheDelete` transparently fall
663
- back to an in-memory store, so naive caching works out of the box.
664
-
665
- ### AI / ML
259
+ ## Errors, async, and concurrency
666
260
 
667
261
  ```plainscript
668
- let reply be chat("gpt-4o-mini", list with
669
- record with role "user" and content "Say hello in two words"
670
- done)
671
-
672
- let vec be embedText("text-embedding-3-small", "PlainScript rocks")
673
- let score be similarity(vec, embedText("text-embedding-3-small", "I love PlainScript"))
674
-
675
- let tags be ai_tags("PlainScript is an intent-oriented language")
676
- let article be ai_post("Welcome to PlainScript", list with "why IOPL", "quick start")
677
- ```
678
-
679
- `chat` and `embedText` are async OpenAI-compatible calls (from `OPENAI_API_KEY`,
680
- override with `options.apiKey`/`options.baseURL`); `similarity` returns -1..1.
681
-
682
- ### Pagination
262
+ try
263
+ remember result as get "https://example.com" timeout 5000
264
+ recover as error
265
+ show message of error
266
+ finally
267
+ show "finished"
683
268
 
684
- ```plainscript
685
- let page be paginate(allUsers, 2, 10)
686
- show page.items # second page of 10
687
- show page.hasNext # true if another page exists
269
+ retry 3 times every 1 second
270
+ show "attempt"
271
+ done
688
272
  ```
689
273
 
690
- `paginate(list, page, perPage)` returns
691
- `record with items, count, page, pages, perPage, hasNext, hasPrev done`.
692
-
693
- ---
274
+ Use `allOf(list with one(), two())`, `anyOf(...)`, `settledOf(...)`, and
275
+ `withTimeout(promise, milliseconds)` for concurrent operations. `every 5
276
+ minutes ... done` and `schedule "0 * * * *" ... done` register recurring work.
694
277
 
695
- ## Multi-file projects
696
-
697
- ```plainscript
698
- import "./math.pln"
699
- import "./utils.pln"
700
-
701
- show PI
702
-
703
- show double(5)
704
- ```
705
-
706
- Imports are bundled per entry: `plainscript build` gives every source file its own
707
- standalone output under `dist/`, with imported code inlined.
708
-
709
- ---
710
-
711
- ## Express server
278
+ ## Modules and packages
712
279
 
713
280
  ```plainscript
281
+ import { circleArea } from "./math.pln"
282
+ export circleArea
714
283
  use express
715
-
716
- let app be express()
717
-
718
- serve folder "public"
719
-
720
- when someone visits "/"
721
- show "Hello from PlainScript!"
722
- done
723
-
724
- when someone visits "/api/status"
725
- show json
726
- status is "ok"
727
- version is "0.3"
728
- done
729
- done
730
-
731
- listen on 3000
732
- show "Server running at http://localhost:3000"
733
- done
734
284
  ```
735
285
 
736
- ---
737
-
738
- ## WhatsApp Bots
739
-
740
- Full WhatsApp connectivity through Baileys — the implementation package is
741
- installed automatically and never appears in your source:
742
-
743
- ```plainscript
744
- whatsapp bot
745
- auth "session" // credential folder, persists
746
- // across restarts
747
- login qr // or: login pairing "2348012345678"
748
-
749
- on message
750
- log message // print the normalized record
751
-
752
- when message.text is "/start"
753
- show "Welcome!"
754
- done
755
-
756
- when message.text is "/help"
757
- show `Available commands:
758
- /start /help`
759
- done
760
- done
761
- done
762
- ```
286
+ Imports are bundled in dependency order. `use` declares an npm dependency that
287
+ the CLI can install. Each compiled entry is standalone.
763
288
 
764
- - `login qr` prints a scannable QR code; `login pairing "<number>"` prints an
765
- enter-on-phone code instead. Pairing numbers are validated at compile time
766
- (digits only after normalization, 8–15).
767
- - `login pairing` also accepts any value — prompt for the number
768
- at runtime instead of hard-coding it:
289
+ ## Testing
769
290
 
770
291
  ```plainscript
771
- ask "WhatsApp number: " as phone
772
-
773
- whatsapp bot
774
- auth "session"
775
- login pairing phone
292
+ test "addition works"
293
+ check add(2, 3) equals 5
776
294
  done
777
295
  ```
778
296
 
779
- - Inside `on message`, `message` holds `record with text, chat, sender, name, id,
780
- time, isGroup done`; `print` answers the current chat.
781
- - The bot ignores its own messages and status broadcasts and keeps working in
782
- groups; transient disconnects reconnect after 3 seconds.
783
-
784
- See `examples/whatsapp-bot/` for ready-to-link programs.
785
-
786
- ---
787
-
788
- ## Project management
789
-
790
- ```bash
791
- plainscript install # Install all detected dependencies
792
- plainscript add express # Add a package
793
- plainscript remove express # Remove a package
794
- plainscript update # Update all packages
795
- plainscript start # Build src/app.pln and run its dist/ output
796
- plainscript doctor # Check project environment
797
- ```
798
-
799
- ---
800
-
801
- ## Supported packages
297
+ Assertions support `equals`, `is`, `contains`, and `raises`.
802
298
 
803
- | PlainScript | Compiles to |
804
- |---------------------------|--------------------------------------|
805
- | `use express` | `const express = require('express');` |
806
- | `use sqlite` | `const Database = require('better-sqlite3');` |
807
- | `use fs` | `const fs = require('fs');` |
808
- | `use path` | `const path = require('path');` |
299
+ ## Bots, OCR, WebSockets, and cache
809
300
 
810
- Any npm package can be used, including hyphenated names like `node-fetch` and
811
- scoped packages like `@scope/package-name`.
301
+ The feature examples in `examples/` are the maintained reference programs:
812
302
 
813
- ---
303
+ | Capability | Example |
304
+ | --- | --- |
305
+ | variables and conditions | `examples/basics.pln`, `examples/conditions.pln` |
306
+ | loops, functions, records | `examples/loops.pln`, `examples/functions.pln`, `examples/records.pln` |
307
+ | JSON, files, packages, HTTP | `examples/json.pln`, `examples/files.pln`, `examples/packages.pln`, `examples/http.pln` |
308
+ | SQLite and web routes | `examples/sqlite.pln`, `examples/web-api.pln` |
309
+ | auth, sessions, cookies | `examples/auth-sessions.pln` |
310
+ | async, errors, concurrency | `examples/async-errors.pln`, `examples/concurrency.pln` |
311
+ | WebSockets and cache | `examples/websocket.pln`, `examples/cache-schedule.pln` |
312
+ | Telegram, AI, and WhatsApp | `examples/bots.pln`, `examples/telegram-bot.pln`, `examples/whatsapp-bot/` |
313
+ | OCR and uploads | `examples/ocr.pln`, `examples/id-verification/` |
314
+ | native tests and modules | `examples/testing.pln`, `examples/modules/` |
315
+ | real-world starters | `templates/` |
814
316
 
815
- ## Running the tests
317
+ ## Verification
816
318
 
817
319
  ```bash
320
+ find examples tests/fixtures -name '*.pln' -print0 |
321
+ xargs -0 -n1 plainscript check
818
322
  npm test
819
323
  ```
820
324
 
821
- ---
325
+ Circular-import fixtures are intentionally rejected by the compiler's
326
+ dependency checks. All maintained runnable examples must pass `plainscript
327
+ check`.
822
328
 
823
- ## Project structure
329
+ ## Project layout
824
330
 
331
+ ```text
332
+ compiler/ lexer, parser, generator, CLI, bundler
333
+ examples/ checked feature and acceptance examples
334
+ tests/ compiler, runtime, compatibility, and acceptance tests
335
+ docs/ website and language reference
336
+ plainscript-vscode/ VS Code extension
337
+ editors/mt-manager/ TextMate-compatible grammar
825
338
  ```
826
- plainscript/
827
- ├── compiler/
828
- │ ├── lexer.js — tokenises PlainScript source into tokens
829
- │ ├── parser.js — builds an AST from tokens
830
- │ ├── generator.js — generates JavaScript from the AST
831
- │ ├── bundler.js — resolves imports and bundles files
832
- │ ├── formatter.js — normalises PlainScript source style
833
- │ ├── dependency-detector.js— detects npm packages from source
834
- │ ├── version.js — single compiler version constant
835
- │ └── cli.js — command-line entry point
836
- │
837
- ├── examples/
838
- │ ├── hello.pln
839
- │ ├── day2.pln
840
- │ ├── day3.pln
841
- │ ├── arrays.pln
842
- │ ├── objects.pln
843
- │ ├── loops.pln
844
- │ ├── expressions.pln
845
- │ ├── stdlib.pln
846
- │ ├── server.pln
847
- │ ├── web-app.pln
848
- │ ├── start.pln
849
- │ ├── database.pln
850
- │ ├── deployment.pln
851
- │ ├── football-backend/ — acceptance example (SQLite + auth + sessions)
852
- │ │ └── app.pln
853
- │ ├── id-verification/ — acceptance example (uploads + OCR matching)
854
- │ │ ├── app.pln
855
- │ │ └── make-sample-id.js
856
- │ └── whatsapp-bot/ — WhatsApp bots (QR and pairing linking)
857
- │ ├── qr.pln
858
- │ └── pairing.pln
859
- │
860
- ├── tests/
861
- │ ├── compiler.test.js — language, CLI and formatter coverage
862
- │ ├── build.test.js — build model, config and packaging coverage
863
- │ ├── backend.test.js — web/database/email/cache runtime tests
864
- │ ├── telegram.test.js — Telegram bot runtime tests
865
- │ ├── ocr.test.js — OCR statement tests
866
- │ ├── runtime.test.js — uploads, database and bot feature suite
867
- │ ├── whatsapp.test.js — WhatsApp bot runtime tests
868
- │ └── acceptance.test.js — boots the example projects over live HTTP
869
- │
870
- ├── docs/
871
- │ ├── PLAINSCRIPT-SPEC.md
872
- │ └── index.html
873
- │
874
- ├── editors/
875
- │ └── mt-manager/
876
- │ └── plainscript.mtsx — MT Manager syntax highlighting
877
- │
878
- ├── package.json
879
- └── README.md
880
- ```