plainscript-lang 1.0.35 → 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 (87) hide show
  1. package/README.md +828 -209
  2. package/compiler/cli.js +68 -4
  3. package/compiler/generator.js +315 -0
  4. package/compiler/lexer.js +12 -0
  5. package/compiler/parser.js +144 -12
  6. package/compiler/version.js +1 -1
  7. package/docs/CAPABILITY_GAP_AUDIT.md +25 -4
  8. package/docs/GAME-PROMPT.md +915 -0
  9. package/docs/PLAINSCRIPT-SPEC.md +130 -1
  10. package/docs/index.html +21 -14
  11. package/docs/website/style.css +162 -195
  12. package/examples/ai-providers.pln +1 -1
  13. package/examples/arrays.pln +1 -1
  14. package/examples/async-errors.pln +1 -1
  15. package/examples/auth-api.pln +1 -1
  16. package/examples/auth-sessions.pln +1 -1
  17. package/examples/basics.pln +1 -1
  18. package/examples/bots.pln +1 -1
  19. package/examples/browser-interactive/README.md +29 -0
  20. package/examples/browser-interactive/public/index.html +83 -0
  21. package/examples/browser-interactive/public/interactive.js +27 -0
  22. package/examples/browser-interactive/src/interactive.pln +34 -0
  23. package/examples/cache-and-jobs.pln +1 -1
  24. package/examples/cache-schedule.pln +1 -1
  25. package/examples/canvas-game/README.md +34 -0
  26. package/examples/canvas-game/public/game.js +131 -0
  27. package/examples/canvas-game/public/index.html +48 -0
  28. package/examples/canvas-game/src/game.pln +139 -0
  29. package/examples/collections.pln +1 -1
  30. package/examples/concurrency.pln +1 -1
  31. package/examples/conditions.pln +1 -1
  32. package/examples/database.pln +1 -1
  33. package/examples/day2.pln +1 -1
  34. package/examples/day3.pln +1 -1
  35. package/examples/deployment.pln +1 -1
  36. package/examples/email-send.pln +1 -1
  37. package/examples/error-handling.pln +1 -1
  38. package/examples/expressions.pln +1 -1
  39. package/examples/file-uploads.pln +1 -1
  40. package/examples/files-and-config.pln +1 -1
  41. package/examples/files.pln +1 -1
  42. package/examples/football-backend/app.pln +1 -1
  43. package/examples/functions.pln +1 -1
  44. package/examples/hello.pln +1 -1
  45. package/examples/http-client.pln +1 -1
  46. package/examples/http.pln +1 -1
  47. package/examples/id-verification/app.pln +1 -1
  48. package/examples/javascript-library/README.md +54 -0
  49. package/examples/javascript-library/package-lock.json +21 -0
  50. package/examples/javascript-library/package.json +8 -0
  51. package/examples/javascript-library/public/config.json +4 -0
  52. package/examples/javascript-library/public/index.html +40 -0
  53. package/examples/javascript-library/src/interop.pln +53 -0
  54. package/examples/json.pln +1 -1
  55. package/examples/loops.pln +1 -1
  56. package/examples/modules/app.pln +1 -1
  57. package/examples/modules/main.pln +1 -1
  58. package/examples/modules/math.pln +1 -1
  59. package/examples/mongo.pln +1 -1
  60. package/examples/objects.pln +1 -1
  61. package/examples/ocr.pln +1 -1
  62. package/examples/packages.pln +1 -1
  63. package/examples/record-kinds.pln +1 -1
  64. package/examples/records.pln +1 -1
  65. package/examples/rest-api-fetch.pln +1 -1
  66. package/examples/rest-api.pln +1 -1
  67. package/examples/scheduled-tasks.pln +1 -1
  68. package/examples/search-and-filter.pln +1 -1
  69. package/examples/server.pln +1 -1
  70. package/examples/sessions-and-cookies.pln +1 -1
  71. package/examples/sqlite.pln +1 -1
  72. package/examples/start.pln +1 -1
  73. package/examples/stdlib.pln +1 -1
  74. package/examples/string-verbs.pln +1 -1
  75. package/examples/telegram-ai-bot.pln +1 -1
  76. package/examples/telegram-bot.pln +1 -1
  77. package/examples/testing.pln +1 -1
  78. package/examples/three-dimensional/README.md +51 -0
  79. package/examples/three-dimensional/public/index.html +33 -0
  80. package/examples/three-dimensional/src/scene.pln +34 -0
  81. package/examples/web-api.pln +1 -1
  82. package/examples/web-app.pln +1 -1
  83. package/examples/websocket-server.pln +1 -1
  84. package/examples/websocket.pln +1 -1
  85. package/examples/whatsapp-bot/pairing.pln +1 -1
  86. package/examples/whatsapp-bot/qr.pln +1 -1
  87. package/package.json +4 -3
package/compiler/cli.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // Usage:
5
5
  // plainscript run <file.pln> install missing dependencies, compile and execute
6
6
  // plainscript build [file.pln] compile src/ (or one file) to dist/, names preserved
7
+ // plainscript build <file.pln> -o <out.js> compile one file to a chosen output path
7
8
  // plainscript check [target] fully validate source(s): imports + generate + JS syntax
8
9
  // (target: a .pln file, a directory, or none to scan the project)
9
10
  // plainscript fmt <file.pln> format a PlainScript file in-place
@@ -61,6 +62,8 @@ ${section('START')}
61
62
  ${section('BUILD & CHECK')}
62
63
  plainscript build Compile every .pln under src/ into dist/
63
64
  plainscript build <file.pln> Compile one file into dist/ (name preserved)
65
+ plainscript build <file.pln> -o <out.js> Compile one file to an explicit path
66
+
64
67
  plainscript check [target] Validate imports + generate + JS output (no writes)
65
68
  target: a .pln file, a directory, or none = project scan
66
69
  --json emits deterministic machine-readable output
@@ -501,6 +504,38 @@ function buildOne(filePath, srcDir, outDir, options = {}) {
501
504
  return path.relative(process.cwd(), outPath) || outPath;
502
505
  }
503
506
 
507
+ // `plainscript build <file.pln> -o <out.js>` — compile one entry to an explicit
508
+ // output path (same compilation pipeline as buildOne, including source maps
509
+ // when requested). Valuable for browser payloads such as the v1.0.36
510
+ // requestAnimationFrame / addEventListener helpers, which are meant to run as
511
+ // a single script tag.
512
+ function writeOneFile(filePath, outputFile) {
513
+ const absFile = path.resolve(filePath);
514
+ if (!fs.existsSync(absFile)) {
515
+ console.error(`File not found: ${filePath}`);
516
+ process.exit(1);
517
+ }
518
+ const outPath = path.resolve(outputFile);
519
+
520
+ const isSourcemap = process.argv.includes('--sourcemap') || process.argv.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
521
+
522
+ let code, mapObject;
523
+ if (isSourcemap) {
524
+ const res = compile(absFile, { sourceMap: true, outputFile: path.basename(outPath) });
525
+ code = res.code + `\n//# sourceMappingURL=${path.basename(outPath)}.map\n`;
526
+ mapObject = res.mapObject;
527
+ } else {
528
+ code = compile(absFile);
529
+ }
530
+
531
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
532
+ fs.writeFileSync(outPath, code, 'utf8');
533
+ if (mapObject) {
534
+ fs.writeFileSync(outPath + '.map', JSON.stringify(mapObject, null, 2), 'utf8');
535
+ }
536
+ return path.relative(process.cwd(), outPath) || outPath;
537
+ }
538
+
504
539
  // `plainscript build` — TypeScript-style production build:
505
540
  //
506
541
  // Zero config (default):
@@ -514,16 +549,24 @@ function buildOne(filePath, srcDir, outDir, options = {}) {
514
549
  //
515
550
  // With an explicit file argument only that entry is compiled; without one,
516
551
  // every .pln under the discovered source root builds to the output directory.
517
- async function cmdBuild(filePath) {
552
+ // The optional -o/--output <path> flag (single-file builds only) redirects the
553
+ // output to an explicit file instead of the dist layout.
554
+ async function cmdBuild(filePath, outputPath) {
518
555
  const opts = readCompilerOptions();
519
556
  const srcDir = resolveSrcDir(opts);
520
557
  const outDir = resolveOutDir(opts);
521
558
  const exclude = opts && opts.exclude;
522
559
  if (filePath) {
523
- const outPath = buildOne(filePath, srcDir, outDir);
560
+ const outPath = outputPath
561
+ ? writeOneFile(filePath, outputPath)
562
+ : buildOne(filePath, srcDir, outDir);
524
563
  console.log(`\nOutput written to ${outPath}`);
525
564
  return;
526
565
  }
566
+ if (outputPath) {
567
+ console.error('Usage: plainscript build <file.pln> -o <output.js>\n\n-o/--output needs a single .pln file to compile.');
568
+ process.exit(1);
569
+ }
527
570
  const sources = discoverSources(srcDir, outDir, exclude);
528
571
  if (sources.length === 0) {
529
572
  console.error(`No .pln files found under "${srcDir}".`);
@@ -588,7 +631,7 @@ done
588
631
  route get "/api/status"
589
632
  reply json
590
633
  status is "ok"
591
- version is "1.0.35"
634
+ version is "1.0.36"
592
635
  done
593
636
  done
594
637
 
@@ -970,7 +1013,28 @@ async function main() {
970
1013
 
971
1014
  switch (command) {
972
1015
  case 'run': await cmdRun(fileArg, positional.slice(2)); break;
973
- case 'build': await cmdBuild(fileArg); break;
1016
+ case 'build': {
1017
+ // v1.0.36 — optional -o/--output <path>. "-o" is a single-dash flag, so
1018
+ // it survives the "--filtered" positional list; pull it out here before
1019
+ // building the positional file argument for cmdBuild.
1020
+ let outputPath = null;
1021
+ const positionalOnly = [];
1022
+ for (let i = 0; i < args.length; i++) {
1023
+ const a = args[i];
1024
+ if (a === '-o' || a === '--output') {
1025
+ if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1026
+ outputPath = args[++i];
1027
+ } else {
1028
+ console.error('Usage: plainscript build <file.pln> -o <output.js>');
1029
+ process.exit(1);
1030
+ }
1031
+ } else if (!a.startsWith('-')) {
1032
+ positionalOnly.push(a);
1033
+ }
1034
+ }
1035
+ await cmdBuild(positionalOnly[1] || '', outputPath);
1036
+ break;
1037
+ }
974
1038
  case 'check': cmdCheck(fileArg, json); break;
975
1039
  case 'fmt': cmdFmt(fileArg); break;
976
1040
  case 'new': cmdNew(fileArg); break;
@@ -88,6 +88,164 @@ const BUILTIN_DECLARATIONS = {
88
88
  ` }`,
89
89
  `}`,
90
90
  ].join('\n'),
91
+ // v1.0.36 — DOM browser runtime (select/selectAll/parseHTML). Browser
92
+ // globals are guarded so the generated JS explains the problem when it is
93
+ // run under Node instead of failing with a ReferenceError midpoint.
94
+ dom: [
95
+ `function __select(sel) {`,
96
+ ` if (typeof document === 'undefined') throw new Error('select(...) needs a browser (document is not defined in Node).');`,
97
+ ` return document.querySelector(sel);`,
98
+ `}`,
99
+ `function __selectAll(sel) {`,
100
+ ` if (typeof document === 'undefined') throw new Error('selectAll(...) needs a browser (document is not defined in Node).');`,
101
+ ` return [...document.querySelectorAll(sel)];`,
102
+ `}`,
103
+ `function __parseHTML(html) {`,
104
+ ` if (typeof document === 'undefined') throw new Error('parseHTML(...) needs a browser (document is not defined in Node).');`,
105
+ ` const template = document.createElement('template');`,
106
+ ` template.innerHTML = String(html);`,
107
+ ` return template.content;`,
108
+ `}`,
109
+ ].join('\n'),
110
+ // v1.0.36 — input runtime: pointer coordinates, gamepads, dropped files.
111
+ input: [
112
+ `function __localPoint(e, canvas) {`,
113
+ ` if (typeof document === 'undefined') throw new Error('localPoint(...) needs a browser (document is not defined in Node).');`,
114
+ ` const rect = canvas.getBoundingClientRect();`,
115
+ ` return {`,
116
+ ` x: (e.clientX - rect.left) * (canvas.width / rect.width),`,
117
+ ` y: (e.clientY - rect.top) * (canvas.height / rect.height),`,
118
+ ` };`,
119
+ `}`,
120
+ `function __gamepads() {`,
121
+ ` if (typeof navigator === 'undefined' || typeof navigator.getGamepads !== 'function') throw new Error('gamepads() needs a browser with the Gamepad API (navigator.getGamepads).');`,
122
+ ` return navigator.getGamepads().filter(Boolean);`,
123
+ `}`,
124
+ `function __droppedFiles(event) {`,
125
+ ` return [...(event && event.dataTransfer ? event.dataTransfer.files : [])];`,
126
+ `}`,
127
+ ].join('\n'),
128
+ // v1.0.36 — asset-loading runtime (images, JSON, bytes, data URLs). All
129
+ // helpers return promises; the STDLIB entries await them.
130
+ assets: [
131
+ `function __loadImage(url) {`,
132
+ ` if (typeof Image === 'undefined') throw new Error('loadImage(...) needs a browser (global Image is not defined in Node).');`,
133
+ ` return new Promise((resolve, reject) => {`,
134
+ ` const img = new Image();`,
135
+ ` img.onload = () => resolve(img);`,
136
+ ` img.onerror = () => reject(new Error('Could not load image: ' + url));`,
137
+ ` img.src = String(url);`,
138
+ ` });`,
139
+ `}`,
140
+ `async function __fetchJson(url) {`,
141
+ ` if (typeof fetch === 'undefined') throw new Error('fetchJson(...) needs a browser or Node 18+ with global fetch.');`,
142
+ ` const response = await fetch(url);`,
143
+ ` const text = await response.text();`,
144
+ ` let data = null;`,
145
+ ` let parseError = null;`,
146
+ ` try { data = JSON.parse(text); } catch (e) { parseError = e.message; }`,
147
+ ` return { ok: response.ok, status: response.status, data, text, parseError };`,
148
+ `}`,
149
+ `async function __fetchBytes(url) {`,
150
+ ` if (typeof fetch === 'undefined') throw new Error('fetchBytes(...) needs a browser or Node 18+ with global fetch.');`,
151
+ ` const response = await fetch(url);`,
152
+ ` const buffer = await response.arrayBuffer();`,
153
+ ` return { ok: response.ok, status: response.status, data: new Uint8Array(buffer) };`,
154
+ `}`,
155
+ `function __readDataUrl(file) {`,
156
+ ` if (typeof FileReader === 'undefined') throw new Error('readDataUrl(...) needs a browser (FileReader is not defined in Node).');`,
157
+ ` return new Promise((resolve, reject) => {`,
158
+ ` const reader = new FileReader();`,
159
+ ` reader.onload = () => resolve(reader.result);`,
160
+ ` reader.onerror = () => reject(new Error('Could not read the file as a data URL.'));`,
161
+ ` reader.readAsDataURL(file);`,
162
+ ` });`,
163
+ `}`,
164
+ ].join('\n'),
165
+ // v1.0.36 — Web Audio runtime. The AudioContext is created once and shared
166
+ // (browsers cap the number), and resumed on demand because autoplay policies
167
+ // start it suspended.
168
+ audio: [
169
+ `let __plainAudioCtx = null;`,
170
+ `function __audioContext() {`,
171
+ ` if (typeof window === 'undefined' && typeof self === 'undefined') throw new Error('audioContext() / playTone(...) need a browser (Web Audio is not available in Node).');`,
172
+ ` if (!__plainAudioCtx) {`,
173
+ ` const Ctx = window.AudioContext || window.webkitAudioContext;`,
174
+ ` if (!Ctx) throw new Error('Web Audio is not supported in this browser.');`,
175
+ ` __plainAudioCtx = new Ctx();`,
176
+ ` }`,
177
+ ` if (__plainAudioCtx.state === 'suspended') __plainAudioCtx.resume();`,
178
+ ` return __plainAudioCtx;`,
179
+ `}`,
180
+ `function __audioTone(freq, seconds, opts) {`,
181
+ ` const ctx = __audioContext();`,
182
+ ` const o = opts || {};`,
183
+ ` const oscillator = ctx.createOscillator();`,
184
+ ` const gain = ctx.createGain();`,
185
+ ` const duration = seconds || 0.5;`,
186
+ ` oscillator.type = o.type || 'sine';`,
187
+ ` oscillator.frequency.value = freq;`,
188
+ ` gain.gain.value = o.gain || 0.2;`,
189
+ ` oscillator.connect(gain);`,
190
+ ` gain.connect(ctx.destination);`,
191
+ ` const t = ctx.currentTime;`,
192
+ ` if (o.when) oscillator.start(t + o.when); else oscillator.start(t);`,
193
+ ` gain.gain.setValueAtTime(o.gain || 0.2, t);`,
194
+ ` gain.gain.exponentialRampToValueAtTime(0.0001, t + duration);`,
195
+ ` oscillator.stop(t + duration);`,
196
+ `}`,
197
+ `function __loadAudio(url) {`,
198
+ ` if (typeof Audio === 'undefined') throw new Error('loadAudio(...) needs a browser (global Audio is not defined in Node).');`,
199
+ ` return new Promise((resolve, reject) => {`,
200
+ ` const audio = new Audio();`,
201
+ ` audio.oncanplaythrough = () => resolve(audio);`,
202
+ ` audio.onerror = () => reject(new Error('Could not load audio: ' + url));`,
203
+ ` audio.src = String(url);`,
204
+ ` audio.load();`,
205
+ ` });`,
206
+ `}`,
207
+ ].join('\n'),
208
+ // v1.0.36 — WebGL runtime: context selection plus the three compile/link/
209
+ // buffer helpers behind the gl* stdlib entries.
210
+ gl: [
211
+ `function __glContext(canvas) {`,
212
+ ` if (typeof document === 'undefined') throw new Error('webglContext(...) needs a browser (document is not defined in Node).');`,
213
+ ` const gl = canvas.getContext('webgl2') || canvas.getContext('webgl') || canvas.getContext('experimental-webgl');`,
214
+ ` if (!gl) throw new Error('WebGL is not supported in this browser.');`,
215
+ ` return gl;`,
216
+ `}`,
217
+ `function __glShader(gl, type, source) {`,
218
+ ` // Accept both the friendly names ("vertex"/"fragment") and the DOM`,
219
+ ` // constant names ("VERTEX_SHADER"/"FRAGMENT_SHADER").`,
220
+ ` const kind = type === 'vertex' || type === 'VERTEX_SHADER' ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER;`,
221
+ ` const shader = gl.createShader(kind);`,
222
+ ` gl.shaderSource(shader, source);`,
223
+ ` gl.compileShader(shader);`,
224
+ ` if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {`,
225
+ ` const info = gl.getShaderInfoLog(shader);`,
226
+ ` gl.deleteShader(shader);`,
227
+ ` throw new Error('Shader compile error: ' + (info || 'unknown'));`,
228
+ ` }`,
229
+ ` return shader;`,
230
+ `}`,
231
+ `function __glProgram(gl, vertexShader, fragmentShader) {`,
232
+ ` const program = gl.createProgram();`,
233
+ ` gl.attachShader(program, vertexShader);`,
234
+ ` gl.attachShader(program, fragmentShader);`,
235
+ ` gl.linkProgram(program);`,
236
+ ` if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {`,
237
+ ` const info = gl.getProgramInfoLog(program);`,
238
+ ` throw new Error('Program link error: ' + (info || 'unknown'));`,
239
+ ` }`,
240
+ ` return program;`,
241
+ `}`,
242
+ `function __glBuffer(gl, data) {`,
243
+ ` const buffer = gl.createBuffer();`,
244
+ ` gl.bindBuffer(gl.ARRAY_BUFFER, buffer);`,
245
+ ` gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);`,
246
+ ` return buffer;`,
247
+ `}`,
248
+ ].join('\n'),
91
249
  // v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
92
250
  // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
93
251
  // when any feature that needs them is used.
@@ -226,6 +384,7 @@ const BUILTIN_DECLARATIONS = {
226
384
  // from a web route without a native graphics dependency.
227
385
  visualization: [
228
386
  `const __vizFs = require('fs');`,
387
+ `const __vizPath = require('path');`,
229
388
  `function __svgEscape(value) {`,
230
389
  ` return String(value == null ? '' : value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');`,
231
390
  `}`,
@@ -304,6 +463,7 @@ const BUILTIN_DECLARATIONS = {
304
463
  `}`,
305
464
  `function __saveImage(file, image) {`,
306
465
  ` const target = String(file);`,
466
+ ` __vizFs.mkdirSync(__vizPath.dirname(target), { recursive: true });`,
307
467
  ` __vizFs.writeFileSync(target, String(image == null ? '' : image), 'utf8');`,
308
468
  ` return target;`,
309
469
  `}`,
@@ -2494,6 +2654,115 @@ const BUILTIN_DECLARATIONS = {
2494
2654
  blob: (args, context) => `new Blob(${args.map(a => generateExpr(a, context)).join(', ')})`,
2495
2655
  file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2496
2656
  formData: (_args) => `new FormData()`,
2657
+
2658
+ // ── v1.0.36 — browser DOM (IOPL-native). All helpers guard their browser
2659
+ // global, so the generated output throws a clear teaching error under Node.
2660
+ select: (args, context) => {
2661
+ ensureBuiltin(context, 'dom');
2662
+ requireOneArg('select', args);
2663
+ return `__select(${generateExpr(args[0], context)})`;
2664
+ },
2665
+ selectAll: (args, context) => {
2666
+ ensureBuiltin(context, 'dom');
2667
+ requireOneArg('selectAll', args);
2668
+ return `__selectAll(${generateExpr(args[0], context)})`;
2669
+ },
2670
+ parseHTML: (args, context) => {
2671
+ ensureBuiltin(context, 'dom');
2672
+ requireOneArg('parseHTML', args);
2673
+ return `__parseHTML(${generateExpr(args[0], context)})`;
2674
+ },
2675
+
2676
+ // ── v1.0.36 — browser input (IOPL-native).
2677
+ localPoint: (args, context) => {
2678
+ ensureBuiltin(context, 'input');
2679
+ requireArgs('localPoint', args, 2, 'localPoint(event, canvas)');
2680
+ return `__localPoint(${args.map(a => generateExpr(a, context)).join(', ')})`;
2681
+ },
2682
+ gamepads: (_args, context) => {
2683
+ ensureBuiltin(context, 'input');
2684
+ return `__gamepads()`;
2685
+ },
2686
+ droppedFiles: (args, context) => {
2687
+ ensureBuiltin(context, 'input');
2688
+ requireOneArg('droppedFiles', args);
2689
+ return `__droppedFiles(${generateExpr(args[0], context)})`;
2690
+ },
2691
+
2692
+ // ── v1.0.36 — browser assets (IOPL-native). Each awaitable helper is
2693
+ // awaited here, so the surrounding function/handler is marked async.
2694
+ loadImage: (args, context) => {
2695
+ ensureBuiltin(context, 'assets');
2696
+ requireOneArg('loadImage', args);
2697
+ markAsync(context);
2698
+ return `(await __loadImage(${generateExpr(args[0], context)}))`;
2699
+ },
2700
+ loadAudio: (args, context) => {
2701
+ ensureBuiltin(context, 'assets');
2702
+ requireOneArg('loadAudio', args);
2703
+ markAsync(context);
2704
+ return `(await __loadAudio(${generateExpr(args[0], context)}))`;
2705
+ },
2706
+ fetchJson: (args, context) => {
2707
+ ensureBuiltin(context, 'assets');
2708
+ requireOneArg('fetchJson', args);
2709
+ markAsync(context);
2710
+ return `(await __fetchJson(${generateExpr(args[0], context)}))`;
2711
+ },
2712
+ fetchBytes: (args, context) => {
2713
+ ensureBuiltin(context, 'assets');
2714
+ requireOneArg('fetchBytes', args);
2715
+ markAsync(context);
2716
+ return `(await __fetchBytes(${generateExpr(args[0], context)}))`;
2717
+ },
2718
+ readDataUrl: (args, context) => {
2719
+ ensureBuiltin(context, 'assets');
2720
+ requireOneArg('readDataUrl', args);
2721
+ markAsync(context);
2722
+ return `(await __readDataUrl(${generateExpr(args[0], context)}))`;
2723
+ },
2724
+
2725
+ // ── v1.0.36 — Web Audio (IOPL-native).
2726
+ audioContext: (_args, context) => {
2727
+ ensureBuiltin(context, 'audio');
2728
+ return `__audioContext()`;
2729
+ },
2730
+ playTone: (args, context) => {
2731
+ ensureBuiltin(context, 'audio');
2732
+ requireArgs('playTone', args, 1, 'playTone(440)');
2733
+ return `__audioTone(${args.map(a => generateExpr(a, context)).join(', ')})`;
2734
+ },
2735
+
2736
+ // ── v1.0.36 — WebSocket send helper (works with any WebSocket-like object,
2737
+ // browser or Node): strings go through verbatim, everything else is JSON.
2738
+ webSocketSend: (args, context) => {
2739
+ requireArgs('webSocketSend', args, 2, 'webSocketSend(socket, { type: "move", x: 10 })');
2740
+ const ws = generateExpr(args[0], context);
2741
+ const value = generateExpr(args[1], context);
2742
+ return `${ws}.send(typeof (${value}) === 'string' ? (${value}) : JSON.stringify(${value}))`;
2743
+ },
2744
+
2745
+ // ── v1.0.36 — WebGL (IOPL-native).
2746
+ webglContext: (args, context) => {
2747
+ ensureBuiltin(context, 'gl');
2748
+ requireOneArg('webglContext', args);
2749
+ return `__glContext(${generateExpr(args[0], context)})`;
2750
+ },
2751
+ glShader: (args, context) => {
2752
+ ensureBuiltin(context, 'gl');
2753
+ requireArgs('glShader', args, 3, 'glShader(gl, "vertex", "void main() {}")');
2754
+ return `__glShader(${args.map(a => generateExpr(a, context)).join(', ')})`;
2755
+ },
2756
+ glProgram: (args, context) => {
2757
+ ensureBuiltin(context, 'gl');
2758
+ requireArgs('glProgram', args, 3, 'glProgram(gl, vertexShader, fragmentShader)');
2759
+ return `__glProgram(${args.map(a => generateExpr(a, context)).join(', ')})`;
2760
+ },
2761
+ glBuffer: (args, context) => {
2762
+ ensureBuiltin(context, 'gl');
2763
+ requireArgs('glBuffer', args, 2, 'glBuffer(gl, new Float32Array([0, 0, 1, 0, 0, 1]))');
2764
+ return `__glBuffer(${args.map(a => generateExpr(a, context)).join(', ')})`;
2765
+ },
2497
2766
  };
2498
2767
 
2499
2768
  // Mark the enclosing program async when a call awaits at the top level, and
@@ -3808,6 +4077,39 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3808
4077
  ].join('\n');
3809
4078
  }
3810
4079
 
4080
+ // v1.0.36 — every frame … done: one requestAnimationFrame loop. The next
4081
+ // frame is scheduled after the body so the body always runs once per
4082
+ // frame; an awaiting body makes the callback async automatically.
4083
+ case 'EveryFrameStatement': {
4084
+ const prevInHandler = context.inHandler;
4085
+ context.inHandler = true;
4086
+ const block = generateBlock(node.body, indent + ' ', context);
4087
+ context.inHandler = prevInHandler;
4088
+ const handlerAsync = block.emitted ? 'async ' : '';
4089
+ return [
4090
+ `${indent}requestAnimationFrame(${handlerAsync}function __frame(__frameTime) {`,
4091
+ block.out,
4092
+ `${indent} requestAnimationFrame(__frame);`,
4093
+ `${indent}});`,
4094
+ ].join('\n');
4095
+ }
4096
+
4097
+ // v1.0.36 — after <n> <unit> … done: one-shot setTimeout. The delay is an
4098
+ // expression scaled by the unit; an awaiting body makes the callback async.
4099
+ case 'AfterStatement': {
4100
+ const delay = generateExpr(node.delay, context);
4101
+ const prevInHandler = context.inHandler;
4102
+ context.inHandler = true;
4103
+ const block = generateBlock(node.body, indent + ' ', context);
4104
+ context.inHandler = prevInHandler;
4105
+ const handlerAsync = block.emitted ? 'async ' : '';
4106
+ return [
4107
+ `${indent}setTimeout(${handlerAsync}() => {`,
4108
+ block.out,
4109
+ `${indent}}, ${delay} * ${node.unit});`,
4110
+ ].join('\n');
4111
+ }
4112
+
3811
4113
  case 'ScheduleStatement': {
3812
4114
  ensureBuiltin(context, 'scheduler');
3813
4115
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -3929,6 +4231,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3929
4231
  return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
3930
4232
  }
3931
4233
 
4234
+ // v1.0.36 — when <target> "<event>" happens [as <name>] … done: DOM event
4235
+ // listener. The handler param defaults to "event"; an awaiting body makes
4236
+ // the callback async automatically.
4237
+ case 'WhenTargetedStatement': {
4238
+ const prevInHandler = context.inHandler;
4239
+ context.inHandler = true;
4240
+ const block = generateBlock(node.body, indent + ' ', context);
4241
+ context.inHandler = prevInHandler;
4242
+ const handlerAsync = block.emitted ? 'async ' : '';
4243
+ const param = node.paramName || 'event';
4244
+ return `${indent}${generateExpr(node.target, context)}.addEventListener(${JSON.stringify(node.event)}, ${handlerAsync}function (${param}) {\n${block.out}\n${indent}});`;
4245
+ }
4246
+
3932
4247
  case 'StreamStatement': {
3933
4248
  ensureBuiltin(context, '__streamFile');
3934
4249
  markAsync(context);
package/compiler/lexer.js CHANGED
@@ -411,6 +411,18 @@ function tokenize(source) {
411
411
  continue;
412
412
  }
413
413
 
414
+ // Hex number literal (0x... → decimal; supports colors like 0xRRGGBB)
415
+ if (source[i] === '0' && (source[i + 1] === 'x' || source[i + 1] === 'X')) {
416
+ let hex = '';
417
+ let j = i + 2;
418
+ while (j < source.length && /[0-9a-fA-F]/.test(source[j])) hex += source[j++];
419
+ if (hex) {
420
+ tokens.push({ type: TOKEN.NUMBER, value: Number.parseInt(hex, 16), line: tokenLine, col: tokenCol });
421
+ i = j;
422
+ continue;
423
+ }
424
+ }
425
+
414
426
  // Number literal (may include decimal point or BigInt suffix 'n')
415
427
  if (/[0-9]/.test(source[i])) {
416
428
  let num = '';