-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms-full.txt
More file actions
2186 lines (1772 loc) · 101 KB
/
Copy pathllms-full.txt
File metadata and controls
2186 lines (1772 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SxfeScript and SXN, complete documentation
Every documentation page from https://sxfescript.github.io/docs/, in full, in source order.
The index with per-page links is at https://sxfescript.github.io/llms.txt.
==============================================================================
# Quick start
Source: docs/guide/quickstart.md
URL: https://sxfescript.github.io/docs/quickstart/
==============================================================================
# Quick start
`sxn` is a single binary. It runs `.sx` — this project's own language — plus
`.ts`, `.js`, `.mjs` and `.cjs`, all directly, with no build step and nothing
to configure first.
## Install
macOS and Linux, arm64 or x64:
```sh
curl -fsSL https://sxfescript.github.io/latest/install.sh | bash
```
Windows, arm64 or x64:
```powershell
irm https://sxfescript.github.io/latest/install.ps1 | iex
```
Both drop the binary in `~/.sxn/bin` (`%USERPROFILE%\.sxn\bin` on Windows) and
add that to your `PATH`. Open a new shell, then check it:
```sh
sxn --version
```
```
sxn 0.0.1
```
Every release also ships plain `.tar.gz` and `.zip` archives on the
[releases page](https://github.com/SxfeScript/sxfescript/releases), if you'd
rather unpack one yourself.
## Your first program
Put this in `hello.sx`:
```sx
interface Repo {
name: string;
stars: i32;
}
const describe = (repo: Repo): string =>
`${repo.name} has ${repo.stars} star${repo.stars === 1 ? "" : "s"}`;
console.log(describe({ name: "sxfescript", stars: 1 }));
```
```sh
sxn hello.sx
```
```
sxfescript has 1 star
```
That is an ordinary interface and an ordinary annotation, and there is no
`tsc` and no bundler in front of it. `sxn` parses the types itself and strips
them as it goes.
## Ownership and borrows
`.sx` is the same language with mutation and aliasing made explicit. `let mut`
is a mutable owner, `let` an immutable one, `&` borrows a value shared, and
`&mut` borrows it exclusively:
```sx
interface Counter {
hits: i32;
}
// &mut borrows the counter exclusively, so bump can change what it was
// handed without taking ownership of it.
function bump(c: &mut Counter): void {
c.hits += 1;
}
let mut counter: Counter = { hits: 0 };
bump(&mut counter);
bump(&mut counter);
console.log(`counter: ${counter.hits}`);
```
```sh
sxn counter.sx
```
```
counter: 2
```
An interface whose fields are all primitives — `i32`, `f32`, `f64`, `bool` —
describes a fixed-layout struct: declared field order, natural alignment, the
same layout on every supported target. That is what code crossing into native
memory needs.
The syntax is parsed natively today. The full control-flow ownership pass that
enforces every rule in [the language contract](../language/) is still being
written, and [the implementation ledger](../implementation/) tracks exactly
what is checked and what is only parsed. It is worth reading before you rely
on a rule being enforced.
## An HTTP server
`Sxn.serve` hands your function a `Request` and expects a `Response` back —
the same pair of objects a handler gets on Cloudflare Workers, Deno or Bun:
```sx
const server = Sxn.serve({ port: 3000 }, async (req: Request): Promise<Response> => {
const url = new URL(req.url);
if (url.pathname === "/echo") return Response.json(await req.json());
return new Response("hello from " + url.pathname);
});
console.log(`listening on ${server.url}`);
```
```sh
sxn server.sx
```
```
listening on http://127.0.0.1:3000
```
`port: 0` asks the operating system for a free port instead, and
`server.port` then tells you which one it picked. `server.stop()` shuts the
listener down, so one process can serve and then go on to do something else.
## JavaScript and TypeScript run too
Nothing above is required. `sxn` runs a plain `.js`, `.mjs`, `.cjs` or `.ts`
file directly, and a `.sx` module can `import` any of them and vice versa. A
`.sx` file that uses none of the extra syntax is just JavaScript with a
different extension.
```js
const runtime = typeof Sxn !== "undefined" ? "sxn " + Sxn.version : "something else";
console.log(`hello from ${runtime}`);
```
```sh
sxn hello.js
```
```
hello from sxn 0.0.1
```
TypeScript's erasable forms are all accepted: aliases, interfaces, `declare`,
annotations, optional parameters, generics on functions, `as`/`satisfies`, and
union types. `enum` and `namespace` are rejected on purpose rather than
stripped, because both emit a real object at runtime in TypeScript, and
quietly removing them would turn every use of their members into `undefined`:
```
SyntaxError: unsupported keyword: enum
```
## Precompiling
`sxn compile` writes bytecode that skips parsing on later runs:
```sh
sxn compile app.sx -o app.sxbc
sxn app.sxbc
```
`sxn --compile-cache app.sx` does the same thing automatically, building the
cache on the first launch and reusing it afterwards. The measured gains, and
the reason bytecode is not a safe format for untrusted input, are in
[the bytecode spec](../bytecode/).
## Where to go next
- [Examples](../examples/) — complete programs you can run, with their output.
- [The runtime surface](../runtime/) — `fetch`, `Sxn.serve`, streams, crypto, FFI.
- [Node compatibility](../node/) — what runs because it imitates Node.
- [The CLI](../cli/) — every command and flag.
==============================================================================
# Examples
Source: docs/guide/examples.md
URL: https://sxfescript.github.io/docs/examples/
==============================================================================
# Examples
Every program on this page is a real file in
[`examples/`](https://github.com/SxfeScript/sxfescript/tree/main/examples), and
the output under each one is what it actually prints. The code below is
inlined from those files when this page is built, so it cannot drift out of
step with them. Clone the repo and run them, or paste one into a file and run
that.
They are all `.sx`, because that is the language this project is for.
Everything a `.sx` file can do here, a plain `.js`, `.mjs` or `.ts` file can
do too — the annotations and the ownership syntax are the only difference, and
[the quick start](../quickstart/) shows the same program in each.
## Types and borrows
[`examples/hello.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/hello.sx)
```sx
// Run it: sxn examples/hello.sx
//
// This is a .sx file, so the type annotations below are parsed and stripped
// by the runtime itself. There is no tsc, no bundler, and no build step --
// sxn reads this file and runs it.
interface Repo {
name: string;
stars: i32;
}
const describe = (repo: Repo): string =>
`${repo.name} has ${repo.stars} star${repo.stars === 1 ? "" : "s"}`;
console.log(describe({ name: "sxfescript", stars: 1 }));
// `let mut` is a mutable owner, `let` an immutable one. `&mut` borrows a
// value exclusively, so a function can change what it was handed without
// taking ownership of it.
interface Counter {
hits: i32;
}
function bump(c: &mut Counter): void {
c.hits += 1;
}
let mut counter: Counter = { hits: 0 };
bump(&mut counter);
bump(&mut counter);
console.log(`counter: ${counter.hits}`);
```
```sh
sxn examples/hello.sx
```
```
sxfescript has 1 star
counter: 2
```
## A fixed-layout struct
[`examples/velocity.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/velocity.sx)
An interface whose fields are all primitives (`i32`, `f32`, `f64`, `bool`)
describes a struct with declared field order and natural alignment — the same
layout on every supported target, which is what code crossing into native
memory needs.
```sx
interface Transform {
x: f32;
y: f32;
z: f32;
}
const applyVelocity = (transform: &mut Transform, velocity: &Transform, dt: f32): void => {
transform.x += velocity.x * dt;
transform.y += velocity.y * dt;
transform.z += velocity.z * dt;
};
let mut pos: Transform = { x: 0.0, y: 10.0, z: 5.0 };
let vel: Transform = { x: 1.0, y: 0.0, z: 0.0 };
applyVelocity(&mut pos, &vel, 0.016);
console.log(JSON.stringify(pos));
```
```sh
sxn examples/velocity.sx
```
```
{"x":0.016,"y":10,"z":5}
```
## An HTTP server
[`examples/server.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/server.sx)
The handler receives a `Request` and returns a `Response`. `req.url` is
absolute, so `new URL(req.url)` gives you the path and query, and
`await req.json()` reads the body.
```sx
// An HTTP server. Run it: sxn examples/server.sx
//
// The handler takes a Request and returns a Response, the same two objects a
// handler on Cloudflare Workers, Deno or Bun receives. `port: 0` asks the OS
// for a free port; pass a real one to pick it yourself.
interface Note {
id: number;
text: string;
}
const notes: Map<number, string> = new Map([[1, "the first note"]]);
let mut nextId: number = 2;
const server = Sxn.serve({ port: 0 }, async (req: Request): Promise<Response> => {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("try /notes");
}
if (url.pathname === "/notes" && req.method === "GET") {
const all: Note[] = [...notes].map(([id, text]) => ({ id, text }));
return Response.json(all);
}
if (url.pathname === "/notes" && req.method === "POST") {
const { text } = await req.json();
const note: Note = { id: nextId++, text };
notes.set(note.id, note.text);
return Response.json(note, { status: 201 });
}
return new Response("not found", { status: 404 });
});
console.log(`listening on ${server.url}`);
// Call the server we just started, from the same process.
const created = await fetch(`${server.url}/notes`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ text: "written by the example" }),
});
console.log("POST /notes ->", created.status, await created.text());
const all = await fetch(`${server.url}/notes`);
console.log("GET /notes ->", all.status, await all.text());
// Without stop() the listening socket keeps the process alive, which is what
// you want for a real server and not for a script that has finished.
server.stop();
```
```sh
sxn examples/server.sx
```
```
listening on http://127.0.0.1:56690
POST /notes -> 201 {"id":2,"text":"written by the example"}
GET /notes -> 200 [{"id":1,"text":"the first note"},{"id":2,"text":"written by the example"}]
```
The port differs every run, because `port: 0` asks the operating system to
pick a free one. Pass a real port number to choose it yourself.
## fetch and streams
[`examples/fetch.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/fetch.sx)
A response body is a real `ReadableStream`, so it can be piped and consumed a
chunk at a time rather than only read whole.
```sx
// fetch and Web Streams. Run it: sxn examples/fetch.sx
//
// fetch is the global one from the Fetch standard, backed by libcurl. The
// response body is a real ReadableStream, so it can be consumed a chunk at a
// time instead of all at once.
const res: Response = await fetch("https://example.com/");
console.log(res.status, res.headers.get("content-type"));
// Read it as text, in whole.
const html: string = await res.text();
console.log(`${html.length} bytes`);
// Or a chunk at a time, decoding as the bytes arrive.
const streamed: Response = await fetch("https://example.com/");
let mut chunks: number = 0;
let mut characters: number = 0;
for await (const chunk of streamed.body.pipeThrough(new TextDecoderStream())) {
chunks += 1;
characters += chunk.length;
}
console.log(`${chunks} chunk(s), ${characters} characters`);
```
```sh
sxn examples/fetch.sx
```
```
200 text/html
559 bytes
1 chunk(s), 559 characters
```
## Files
[`examples/files.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/files.sx)
`Sxn.file` and `Sxn.write` are the runtime's own file I/O. The `node:fs`
import is the compatibility layer reading the same file back, for code that
already expects Node.
```sx
// Reading and writing files. Run it: sxn examples/files.sx
//
// Sxn.file(path) and Sxn.write(path, data) are the runtime's own file I/O.
// The node:fs import below is the compatibility layer reading the same file,
// for code that already expects Node.
import { tmpdir } from "node:os";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
const path: string = join(tmpdir(), "sxn-example.txt");
await Sxn.write(path, "written by the example\n");
const file = Sxn.file(path);
console.log(JSON.stringify(await file.text()));
// The same file through the Node surface.
console.log("via node:fs ->", JSON.stringify(await readFile(path, "utf8")));
console.log("sxn version:", Sxn.version);
```
```sh
sxn examples/files.sx
```
```
"written by the example\n"
via node:fs -> "written by the example\n"
sxn version: 0.0.1
```
## Calling a C function
[`examples/ffi.sx`](https://github.com/SxfeScript/sxfescript/blob/main/examples/ffi.sx)
`Sxn.ffi(library, symbol, argumentTypes, returnType)` returns a callable
function, through libffi and `dlopen`.
```sx
// Calling a C function directly. Run it: sxn examples/ffi.sx
//
// Sxn.ffi(library, symbol, argumentTypes, returnType) returns a callable
// SxfeScript function, through libffi and dlopen. This is an engine
// capability, not a Node one -- see spec/NATIVE.md for the type list and for
// what is deliberately unsupported (structs by value, callbacks, variadics).
type LibraryName = string;
const libm: LibraryName | undefined = {
darwin: "libSystem.B.dylib",
linux: "libm.so.6",
win32: "msvcrt.dll",
}[process.platform];
if (!libm) throw new Error(`no libm name known for ${process.platform}`);
const pow = Sxn.ffi(libm, "pow", ["f64", "f64"], "f64");
const sqrt = Sxn.ffi(libm, "sqrt", ["f64"], "f64");
console.log("pow(2, 10) =", pow(2, 10));
console.log("sqrt(144) =", sqrt(144));
```
```sh
sxn examples/ffi.sx
```
```
pow(2, 10) = 1024
sqrt(144) = 12
```
Structs by value, callbacks and variadics are rejected rather than
half-supported. [The native-code spec](../native/) has the full type list and
the reasoning.
==============================================================================
# CLI reference
Source: spec/CLI.md
URL: https://sxfescript.github.io/docs/cli/
==============================================================================
# SXN command contract
- `sxn file.sx|ts|js|mjs|cjs|sxbc [args...]` executes a file directly.
- `sxn [--memory-report] [--leak-check] [--compile-cache] <file> [args...]`
runs a file with diagnostics on, or (`--compile-cache`) via a bytecode
cache built and reused across launches -- see `spec/BYTECODE.md`.
- `sxn compile <file> [-o out.sxbc] [--strip]` compiles a file to bytecode
for distribution, without running it. `spec/BYTECODE.md`.
- `sxn run [script] -- [args...]` executes a `package.json` script.
- `sxn install` installs dependencies without lifecycle scripts.
- `sxn add [--dev] package[@range]` adds and installs a dependency.
- `sxn remove package` removes a dependency.
- `sxn init` creates a minimal package.
- `sxn lsp --stdio` runs the language server transport.
Extensionless resolution order (an import or require with no extension, or a
bare directory) is `.sx`, `.mjs`, `.js`, `.cjs`, `.json`, `.node`, `.ts`, then
the same list again under `index.*` for a directory. Lifecycle hooks are
disabled unless their package is explicitly named in the top-level
`trustedDependencies` array.
==============================================================================
# Language contract
Source: spec/LANGUAGE.md
URL: https://sxfescript.github.io/docs/language/
==============================================================================
# SxfeScript language contract
SxfeScript uses `.sx`. JavaScript is the host language; ordinary JS values keep
ordinary JS semantics. Types that can be erased without generating runtime code
are accepted: type aliases, interfaces, `declare`, type-only exports,
annotations, optional parameters, generics on functions, `as`/`satisfies`, and
union types. `enum` and `namespace` are rejected deliberately rather than
erased -- both emit a runtime object in real TypeScript, so silently stripping
them would turn every use of their members into `undefined`. JSX, decorators,
parameter properties, generic classes, and non-null assertions are rejected
because they are simply not implemented yet, not because they've been ruled
out.
`safe` is an optional contextual qualifier for `let` and `const`. It marks a
binding as type-stable for runtime validation and optimization; ordinary
bindings remain dynamic. `safe let` follows the ownership rules below, while
`safe let mut` allows reassignment only within its declared or inferred type.
Safe object shapes reject property addition/deletion and incompatible writes.
The compatibility transformer erases this qualifier; the native parser is
responsible for attaching its runtime descriptor.
Primitive FFI declarations use an explicit unsafe boundary:
```sx
unsafe extern add(i32, i32): i32 from "add.dylib";
```
Native parsing does not implement this lowering yet and rejects `extern`
declarations with an explicit "not yet supported" error rather than
mis-parsing them; the standalone compatibility transformer (src/frontend.c)
lowers the declaration to
```js
const add = Sxn.ffi("add.dylib", "add", "i32, i32", "i32");
```
which is a call that now works -- see `spec/NATIVE.md` for the type list and
what it does with pointers and strings. Structs by value, callbacks and
variadics are still rejected there, because each needs ownership rules this
document has not written down.
## Ownership
- `let mut value: T` creates a mutable owner.
- `let value: T` creates an immutable owner.
- `&value` creates a shared lexical borrow.
- `&mut value` creates an exclusive lexical borrow and requires a mutable owner.
- Passing, assigning, returning, or capturing an affine value by value moves it.
- A borrow cannot be returned, stored in a longer-lived value, or captured.
- `unsafe` permits typed JS/native interop but never disables runtime alias locks.
`i32`, `f32`, `f64`, `bool`, and ordinary JavaScript values are copyable.
Primitive-only interfaces define affine fixed-layout structs. A literal becomes
such a struct only in an explicit annotation, typed argument, or typed return
context.
At control-flow joins, a value moved on any reachable branch is considered
moved. Loop-carried owners must be reinitialized on every continuation path.
Borrowed affine values cannot cross `await`.
## Layout
Fields retain declaration order. `bool` has size/alignment 1, `i32` and `f32`
have size/alignment 4, and `f64` has size/alignment 8. Each field and final
struct size are padded to natural alignment. This layout is identical on all
supported desktop targets.
==============================================================================
# ABI
Source: spec/ABI.md
URL: https://sxfescript.github.io/docs/abi/
==============================================================================
# Sxfe host ABI
The stable public C surface starts in `include/sxfe.h`. Layout descriptors are
finalized before registration. Typed native calls receive pointers only for the
duration of the call. Shared pointers are read-only; mutable pointers are
exclusive. Hosts must not retain either pointer.
The production engine will expose distinct `sx_*` bytecodes for allocation,
move, shared borrow, mutable borrow, release, field access, and owned drop.
QuickJS `OP_drop` remains untouched because it is an operand-stack operation.
Moving a layout value into JavaScript consumes it and boxes a copy. Borrowing it
into JavaScript creates a revocable proxy. Typed JavaScript objects crossing
into SX use shared/exclusive header locks, and incompatible property writes
throw `TypeError`.
FFI declarations are unsafe by default and are expected to use the platform C
ABI. The initial syntax is `unsafe extern name(types): return from "library"`.
Library handles must be runtime-owned and remain live until all wrappers and
callbacks are released; native pointers may not outlive a call unless an
explicit ownership type is added. What is implemented today, and where it
sits relative to the Node compatibility layer, is `spec/NATIVE.md`.
==============================================================================
# Bytecode
Source: spec/BYTECODE.md
URL: https://sxfescript.github.io/docs/bytecode/
==============================================================================
# Precompiled bytecode: `.sxbc`
`sxn` can skip parsing a file entirely and run its already-compiled bytecode
instead. This exists for two different reasons that happen to share one
mechanism:
- **Distribution.** `sxn compile app.sx` produces `app.sxbc`; ship that
instead of the source and there is nothing left to parse on the machine
that finally runs it. `--strip` drops the compiling machine's own file
paths from the output, for when the source shouldn't be reconstructible
from a stack trace.
- **Startup, on a large file.** `sxn --compile-cache app.sx` compiles once,
caches the result next to the source, and reuses it on every later launch
until the source changes. This is the same idea already applied to this
runtime's own bootstrap (see the README's benchmark section), turned into
something a user's own script can opt into.
Both produce and consume the same file format, so `sxn app.sxbc` runs either
one's output directly.
## Is it worth it for your script?
Measured on this runtime's own hardware (Apple M4, Release build), median of
9 runs, whole-process wall clock including startup:
| Script | From source | From bytecode | Saved |
|---|---:|---:|---:|
| `console.log("hi")` | 7.8 ms | 6.9 ms | 12% |
| 32k-line generated file (618 KB) | 15.2 ms | 9.6 ms | 37% |
Skipping the parse always saves something, because there is always a parse to
skip — but it scales with how much there is to parse. A one-line script gets
a small, real win from skipping the tokenizer and AST setup entirely. A
large generated file, a bundled app, or a big TypeScript-emitted script gets
a large one. `--compile-cache` is the flag to reach for once a script is big
enough, or launched often enough, that the difference shows up in something
you're measuring; for a small script run once, it's not going to move
anything you'd notice.
## `sxn compile <file> [-o out.sxbc] [--strip]`
```sh
sxn compile app.sx # writes app.sxbc next to it
sxn compile app.sx -o dist/app.sxbc
sxn compile app.sx --strip -o dist/app.sxbc # no local paths in the output
```
Works on anything `sxn` can run as an entry point: `.sx`, `.ts`, `.js`,
`.mjs`, `.cjs`, module or CommonJS, decided the same way running it directly
would decide (`spec/NODE.md`). The output name defaults to the input's name
with its extension replaced by `.sxbc`.
`--strip` removes line-number and local-variable debug tables (so a stripped
error reports a bytecode offset, not a source line) and, separately, embeds
the source's bare filename instead of its full path at compile time, so
nothing about the machine or directory the source lived in survives into the
shipped file. Verify what you're about to ship with `strings out.sxbc` if
that matters to you.
## `sxn --compile-cache <file> [args...]`
Runs `file` exactly as `sxn file` would, except: before running, it checks
for an `.sxbc` cache next to the source. If the cache is missing or older
than the source (by mtime), it compiles fresh and writes the cache; either
way, execution then runs from bytecode. A script invoked repeatedly parses
once, not on every launch — the common case for a CLI tool people run
often, or a dev server that restarts on every save without its own source
having changed on most of those restarts.
The cache is invisible to the script itself: `process.argv` and `__filename`
still show the original source path, not the internal `.sxbc` file.
## `sxn app.sxbc`
Runs a `.sxbc` file directly, as if it were the source it was compiled from.
`require()` and `import` inside it resolve normally, against the directory
the `.sxbc` file itself sits in.
## Format and limits
A `.sxbc` file is 5 bytes of header — a magic number this runtime checks
before trusting the rest as bytecode, so a corrupt or foreign file fails with
a clear message rather than a confusing one from deep inside the engine —
followed by QuickJS's own serialized bytecode for either a compiled module or
a compiled CommonJS wrapper function. The format is tied to this runtime's
exact build (the same `BC_VERSION` dependency the lazily-loaded builtins
have, `spec/IMPLEMENTATION.md`): a `.sxbc` compiled by one version of `sxn`
is not guaranteed to load in another, and a version mismatch is reported
rather than misread.
**Only compile trusted code.** `JS_ReadObject` with bytecode enabled is, by
QuickJS's own documentation, not a safe format to parse untrusted input —
unlike source text, a crafted bytecode blob can misdirect the interpreter
directly. Compile your own code, or code you already trust as source; don't
treat a `.sxbc` from an untrusted party as safer to run than the
`.js`/`.mjs`/`.cjs` it might have come from.
A `.sxbc`'s dependencies (whatever it `import`s or `require`s) still resolve
and load as ordinary source at run time — compiling one file does not pull
its dependency tree into the same blob. Compiling a whole app ahead of time
currently means compiling each of its own files individually; there is no
bundler step here.
==============================================================================
# Runtime surface
Source: spec/RUNTIME.md
URL: https://sxfescript.github.io/docs/runtime/
==============================================================================
# The runtime surface
This is what `sxn` gives you independent of Node compatibility: the WinterCG
web APIs (45 of 55 names in the common surface), the `Sxn` host namespace, and
the engine capabilities that go with it. `spec/NODE.md` is the other half —
what runs because it imitates Node.
The split matters because only this half travels when the engine is embedded
elsewhere (`spec/NATIVE.md` explains why for the native-code case
specifically).
If you're choosing what to build against: code written to this surface plus
`spec/NODE.md`'s CommonJS/ESM loader runs on `sxn`, in a browser Worker, and
on Cloudflare Workers/Deno/Bun without a compatibility shim, because it's the
same surface those runtimes implement.
## Script kinds and entry points
`sxn file.sx` runs an SxfeScript file — ordinary JavaScript plus explicit
mutation, affine values, and borrow sigils, parsed natively with no separate
transform step (`spec/LANGUAGE.md`). `sxn file.ts` strips TypeScript types and
runs the result, also natively, with no build step. `sxn file.js` / `.mjs` /
`.cjs` run plain JavaScript. All four import each other freely: a `.sx`
module can `import` a `.ts` module and vice versa.
Module-or-script is decided the way Node decides it — see spec/NODE.md — with
one exception: `.sx` and `.ts` are always modules, because type stripping is
this project's own feature and has always meant ESM.
## `fetch`
A global `fetch(url, options)`, backed by libcurl, with methods, headers,
redirects, and streaming request and response bodies. `Sxn.fetch` is the same
function reachable through the host namespace, for code that wants to be
explicit about where it's calling.
- `Request`, `Response`, `Headers`, `URL`, `URLSearchParams` — the standard
classes, including `Response.json/error/redirect`, `Request.clone`,
`Headers.getSetCookie`, and the one exception the Fetch spec itself carves
out: repeated `Headers.append("Set-Cookie", …)` calls stay separate instead
of folding into one comma-joined value.
- A string body streams; `for await (const chunk of res.body)` and
`res.body.pipeThrough(new TextDecoderStream())` both work on a response.
- `FormData`, `File`, `Blob` for multipart bodies.
## Sxn.serve — the HTTP server
```sx
const server = Sxn.serve({ port: 0 }, async (req: Request): Promise<Response> => {
const url = new URL(req.url);
if (url.pathname === "/echo") return Response.json(await req.json());
return new Response("hi");
});
server.port; // the port the OS chose, since `port: 0` asked it to pick
server.url; // "http://127.0.0.1:PORT"
server.stop();
```
The handler receives a `Request` — `req.url` is absolute, so `new URL(req.url)`
gives you the path and query, and `req.text()`/`req.json()`/`req.arrayBuffer()`
read the body. It returns a `Response`, `Sxn.serve`'s own SSE helper, a
WebSocket upgrade, or a plain `{ statusCode, headers, body }` object, which is
the shape the native layer speaks and `node:http` is built on directly.
Response headers are emitted in declaration order; an array value repeats the
header (the multi-`Set-Cookie` case), and `Content-Length`/`Connection` are
filtered since those describe the framing rather than the payload the handler
wrote. The returned handle reports `port`, `url`, and a `stop()` that lets a
process serve and then do something else, rather than block forever the way a
bare listener would.
## Web Streams
`ReadableStream`, `WritableStream`, `TransformStream`, and both queuing
strategies, plus `TextEncoderStream`/`TextDecoderStream` built on them. A
fetch response body is a real `ReadableStream`, not a stand-in, so
`pipeThrough`, `pipeTo`, and `for await` all work on one. Not yet
implemented: `CompressionStream`/`DecompressionStream` (`node:zlib` covers
the same ground synchronously — see spec/NODE.md) and the BYOB reader.
## Crypto
`crypto.getRandomValues`, `crypto.randomUUID`, and `crypto.subtle` — the
Web Crypto surface, backed by OpenSSL. `node:crypto`'s `Hash`/`Hmac`/
`randomBytes`/`timingSafeEqual` cover the synchronous, Node-flavored version
of the same digests; see spec/NODE.md.
## Structured data and messaging
`structuredClone`, `MessageChannel`/`MessagePort`/`MessageEvent`,
`Event`/`EventTarget`/`CustomEvent`, `AbortController`/`AbortSignal`,
`DOMException`. `queueMicrotask`, `setTimeout`/`setInterval` and their
`clearX` counterparts, `performance.now` (bound directly to its C primitive,
not wrapped — see the README benchmarks for why that matters).
Not implemented: `URLPattern`, `BroadcastChannel`, `Worker`, `WebSocket` as an
*outbound client* (the server side — upgrading an incoming connection to a
WebSocket from a `Sxn.serve` handler — works), `ErrorEvent`,
`PromiseRejectionEvent`, and `Intl`.
## `Sxn.ffi` — calling a C function
```sx
const pow = Sxn.ffi("libSystem.B.dylib", "pow", ["f64", "f64"], "f64");
pow(2, 10); // 1024
```
Backed by libffi and `dlopen`. Full type list, pointer/string handling, and
what's deliberately unsupported (structs by value, callbacks, variadics) are
in `spec/NATIVE.md`, along with why this is the half of native-code support
that belongs to the engine rather than to Node compatibility.
## Other `Sxn.*` entries
`Sxn.file(path)` and `Sxn.write(path, data)` for file I/O in the Bun-style
idiom; `Sxn.memoryUsage()`; `Sxn.version`.
## What's deliberately not here
Anything that only makes sense with a machine-code tier — a JIT, or
`process.dlopen`/`.node` addons — lives in the Node-compatibility layer
instead, not here, precisely so a build of this runtime that drops that layer
loses nothing on this side. See `spec/NATIVE.md` for the reasoning and
`spec/NODE.md` for what that layer covers.
==============================================================================
# Node compatibility
Source: spec/NODE.md
URL: https://sxfescript.github.io/docs/node/
==============================================================================
# The Node-compatibility layer
This is what makes `sxn` usable as a Node alternative: CommonJS, the `node:`
builtins, and native-addon loading. It's the half of the runtime that a
mobile or embedded build can drop entirely without losing anything on the
`spec/RUNTIME.md` side — `spec/NATIVE.md` explains why that split exists for
the native-code case, and the same reasoning applies to this whole layer:
Node emulation is dead weight to an embedder with no Node surface of its own.
## Running a file the way Node runs it
`sxn` decides module-or-CommonJS the way Node does: `.mjs`/`.mts` are always
modules, `.cjs` is always CommonJS, and a plain `.js` file or an extensionless
one (every CLI an npm package ships) follows the nearest `package.json`'s
`"type"`, defaulting to CommonJS. A `#!/usr/bin/env node` shebang line is
stripped before evaluation, the way Node strips it, so those extensionless
CLIs run directly: `sxn ./node_modules/.bin/whatever` works.
A CommonJS module gets `require`, `module`, `exports`, `__filename`, and
`__dirname`, wrapped exactly the way Node wraps it. `require.resolve(spec)`
exists on every `require`. `require("node:module").createRequire(path)`
returns a `require` anchored at that path's directory rather than the caller's
— get this wrong and it resolves the wrong package's siblings.
## Module resolution
Bare specifiers resolve through `node_modules`, walking up from the importing
file — plain packages, scoped packages (`@scope/name`), and subpath imports.
A package's `exports` field is read for the `.` subpath, checking conditions
in the order `import`, `module`, `default`, `require`, `node`, then falling
back to `module`, then `main`. Circular `require` sees the same partially
filled `exports` a cycle sees in Node, rather than recursing forever.
## `.node` addons
`require("./thing.node")` and the `process.dlopen` it calls under the hood
both work, through a Node-API implementation built on QuickJS — full detail,
including what's implemented and what isn't, is `spec/NATIVE.md`. It's
listed here because it's the other reason this layer exists as a separate,
droppable piece: on iOS you can't `dlopen` code that arrived after the app
was signed, so this half of native-code support is inherently a
desktop-and-server capability, unlike `Sxn.ffi`.
## `node:` builtins
24 of the ~37 Node ships. What each one covers, briefly, and where it's
worth knowing the gap:
| Module | Covers |
|---|---|
| `assert`, `assert/strict` | The standard assertion functions. |
| `buffer` | See below — this one gets its own section. |
| `crypto` | `Hash`, `Hmac` (standard construction over the digest primitive), `randomBytes`, `randomUUID`, `timingSafeEqual`. |
| `events` | `EventEmitter`, including the mixin pattern (`Object.assign(fn, EventEmitter.prototype)`) Express uses, where `_events` is created lazily on first `on()`/`emit()` rather than in a constructor that never runs. |
| `fs`, `fs/promises` | File I/O, sync and promise-based. |
| `http` | `createServer`, `IncomingMessage`, `ServerResponse`, `ClientRequest`, `STATUS_CODES`, `METHODS`. The request body defers behind `_read` rather than pushing eagerly, because a body-parser attaches its listener after the handler returns — push first and it gets nothing. |
| `module` | The `Module` constructor (what `require('module').prototype` expects), `createRequire`, `builtinModules`, `isBuiltin`. |
| `net` | `isIP`/`isIPv4`/`isIPv6`, including IPv6 zone-index stripping (`fe80::1%eth0`). `Socket`/`Server` are not implemented and throw. |
| `os`, `path`, `querystring`, `url`, `util` | The usual surface — `inspect`, `format`, `promisify`, `deepEqual`, POSIX/Win32 path handling, and so on. |
| `perf_hooks` | Enough for timing code that reads `performance.now`-equivalent values. |
| `process` | `platform`, `arch`, `version`/`versions`, `stdout`/`stderr`/`stdin`, `hrtime`, `emitWarning`, `uptime`, `pid`, `env`, `argv`, `dlopen`. |
| `stream`, `stream/promises` | `Readable`/`Writable`/`Duplex`/`Transform`/`PassThrough`, `pipeline`, `finished`. The module export is the `Stream` function itself (some packages `require('stream')` and call it as a constructor), and `Readable` supports real `pipe`/`unpipe` — the latter matters because `finalhandler` calls it on every response, piped or not. |
| `string_decoder`, `timers`, `timers/promises`, `tty` | Small, focused shims. |
| `zlib` | `gzipSync`/`gunzipSync`/`deflateSync`/`inflateSync` and the stream equivalents (`createGzip` etc.), over the zlib already linked in. No `promises` namespace — Node doesn't have one either. |
Not implemented: `child_process`, `cluster`, `dns`, `http2`, `https`,
`readline`, `stream/web`, `tls`, `v8`, `vm`, `worker_threads`, `inspector`,
`async_hooks`. `child_process` is the one that stops `next build` today —
see `spec/NATIVE.md`'s account of running Next.js's own compiler for the
full trace of what does and doesn't stand in the way.
## Buffer
`Buffer` extends `Uint8Array` and matches Node's encoding behavior, verified
against Node's own output rather than against itself — a divergence in either
runtime fails the fixture:
- `utf8`/`utf-8`, `hex`, `base64`, `base64url`, `latin1`/`binary`, `ascii`,
`ucs2`/`ucs-2`/`utf16le`/`utf-16le` — every encoding name, case-insensitive,
in both directions.
- `hex` decoding stops at the first invalid pair rather than throwing, the
way Node's own reader does (unlike the standard `Uint8Array.fromHex`, which
throws).
- `base64` decoding skips characters it can't use, stops at `=`, accepts
either alphabet, needs no padding, and reads one byte per UTF-16 code unit
— which is why a multi-byte character truncates a base64 string early: its
high surrogate half masks down to `=`.
- `Buffer.byteLength`, `compare`, `equals`, `concat`, `toJSON` (Node's
`{type:"Buffer",data:[...]}` shape).
## Encoding-name and Buffer performance
Two things specific to this layer are worth knowing if you're profiling
Buffer-heavy code: a literal encoding string (`"utf-8"`, `"hex"`) at a call
site is recognized by pointer identity against the atom table rather than by
hashing and comparing, and `Buffer.byteLength` computes the UTF-8 byte count
directly rather than encoding the string to measure it. Both are covered in
more depth, with numbers, in the README's benchmark section.
==============================================================================
# Native code
Source: spec/NATIVE.md
URL: https://sxfescript.github.io/docs/native/
==============================================================================
# Calling native code
Two things in this runtime call into machine code, and they sit on opposite
sides of a line that matters for where ArcSX is going.
| | `Sxn.ffi` | `.node` addons |
|---|---|---|
| Lives in | `src/ffi.c` | `src/napi.c` |
| Installed by | the runtime's own `Sxn` surface (`src/network.c`) | the node: layer (`src/node.c`) |
| Direction | JavaScript calls out to a C function | a C library calls back into the host |
| Backed by | libffi + `dlopen` | Node-API implemented on QuickJS |
| Goes to Rayact | yes | no |
## Which side of the fence, and why
The question that decided this is what happens when ArcSX is folded into
Rayact. Rayact embeds quickjs-ng 0.15.0 — the same base this fork started
from, with about 350 lines of its own on top — so the swap is a small delta
rather than a re-port, and whatever these two features are attached to comes
along with it.