plainscript-lang 1.0.3 → 1.0.36

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