plainscript-lang 1.0.3-beta → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +97 -120
  2. package/compiler/bundler.js +83 -12
  3. package/compiler/cli.js +62 -11
  4. package/compiler/dependency-detector.js +11 -0
  5. package/compiler/generator.js +280 -15
  6. package/compiler/lexer.js +2 -0
  7. package/compiler/parser.js +410 -28
  8. package/compiler/sourcemap.js +142 -0
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +17 -15
  11. package/docs/PLAINSCRIPT-SPEC.md +41 -39
  12. package/docs/index.html +60 -33
  13. package/docs/website/script.js +168 -19
  14. package/docs/website/style.css +187 -41
  15. package/examples/ai-providers.pln +1 -1
  16. package/examples/arrays.pln +1 -1
  17. package/examples/async-errors.pln +1 -1
  18. package/examples/auth-api.pln +1 -1
  19. package/examples/auth-sessions.pln +1 -1
  20. package/examples/basics.pln +1 -1
  21. package/examples/bots.pln +1 -1
  22. package/examples/cache-and-jobs.pln +1 -1
  23. package/examples/cache-schedule.pln +1 -1
  24. package/examples/collections.pln +1 -1
  25. package/examples/concurrency.pln +1 -1
  26. package/examples/conditions.pln +1 -1
  27. package/examples/database.pln +1 -1
  28. package/examples/day2.pln +1 -1
  29. package/examples/day3.pln +1 -1
  30. package/examples/deployment.pln +1 -1
  31. package/examples/email-send.pln +1 -1
  32. package/examples/error-handling.pln +1 -1
  33. package/examples/expressions.pln +1 -1
  34. package/examples/file-uploads.pln +1 -1
  35. package/examples/files-and-config.pln +1 -1
  36. package/examples/files.pln +1 -1
  37. package/examples/football-backend/app.pln +1 -1
  38. package/examples/functions.pln +1 -1
  39. package/examples/hello.pln +1 -1
  40. package/examples/http-client.pln +1 -1
  41. package/examples/http.pln +1 -1
  42. package/examples/id-verification/app.pln +1 -1
  43. package/examples/json.pln +1 -1
  44. package/examples/loops.pln +1 -1
  45. package/examples/modules/app.pln +1 -1
  46. package/examples/modules/main.pln +1 -1
  47. package/examples/modules/math.pln +1 -1
  48. package/examples/mongo.pln +33 -0
  49. package/examples/objects.pln +1 -1
  50. package/examples/ocr.pln +1 -1
  51. package/examples/packages.pln +1 -1
  52. package/examples/record-kinds.pln +1 -1
  53. package/examples/records.pln +1 -1
  54. package/examples/rest-api-fetch.pln +1 -1
  55. package/examples/rest-api.pln +1 -1
  56. package/examples/scheduled-tasks.pln +1 -1
  57. package/examples/search-and-filter.pln +1 -1
  58. package/examples/server.pln +1 -1
  59. package/examples/sessions-and-cookies.pln +1 -1
  60. package/examples/sqlite.pln +1 -1
  61. package/examples/start.pln +1 -1
  62. package/examples/stdlib.pln +1 -1
  63. package/examples/string-verbs.pln +16 -0
  64. package/examples/telegram-ai-bot.pln +1 -1
  65. package/examples/telegram-bot.pln +1 -1
  66. package/examples/testing.pln +1 -1
  67. package/examples/web-api.pln +1 -1
  68. package/examples/web-app.pln +1 -1
  69. package/examples/websocket-server.pln +1 -1
  70. package/examples/websocket.pln +1 -1
  71. package/examples/whatsapp-bot/pairing.pln +1 -1
  72. package/examples/whatsapp-bot/qr.pln +1 -1
  73. package/package.json +3 -2
package/README.md CHANGED
@@ -1,12 +1,10 @@
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)](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`.
8
4
 
9
- ## Quick start
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.
6
+
7
+ ## Get started in 60 seconds
10
8
 
11
9
  ```bash
12
10
  npx plainscript new hello
@@ -17,34 +15,31 @@ npm run build
17
15
  npm start
18
16
  ```
19
17
 
20
- Run a single source file without writing build output:
18
+ Run a single file without saving any build output:
21
19
 
22
20
  ```bash
23
21
  npx plainscript run examples/basics.pln
24
22
  ```
25
23
 
26
- ## CLI
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
41
- ```
42
-
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.
24
+ ## Commands
46
25
 
47
- ## Core syntax
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 |
39
+
40
+ Run `plainscript check` after every change — it validates your code and catches errors early.
41
+
42
+ ## Syntax
48
43
 
49
44
  ### Variables and output
50
45
 
@@ -56,8 +51,7 @@ show greeting
56
51
  count becomes count + 1
57
52
  ```
58
53
 
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.
54
+ `remember name as value` declares a variable. `show`, `print`, and `display` all print output.
61
55
 
62
56
  ### Conditions
63
57
 
@@ -69,9 +63,7 @@ otherwise
69
63
  done
70
64
  ```
71
65
 
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`.
66
+ You can use `is`, `more than`, `fewer than`, `contains`, `starts with`, `ends with`, `and`, `or`, and `not`.
75
67
 
76
68
  ### Lists and records
77
69
 
@@ -83,8 +75,7 @@ remember user as record with name "Ada" and active true done
83
75
  show user.name
84
76
  ```
85
77
 
86
- Inline JavaScript array and object literals are also supported:
87
- `[1, 2, 3]` and `{name: "Ada", active: true}`.
78
+ You can also use plain JavaScript arrays and objects: `[1, 2, 3]` and `{name: "Ada"}`.
88
79
 
89
80
  ### Functions
90
81
 
@@ -96,17 +87,12 @@ done
96
87
  show add(2, 3)
97
88
  ```
98
89
 
99
- Defaults use `as` in the parameter list:
100
-
101
90
  ```plainscript
102
91
  make greet(name as "friend")
103
92
  give `Hello, ${name}`
104
93
  done
105
94
  ```
106
95
 
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.
109
-
110
96
  ### Loops
111
97
 
112
98
  ```plainscript
@@ -134,11 +120,46 @@ done
134
120
  remember player as create a Player with name "Ada" and goals 4
135
121
  ```
136
122
 
137
- ## AI providers and Telegram
123
+ ### Compound data structures
138
124
 
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.
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
130
+
131
+ // Sets
132
+ remember tags as set with "admin", "editor", "user" done
133
+ remember newTags as union of tags and (set with "moderator" done)
134
+
135
+ // Tuples
136
+ remember point as tuple with 10, 20, 30 done
137
+ unpack point into x, y, z
138
+ ```
139
+
140
+ ### Imports and exports
141
+
142
+ ```plainscript
143
+ // Import specific functions
144
+ bring circleArea and squareArea from "./math.pln"
145
+
146
+ // Import with a namespace
147
+ bring all from "./math.pln" as math
148
+ show math.circleArea(5)
149
+
150
+ // Import an npm package
151
+ bring axios from "axios"
152
+
153
+ // Use @/ to import from src/
154
+ bring button from "@/components/button.pln"
155
+
156
+ // Re-export everything from another file
157
+ export all from "./submodule.pln"
158
+ ```
159
+
160
+ ## AI providers
161
+
162
+ PlainScript can call AI models from any provider that supports the OpenAI API format. Your API keys stay in environment variables.
142
163
 
143
164
  ```plainscript
144
165
  remember answer as chat("llama-3.3-70b-versatile", "Summarize PlainScript", {
@@ -149,13 +170,9 @@ remember answer as chat("llama-3.3-70b-versatile", "Summarize PlainScript", {
149
170
  show answer
150
171
  ```
151
172
 
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`.
173
+ Supported providers: `groq`, `openai`, `openrouter`, `together`, `fireworks`, `deepseek`. You can also point to any custom OpenAI-compatible endpoint with `base`, `key`, and `headers`.
156
174
 
157
- Telegram supports fixed replies, command arguments, regex captures, callbacks,
158
- inline buttons, and the complete raw Bot API:
175
+ ## Telegram bots
159
176
 
160
177
  ```plainscript
161
178
  bot env("TELEGRAM_BOT_TOKEN")
@@ -169,14 +186,11 @@ done
169
186
  start telegram bot
170
187
  ```
171
188
 
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.
189
+ Inside a handler, `message`, `args`, `matches`, `chat`, and `chatId` give you access to the current update.
176
190
 
177
191
  ## Standard library
178
192
 
179
- No import is needed for built-ins such as:
193
+ No imports needed — these work out of the box:
180
194
 
181
195
  ```plainscript
182
196
  remember encoded as jsonEncode(user)
@@ -188,13 +202,9 @@ remember currentTime as time()
188
202
  remember identifier as uuid()
189
203
  ```
190
204
 
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.
205
+ Other built-in helpers cover strings, collections, file paths, HTTP, caching, environment variables, and crypto.
196
206
 
197
- ## Web applications
207
+ ## Web apps
198
208
 
199
209
  ```plainscript
200
210
  web app
@@ -216,14 +226,7 @@ done
216
226
  start 3000
217
227
  ```
218
228
 
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.
223
-
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"`.
229
+ Routes support `get`, `post`, `put`, `patch`, and `delete`. Read request data with `body of request`, `param("id")`, `query("page")`, and `header("x-name")`.
227
230
 
228
231
  ## HTTP client
229
232
 
@@ -233,7 +236,7 @@ remember created as post "https://example.com/data" with {name: "Ada"} headers {
233
236
  show response.status
234
237
  ```
235
238
 
236
- ## SQLite and SQL
239
+ ## SQLite
237
240
 
238
241
  ```plainscript
239
242
  database "app.db" using "wasm"
@@ -252,9 +255,7 @@ remember people as query
252
255
  done
253
256
  ```
254
257
 
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.
258
+ Use `using "native"` for a Node.js SQLite backend, or `using "wasm"` for in-memory. SQL placeholders like `{name}` bind to PlainScript variables.
258
259
 
259
260
  ## Errors, async, and concurrency
260
261
 
@@ -271,20 +272,7 @@ retry 3 times every 1 second
271
272
  done
272
273
  ```
273
274
 
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.
277
-
278
- ## Modules and packages
279
-
280
- ```plainscript
281
- import { circleArea } from "./math.pln"
282
- export circleArea
283
- use express
284
- ```
285
-
286
- Imports are bundled in dependency order. `use` declares an npm dependency that
287
- the CLI can install. Each compiled entry is standalone.
275
+ Run promises in parallel with `allOf()`, `anyOf()`, and `settledOf()`. Schedule recurring work with `every 5 minutes ... done`.
288
276
 
289
277
  ## Testing
290
278
 
@@ -294,45 +282,34 @@ test "addition works"
294
282
  done
295
283
  ```
296
284
 
297
- Assertions support `equals`, `is`, `contains`, and `raises`.
285
+ Assertions: `equals`, `is`, `contains`, and `raises`.
298
286
 
299
- ## Bots, OCR, WebSockets, and cache
287
+ ## Examples
300
288
 
301
- The feature examples in `examples/` are the maintained reference programs:
289
+ The `examples/` folder has working code for every feature:
302
290
 
303
- | Capability | Example |
291
+ | Topic | Files |
304
292
  | --- | --- |
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/` |
316
-
317
- ## Verification
318
-
319
- ```bash
320
- find examples tests/fixtures -name '*.pln' -print0 |
321
- xargs -0 -n1 plainscript check
322
- npm test
323
- ```
324
-
325
- Circular-import fixtures are intentionally rejected by the compiler's
326
- dependency checks. All maintained runnable examples must pass `plainscript
327
- check`.
328
-
329
- ## Project layout
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/` |
305
+
306
+ ## Project structure
330
307
 
331
308
  ```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
309
+ compiler/ compiler, parser, and CLI
310
+ examples/ feature demos and examples
311
+ tests/ test suite
312
+ docs/ website and docs
336
313
  plainscript-vscode/ VS Code extension
337
- editors/mt-manager/ TextMate-compatible grammar
314
+ editors/mt-manager/ TextMate grammar
338
315
  ```
@@ -7,11 +7,55 @@ const { tokenize } = require('./lexer');
7
7
  const { parse } = require('./parser');
8
8
  const { generate, createGenerationContext, wrapAsync } = require('./generator');
9
9
 
10
- // Returns the import paths declared at the top level of an AST.
10
+ function isLocalImportPath(p) {
11
+ if (!p) return false;
12
+ return p.startsWith('.') || p.startsWith('/') || p.startsWith('\\') || p.startsWith('@/') || p.endsWith('.pln');
13
+ }
14
+
15
+ function resolveImportPath(dir, importPath) {
16
+ let base;
17
+ if (importPath.startsWith('@/')) {
18
+ const srcDir = fs.existsSync(path.resolve(process.cwd(), 'src'))
19
+ ? path.resolve(process.cwd(), 'src')
20
+ : process.cwd();
21
+ base = path.resolve(srcDir, importPath.slice(2));
22
+ } else {
23
+ base = path.resolve(dir, importPath);
24
+ }
25
+
26
+ // 1. Direct match (e.g. "./math.pln")
27
+ if (fs.existsSync(base) && fs.statSync(base).isFile()) {
28
+ return base;
29
+ }
30
+ // 2. Implicit .pln extension (e.g. "./math" -> "./math.pln")
31
+ if (fs.existsSync(`${base}.pln`) && fs.statSync(`${base}.pln`).isFile()) {
32
+ return `${base}.pln`;
33
+ }
34
+ // 3. Directory index resolution (e.g. "./utils" -> "./utils/index.pln" or "./utils/app.pln")
35
+ if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {
36
+ const indexPath = path.join(base, 'index.pln');
37
+ if (fs.existsSync(indexPath) && fs.statSync(indexPath).isFile()) {
38
+ return indexPath;
39
+ }
40
+ const appPath = path.join(base, 'app.pln');
41
+ if (fs.existsSync(appPath) && fs.statSync(appPath).isFile()) {
42
+ return appPath;
43
+ }
44
+ }
45
+ return base;
46
+ }
47
+
48
+ // Returns the local file import and re-export paths declared at the top level of an AST.
11
49
  function getImports(ast) {
12
- return ast.body
13
- .filter(node => node.type === 'ImportStatement')
14
- .map(node => node.path);
50
+ const paths = [];
51
+ for (const node of ast.body) {
52
+ if (node.type === 'ImportStatement' && node.path && isLocalImportPath(node.path)) {
53
+ paths.push(node.path);
54
+ } else if (node.type === 'ExportStatement' && node.fromPath && isLocalImportPath(node.fromPath)) {
55
+ paths.push(node.fromPath);
56
+ }
57
+ }
58
+ return paths;
15
59
  }
16
60
 
17
61
  // Resolves all dependencies of entryPath using DFS topological order.
@@ -45,8 +89,8 @@ function resolveDependencies(entryPath) {
45
89
  }
46
90
 
47
91
  // Parse the file to discover its own imports.
48
- // Annotate any tokenise/parse error with the filename so callers see
49
- // "file.pln — Line N, Column N: …" rather than a bare positional message.
92
+ // Annotate any tokenise/parse error with the filename so callers see
93
+ // "file.pln — Line N, Column N: …" rather than a bare positional message.
50
94
  const source = fs.readFileSync(absPath, 'utf8');
51
95
  let tokens, ast;
52
96
  try {
@@ -61,7 +105,7 @@ function resolveDependencies(entryPath) {
61
105
  const newStack = [...stack, absPath];
62
106
  for (const importPath of getImports(ast)) {
63
107
  const dir = path.dirname(absPath);
64
- const resolvedAbs = path.resolve(dir, importPath);
108
+ const resolvedAbs = resolveImportPath(dir, importPath);
65
109
  visit(resolvedAbs, newStack);
66
110
  }
67
111
 
@@ -75,12 +119,39 @@ function resolveDependencies(entryPath) {
75
119
  }
76
120
 
77
121
  // Compile all files in dependency order into one JavaScript string.
78
- function bundle(entryPath) {
122
+ function bundle(entryPath, options = {}) {
79
123
  const files = resolveDependencies(entryPath);
80
- const context = createGenerationContext();
81
- const parts = files.map(({ ast }) => generate(ast, context)).filter(js => js.trim() !== '');
82
- const js = parts.join('\n');
83
- return context.needsAsync ? wrapAsync(js) : js;
124
+ const context = createGenerationContext(options);
125
+ const parts = files.map(({ absPath, ast }) => {
126
+ const relPath = path.relative(process.cwd(), absPath).replace(/\\/g, '/') || path.basename(absPath);
127
+ context.sourceFile = relPath;
128
+ if (context.sourceMapBuilder) {
129
+ try {
130
+ const content = fs.readFileSync(absPath, 'utf8');
131
+ context.sourceMapBuilder.addSource(relPath, content);
132
+ } catch (_) { /* ignore missing content */ }
133
+ }
134
+ const res = generate(ast, context);
135
+ return typeof res === 'string' ? res : (res && res.code ? res.code : '');
136
+ }).filter(js => js && js.trim() !== '');
137
+ let js = parts.join('\n');
138
+ if (context.needsAsync) {
139
+ js = wrapAsync(js);
140
+ if (context.sourceMapBuilder) {
141
+ for (const m of context.sourceMapBuilder.mappings) {
142
+ m.generatedLine += 1;
143
+ }
144
+ }
145
+ }
146
+
147
+ if (options.sourceMap && context.sourceMapBuilder) {
148
+ return {
149
+ code: js,
150
+ map: context.sourceMapBuilder,
151
+ mapObject: context.sourceMapBuilder.toJSON(),
152
+ };
153
+ }
154
+ return js;
84
155
  }
85
156
 
86
157
  module.exports = { bundle, resolveDependencies };
package/compiler/cli.js CHANGED
@@ -364,13 +364,13 @@ function ensureDependencies(files, install = true) {
364
364
  // Deterministic only: the lexer/parser/generator pipeline is the single
365
365
  // authoritative compiler. Unsupported syntax produces a precise compiler
366
366
  // error — there is no second compilation path (v2.1.1).
367
- function compile(filePath) {
367
+ function compile(filePath, options = {}) {
368
368
  const absPath = path.resolve(filePath);
369
369
  if (!fs.existsSync(absPath)) {
370
370
  console.error(`File not found: ${filePath}`);
371
371
  process.exit(1);
372
372
  }
373
- const generationContext = createGenerationContext();
373
+ const generationContext = createGenerationContext(options);
374
374
 
375
375
  let files;
376
376
  stage('Resolving imports', () => {
@@ -378,9 +378,38 @@ function compile(filePath) {
378
378
  });
379
379
  stage('Building dependency graph', () => files);
380
380
  stage('Checking runtime dependencies', () => ensureDependencies(files, true));
381
- const js = stage('Generating JavaScript', () =>
382
- files.map(({ ast }) => generate(ast, generationContext)).filter(s => s.trim()).join('\n'));
383
- return generationContext.needsAsync ? wrapAsync(js) : js;
381
+ const parts = stage('Generating JavaScript', () =>
382
+ files.map(({ absPath: fileAbs, ast }) => {
383
+ const relPath = path.relative(process.cwd(), fileAbs).replace(/\\/g, '/') || path.basename(fileAbs);
384
+ generationContext.sourceFile = relPath;
385
+ if (generationContext.sourceMapBuilder) {
386
+ try {
387
+ const content = fs.readFileSync(fileAbs, 'utf8');
388
+ generationContext.sourceMapBuilder.addSource(relPath, content);
389
+ } catch (_) {}
390
+ }
391
+ const res = generate(ast, generationContext);
392
+ return typeof res === 'string' ? res : (res && res.code ? res.code : '');
393
+ }).filter(s => s && s.trim()));
394
+ let js = parts.join('\n');
395
+ if (generationContext.needsAsync) {
396
+ js = wrapAsync(js);
397
+ if (generationContext.sourceMapBuilder) {
398
+ for (const m of generationContext.sourceMapBuilder.mappings) {
399
+ m.generatedLine += 1;
400
+ }
401
+ }
402
+ }
403
+
404
+ if (options.sourceMap && generationContext.sourceMapBuilder) {
405
+ return {
406
+ code: js,
407
+ map: generationContext.sourceMapBuilder,
408
+ mapObject: generationContext.sourceMapBuilder.toJSON(),
409
+ };
410
+ }
411
+
412
+ return js;
384
413
  }
385
414
 
386
415
  // ── Commands ─────────────────────────────────────────────────────────────────
@@ -408,7 +437,14 @@ async function cmdRun(filePath, extraArgs = []) {
408
437
  console.error('Usage: plainscript run <file.pln>');
409
438
  process.exit(1);
410
439
  }
411
- const js = compile(filePath);
440
+ const isSourcemap = process.argv.includes('--sourcemap') || process.argv.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
441
+ let js;
442
+ if (isSourcemap) {
443
+ const res = compile(filePath, { sourceMap: true, outputFile: 'out.js' });
444
+ js = res.code + '\n' + res.map.toInlineDataUrl() + '\n';
445
+ } else {
446
+ js = compile(filePath);
447
+ }
412
448
  console.log('');
413
449
  // Execute from the entry file's directory so relative assets and CWD-based
414
450
  // behaviour match a direct `node` invocation.
@@ -417,8 +453,9 @@ async function cmdRun(filePath, extraArgs = []) {
417
453
  const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'plainscript-run-'));
418
454
  const tmpFile = path.join(tmpDir, 'out.js');
419
455
  fs.writeFileSync(tmpFile, js, 'utf8');
456
+ const nodeFlags = isSourcemap ? ['--enable-source-maps'] : [];
420
457
  try {
421
- execFileSync(process.execPath, [tmpFile, ...extraArgs], {
458
+ execFileSync(process.execPath, [...nodeFlags, tmpFile, ...extraArgs], {
422
459
  stdio: 'inherit',
423
460
  cwd: entryDir,
424
461
  env: { ...process.env, NODE_PATH: searchPaths.join(path.delimiter) },
@@ -434,19 +471,33 @@ async function cmdRun(filePath, extraArgs = []) {
434
471
 
435
472
  // Compile one entry and write it to outDir with its source name preserved,
436
473
  // relative to the source root when the file lives inside it.
437
- function buildOne(filePath, srcDir, outDir) {
474
+ function buildOne(filePath, srcDir, outDir, options = {}) {
438
475
  const absFile = path.resolve(filePath);
439
476
  if (!fs.existsSync(absFile)) {
440
477
  console.error(`File not found: ${filePath}`);
441
478
  process.exit(1);
442
479
  }
443
- const js = compile(absFile);
444
480
  const srcRoot = path.resolve(srcDir);
445
481
  let rel = path.relative(srcRoot, absFile).replace(/\.pln$/, '.js');
446
482
  if (rel.startsWith('..') || path.isAbsolute(rel)) rel = path.basename(absFile).replace(/\.pln$/, '.js');
447
483
  const outPath = path.join(path.resolve(outDir), rel);
484
+
485
+ const isSourcemap = options.sourceMap || process.argv.includes('--sourcemap') || process.argv.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
486
+
487
+ let code, mapObject;
488
+ if (isSourcemap) {
489
+ const res = compile(absFile, { sourceMap: true, outputFile: path.basename(outPath) });
490
+ code = res.code + `\n//# sourceMappingURL=${path.basename(outPath)}.map\n`;
491
+ mapObject = res.mapObject;
492
+ } else {
493
+ code = compile(absFile);
494
+ }
495
+
448
496
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
449
- fs.writeFileSync(outPath, js, 'utf8');
497
+ fs.writeFileSync(outPath, code, 'utf8');
498
+ if (mapObject) {
499
+ fs.writeFileSync(outPath + '.map', JSON.stringify(mapObject, null, 2), 'utf8');
500
+ }
450
501
  return path.relative(process.cwd(), outPath) || outPath;
451
502
  }
452
503
 
@@ -537,7 +588,7 @@ done
537
588
  route get "/api/status"
538
589
  reply json
539
590
  status is "ok"
540
- version is "1.0.3-beta"
591
+ version is "1.0.3"
541
592
  done
542
593
  done
543
594
 
@@ -33,6 +33,8 @@ const PACKAGE_MAP = Object.freeze({
33
33
  // through qrcode-terminal. Neither package ever appears in PlainScript source.
34
34
  whatsapp: '@whiskeysockets/baileys',
35
35
  'wa-qrcode': 'qrcode-terminal',
36
+ // v2.2.0 — MongoDB driver.
37
+ mongodb: 'mongodb',
36
38
  });
37
39
 
38
40
  const BUILTIN_MODULES = new Set(builtinModules);
@@ -66,6 +68,12 @@ function visit(node, onUse) {
66
68
 
67
69
  if (node.type === 'UseStatement') {
68
70
  onUse(node.module);
71
+ } else if (node.type === 'ImportStatement' && node.path) {
72
+ // Detect npm package dependencies imported via `bring ... from "pkg"` or `import ... from "pkg"`
73
+ const isLocalFile = node.path.startsWith('.') || node.path.startsWith('/') || node.path.startsWith('\\') || node.path.startsWith('@/') || node.path.endsWith('.pln');
74
+ if (!isLocalFile) {
75
+ onUse(node.path);
76
+ }
69
77
  } else if (node.type === 'WebAppStatement') {
70
78
  // The `web app` shorthand creates an Express application.
71
79
  onUse('express');
@@ -87,6 +95,9 @@ function visit(node, onUse) {
87
95
  } else if (node.type === 'PostgresStatement') {
88
96
  // v2.1.0 — `postgres "<url>"` uses node-postgres under the hood.
89
97
  onUse('postgres');
98
+ } else if (node.type === 'MongoStatement') {
99
+ // v2.2.0 — `mongo "<uri>"` uses mongodb driver under the hood.
100
+ onUse('mongodb');
90
101
  } else if (node.type === 'OcrStatement') {
91
102
  // v2.0.1 — `ocr "<image>" as <variable>` uses tesseract.js under the hood.
92
103
  onUse('ocr');