plainscript-lang 1.1.0 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,7 +131,7 @@ done
131
131
  </tr>
132
132
  </table>
133
133
 
134
- **Current version:** `v1.1.0` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
134
+ **Current version:** `v1.1.5` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
135
135
 
136
136
  ---
137
137
 
@@ -261,7 +261,7 @@ For projects that need custom output or source directories, add a `plainscript.c
261
261
  "build": "plainscript build",
262
262
  "prepare": "plainscript build"
263
263
  },
264
- "devDependencies": { "plainscript-lang": "^1.1.0" }
264
+ "devDependencies": { "plainscript-lang": "^1.1.5" }
265
265
  }
266
266
  ```
267
267
 
@@ -365,9 +365,11 @@ All comparison operators:
365
365
  | `is not` | `!==` |
366
366
  | `different from` | `!==` |
367
367
  | `is greater than` / `is above` | `>` |
368
- | `more than` | `>` |
368
+ | `more than` / `is more than` | `>` |
369
369
  | `is less than` / `is below` | `<` |
370
- | `fewer than` | `<` |
370
+ | `fewer than` / `is fewer than` | `<` |
371
+ | `greater than or equal to` / `is more than or equal to` | `>=` |
372
+ | `less than or equal to` | `<=` |
371
373
  | `is at least` | `>=` |
372
374
  | `is at most` | `<=` |
373
375
  | `is empty` | `.length === 0` |
@@ -419,7 +421,7 @@ PlainScript supports contextual `type` declarations for records and typed
419
421
  function parameters. The compiler records the contract in the AST and emitted
420
422
  programs validate typed arguments at runtime with clear field-level errors.
421
423
  Primitive types are `number`, `text`, `boolean`, `object`, and `null`; contracts
422
- also support `optional`, `list of`, `dictionary of`, and `or` unions.
424
+ also support `optional`, `list of`, `dictionary of`, `set of`, `map of K to V`, fixed-size `tuple of A, B`, and `or` unions. Named aliases are substituted across assignments, returns, and local imports.
423
425
 
424
426
  ```plainscript
425
427
  type User
@@ -446,11 +448,66 @@ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
446
448
  ```
447
449
 
448
450
  List elements, dictionary values, and nested record fields are checked
449
- recursively. Optional and union element types are supported. The static checker
450
- reports unknown fields, missing required fields, incompatible literal values,
451
- unknown contract names, arity errors, invalid assignments, unsafe optional
452
- member access, and invalid member access to editor tooling. Whole-program
453
- inference and exhaustiveness checking remain future work.
451
+ recursively. Optional and union element types are supported. The v1.1.5
452
+ checker also propagates known expression results through canonical standard
453
+ library calls and common text/list methods:
454
+
455
+ ```plainscript
456
+ make normalized() returns text
457
+ give " Ada ".trim().toLowerCase()
458
+ done
459
+
460
+ make words() returns list of text
461
+ give "ada,grace".split(",")
462
+ done
463
+ ```
464
+
465
+ Known math helpers, text conversions, collection operations, and member methods
466
+ now contribute their return types to argument and return-contract checking.
467
+ Unknown JavaScript/npm calls remain `any` rather than being guessed. The static
468
+ checker reports unknown fields, missing required fields, incompatible literal
469
+ values, unknown contract names, arity errors, invalid assignments, unsafe
470
+ optional member access, and invalid member access to editor tooling.
471
+ ### Generic functions and aliases
472
+
473
+ Generic function parameters use angle brackets. The checker infers a concrete
474
+ type from each call and validates the result; generic parameters are erased
475
+ from runtime assertions because JavaScript cannot observe them directly.
476
+
477
+ ```plainscript
478
+ type UserId is number
479
+
480
+ make id<T>(value as T) returns T
481
+ give value
482
+ done
483
+
484
+ let userId as UserId is id(42)
485
+ show userId
486
+ ```
487
+
488
+ Aliases are checked wherever the aliased type is used, including across local
489
+ imports. Runtime checks still validate the underlying concrete type.
490
+
491
+ The checker narrows nullable values after guards such as `if value is not null`
492
+ and `if value is null`; optional member access remains available when a value
493
+ has not been narrowed. Structural pattern exhaustiveness is not yet enforced.
494
+
495
+ ### Cancellation and disposal
496
+
497
+ The standard library provides explicit cancellation tokens and deterministic
498
+ cleanup helpers:
499
+
500
+ ```plainscript
501
+ let token is cancellationToken()
502
+ remember ignored as cancel(token)
503
+ if isCancelled(token)
504
+ show "cancelled"
505
+ done
506
+ ```
507
+
508
+ `dispose(resource)` can be used by a `using` scope to clean up resources. These
509
+ semantics are cooperative: an operation must inspect its token or call a
510
+ standard-library operation that accepts one.
454
511
 
455
512
  ### Language-server tooling
456
513
 
@@ -770,7 +827,7 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
770
827
  | Streams | `writeLine`, `appendLine` |
771
828
  | Collections | `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet` |
772
829
  | Dynamic modules | `loadModule("./m")` |
773
- | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"`; run files with `plainscript test` |
830
+ | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check object has field "name"`, and `check <expr> raises "msg"`; run files with `plainscript test` |
774
831
  | Exports | `export <name>` |
775
832
 
776
833
  </details>
@@ -834,6 +891,28 @@ database "app.db" using "wasm" // hard requirement: sql.js
834
891
 
835
892
  The WebAssembly engine persists the whole database to disk after every write, so data survives restarts either way.
836
893
 
894
+ SQL blocks use bound PlainScript value placeholders. `{name}` or
895
+ `{imageHash(image)}` becomes a prepared statement parameter; the resulting value
896
+ is never concatenated into SQL text:
897
+
898
+ ```plainscript
899
+ remember email as request.body.email
900
+ remember rows as query
901
+ SELECT receipt_id FROM receipts WHERE email = {email}
902
+ done
903
+ ```
904
+
905
+ Placeholders are parsed as PlainScript expressions, while raw statement text or
906
+ malformed expressions are rejected at compile time. For complex expressions,
907
+ bind the expression first:
908
+
909
+ ```plainscript
910
+ remember receiptHash as imageHash(image)
911
+ remember rows as query
912
+ SELECT receipt_id FROM receipts WHERE hash = {receiptHash}
913
+ done
914
+ ```
915
+
837
916
  ### HTTP Client
838
917
 
839
918
  ```plainscript
@@ -1359,6 +1438,21 @@ export circleArea
1359
1438
 
1360
1439
  Imports are bundled per entry: `plainscript build` gives every source file its own standalone output under `dist/`, with imported code inlined. Functions, lambdas, records, and modules together are how you build your own vocabulary on top of the core verbs - a new reader puzzle (`validate(body, fields)`) is a one-line call, not a loop.
1361
1440
 
1441
+ ### npm and JavaScript imports
1442
+
1443
+ Named package exports may be given an explicit PlainScript local name:
1444
+
1445
+ ```plainscript
1446
+ import { createHash as hash, randomUUID } from "crypto"
1447
+ show hash
1448
+ ```
1449
+
1450
+ The compiler emits a CommonJS `require` followed by destructuring, so
1451
+ `createHash as hash` becomes the JavaScript binding `{ createHash: hash }`.
1452
+ Unaliased named imports retain their exported name. The same brace syntax is
1453
+ accepted for local PlainScript modules; aliased names become local bindings in
1454
+ the bundled output.
1455
+
1362
1456
  ---
1363
1457
 
1364
1458
  ## Express Integration
@@ -128,6 +128,32 @@ function getExportNames(ast) {
128
128
  return names;
129
129
  }
130
130
 
131
+ function getModuleSurface(ast) {
132
+ const explicit = getExportNames(ast);
133
+ if (ast.body.some(node => node.type === 'ExportStatement')) return new Set(explicit);
134
+ return new Set(ast.body
135
+ .filter(node => ['FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(node.type) && node.name)
136
+ .map(node => node.name));
137
+ }
138
+
139
+ function validateImportSurfaces(files) {
140
+ const astByAbs = new Map(files.map(file => [file.absPath, file.ast]));
141
+ for (const { absPath, ast } of files) {
142
+ for (const node of ast.body) {
143
+ if (node.type !== 'ImportStatement' || !node.path || !isLocalImportPath(node.path) || node.namespace) continue;
144
+ const dependency = astByAbs.get(resolveImportPath(path.dirname(absPath), node.path));
145
+ if (!dependency) continue;
146
+ const surface = getModuleSurface(dependency);
147
+ const imported = node.namedImports || (node.names || []).map(name => ({ imported: name, local: name }));
148
+ for (const item of imported) {
149
+ if (!surface.has(item.imported)) {
150
+ throw new Error(`Module "${node.path}" does not export "${item.imported}".\n\nExport it from the module or remove it from the import.`);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ }
156
+
131
157
  // Builds the export surface map for a resolved dependency graph:
132
158
  // local import path (as written) -> exported names of that module. Used by
133
159
  // namespace imports ("bring all from X as ns") which need the export surface
@@ -146,7 +172,7 @@ function buildSurfaces(files) {
146
172
  // Union of explicit exports plus auto-exported function declarations
147
173
  const explicit = getExportNames(depAst);
148
174
  const funcs = depAst.body
149
- .filter(n => n.type === 'FunctionDeclaration' && n.name)
175
+ .filter(n => ['FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(n.type) && n.name)
150
176
  .map(n => n.name);
151
177
  const hasExplicit = depAst.body.some(n => n.type === 'ExportStatement');
152
178
  const surface = hasExplicit ? explicit : [...new Set([...explicit, ...funcs])];
@@ -186,6 +212,7 @@ function buildSurfaces(files) {
186
212
  // bundled programs behave identically no matter which command produced them.
187
213
  function generateBundle(entryPath, options = {}) {
188
214
  const files = resolveDependencies(entryPath);
215
+ validateImportSurfaces(files);
189
216
  const context = createGenerationContext(options);
190
217
  context.bundled = true;
191
218
  context.importSurfaces = buildSurfaces(files);
@@ -229,4 +256,4 @@ function bundle(entryPath, options = {}) {
229
256
  return js;
230
257
  }
231
258
 
232
- module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies };
259
+ module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies, validateImportSurfaces };
package/compiler/cli.js CHANGED
@@ -401,6 +401,7 @@ function compile(filePath, options = {}) {
401
401
  stage('Resolving imports', () => {
402
402
  files = resolveDependencies(absPath);
403
403
  });
404
+ stage('Checking module graph', () => checkResolvedGraph(files));
404
405
  stage('Building dependency graph', () => files);
405
406
  stage('Checking runtime dependencies', () => ensureDependencies(files, true));
406
407
  // Shared bundle pipeline: one context across the whole dependency graph so
@@ -494,6 +495,31 @@ function compile(filePath, options = {}) {
494
495
  return js;
495
496
  }
496
497
 
498
+ function checkResolvedGraph(files) {
499
+ const declarations = new Map();
500
+ for (const file of files) {
501
+ const sourceFile = path.relative(process.cwd(), file.absPath) || file.absPath;
502
+ for (const node of file.ast.body || []) {
503
+ if (!node.name || !['RememberStatement', 'FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(node.type)) continue;
504
+ const owners = declarations.get(node.name) || [];
505
+ owners.push(sourceFile);
506
+ declarations.set(node.name, owners);
507
+ node.sourceFile = sourceFile;
508
+ }
509
+ }
510
+ const collisions = [...declarations.entries()].filter(([, owners]) => new Set(owners).size > 1);
511
+ if (collisions.length) {
512
+ throw new Error(`Module graph contains colliding top-level declarations:\n${collisions.map(([name, owners]) => ` ${name}: ${owners.join(', ')}`).join('\n')}\n\nRename the declarations or import them through an isolated module boundary.`);
513
+ }
514
+ const result = checkTypes({ type: 'Program', body: files.flatMap(file => file.ast.body || []) });
515
+ if (result.diagnostics.length) {
516
+ const details = result.diagnostics.map(item =>
517
+ `${item.file || '<source>'}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
518
+ ).join('\n');
519
+ throw new Error(`Static type checking failed:\n${details}`);
520
+ }
521
+ }
522
+
497
523
  // ── Commands ─────────────────────────────────────────────────────────────────
498
524
 
499
525
  // Node resolves require(...) against the temp file's location, so a scratch
@@ -10,7 +10,7 @@
10
10
  const INDENT = ' '; // 4 spaces
11
11
 
12
12
  // Keywords whose line CLOSES a block (printed at depth - 1).
13
- const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'recover']);
13
+ const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'else', 'recover', 'finally']);
14
14
 
15
15
  // Patterns whose line OPENS a new block (next line indented).
16
16
  const INDENT_STARTERS = [
@@ -18,6 +18,7 @@ const INDENT_STARTERS = [
18
18
  /^to\s+\S+/, // to add a and b together ...
19
19
  /^if\s+/, // if ...
20
20
  /^otherwise\b/, // otherwise
21
+ /^else\b/, // else
21
22
  /^for\s+each\s+/, // for each ...
22
23
  /^for\s+every\s+/, // for every ... in ...
23
24
  /^for\s+index\s+/, // for index i from ... to ...
@@ -40,6 +41,7 @@ const INDENT_STARTERS = [
40
41
  /^transaction\s*$/, // transaction (v2.1 atomic DB block)
41
42
  /^try\s*$/, // try (v2.1.1 error handling)
42
43
  /^recover\b/, // recover [as name] (v2.1.1 error handling)
44
+ /^finally\s*$/, // finally (v2.1.1 error handling)
43
45
  /^retry\s+\d+\s+times\b/, // retry N times ... (v2.1.1 retries)
44
46
  /^every\s+\d+\s+(seconds?|minutes?|hours?|days?)\b/, // every 5 minutes (v2.1)
45
47
  /^every\s+N\s+(seconds?|minutes?|hours?|days?)\b/, // every N seconds (variable)
@@ -148,7 +150,8 @@ function format(source) {
148
150
  // (e.g. make, if, for each) when prior content exists.
149
151
  // Simple statements like remember/show/becomes are NOT block openers and
150
152
  // do NOT get a blank line inserted before them.
151
- if (depth === 0 && opensBlock(content) && output.length > 0) {
153
+ const isContinuation = ['else', 'finally', 'otherwise'].includes(firstWord);
154
+ if (depth === 0 && opensBlock(content) && !isContinuation && output.length > 0) {
152
155
  let lastNonEmpty = output.length - 1;
153
156
  while (lastNonEmpty >= 0 && output[lastNonEmpty] === '') lastNonEmpty--;
154
157