trebol 0.1.0 → 0.1.2

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 (160) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +13790 -11417
  3. package/dist/fonts/OFL.txt +93 -0
  4. package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
  5. package/dist/fonts/inter-cyrillic.woff2 +0 -0
  6. package/dist/fonts/inter-greek-ext.woff2 +0 -0
  7. package/dist/fonts/inter-greek.woff2 +0 -0
  8. package/dist/fonts/inter-latin-ext.woff2 +0 -0
  9. package/dist/fonts/inter-latin.woff2 +0 -0
  10. package/dist/fonts/inter-vietnamese.woff2 +0 -0
  11. package/dist/lib/core/access.d.ts +10 -0
  12. package/dist/lib/core/access.js +210 -0
  13. package/dist/lib/core/base.d.ts +4 -0
  14. package/dist/lib/core/base.js +50 -0
  15. package/dist/lib/core/bitset.d.ts +9 -0
  16. package/dist/lib/core/bitset.js +75 -0
  17. package/dist/lib/core/boot.d.ts +18 -0
  18. package/dist/lib/core/boot.js +73 -0
  19. package/dist/lib/core/compare.d.ts +9 -0
  20. package/dist/lib/core/compare.js +156 -0
  21. package/dist/lib/core/ctx.d.ts +36 -0
  22. package/dist/lib/core/ctx.js +251 -0
  23. package/dist/lib/core/dec.d.ts +28 -0
  24. package/dist/lib/core/dec.js +158 -0
  25. package/dist/lib/core/errors.d.ts +15 -0
  26. package/dist/lib/core/errors.js +44 -0
  27. package/dist/lib/core/escapes.d.ts +14 -0
  28. package/dist/lib/core/escapes.js +80 -0
  29. package/dist/lib/core/eval.d.ts +220 -0
  30. package/dist/lib/core/eval.js +666 -0
  31. package/dist/lib/core/func.d.ts +68 -0
  32. package/dist/lib/core/func.js +129 -0
  33. package/dist/lib/core/hash.d.ts +5 -0
  34. package/dist/lib/core/hash.js +155 -0
  35. package/dist/lib/core/index.d.ts +18 -0
  36. package/dist/lib/core/index.js +20 -0
  37. package/dist/lib/core/int64.d.ts +22 -0
  38. package/dist/lib/core/int64.js +113 -0
  39. package/dist/lib/core/kinds.d.ts +67 -0
  40. package/dist/lib/core/kinds.js +134 -0
  41. package/dist/lib/core/lexer.d.ts +13 -0
  42. package/dist/lib/core/lexer.js +702 -0
  43. package/dist/lib/core/mezz.d.ts +1 -0
  44. package/dist/lib/core/mezz.js +360 -0
  45. package/dist/lib/core/mold.d.ts +20 -0
  46. package/dist/lib/core/mold.js +434 -0
  47. package/dist/lib/core/natives/control.d.ts +1 -0
  48. package/dist/lib/core/natives/control.js +374 -0
  49. package/dist/lib/core/natives/csv.d.ts +15 -0
  50. package/dist/lib/core/natives/csv.js +315 -0
  51. package/dist/lib/core/natives/data.d.ts +11 -0
  52. package/dist/lib/core/natives/data.js +367 -0
  53. package/dist/lib/core/natives/define.d.ts +17 -0
  54. package/dist/lib/core/natives/define.js +47 -0
  55. package/dist/lib/core/natives/encode.d.ts +3 -0
  56. package/dist/lib/core/natives/encode.js +187 -0
  57. package/dist/lib/core/natives/json.d.ts +5 -0
  58. package/dist/lib/core/natives/json.js +273 -0
  59. package/dist/lib/core/natives/math.d.ts +3 -0
  60. package/dist/lib/core/natives/math.js +500 -0
  61. package/dist/lib/core/natives/parse.d.ts +1 -0
  62. package/dist/lib/core/natives/parse.js +600 -0
  63. package/dist/lib/core/natives/series.d.ts +4 -0
  64. package/dist/lib/core/natives/series.js +519 -0
  65. package/dist/lib/core/natives/text.d.ts +1 -0
  66. package/dist/lib/core/natives/text.js +487 -0
  67. package/dist/lib/core/natives/xml.d.ts +9 -0
  68. package/dist/lib/core/natives/xml.js +242 -0
  69. package/dist/lib/core/series.d.ts +26 -0
  70. package/dist/lib/core/series.js +73 -0
  71. package/dist/lib/core/symbols.d.ts +9 -0
  72. package/dist/lib/core/symbols.js +44 -0
  73. package/dist/lib/core/values.d.ts +206 -0
  74. package/dist/lib/core/values.js +223 -0
  75. package/dist/lib/host/browser.d.ts +4 -0
  76. package/dist/lib/host/browser.js +4974 -0
  77. package/dist/lib/host/chart.d.ts +26 -0
  78. package/dist/lib/host/chart.js +158 -0
  79. package/dist/lib/host/compress.d.ts +1 -0
  80. package/dist/lib/host/compress.js +37 -0
  81. package/dist/lib/host/devlog.d.ts +11 -0
  82. package/dist/lib/host/devlog.js +13 -0
  83. package/dist/lib/host/devtools.d.ts +23 -0
  84. package/dist/lib/host/devtools.js +626 -0
  85. package/dist/lib/host/draw.d.ts +31 -0
  86. package/dist/lib/host/draw.js +348 -0
  87. package/dist/lib/host/fonts/OFL.txt +93 -0
  88. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  89. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  90. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  91. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  92. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  93. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  94. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  95. package/dist/lib/host/fonts.d.ts +11 -0
  96. package/dist/lib/host/fonts.js +29 -0
  97. package/dist/lib/host/icons.d.ts +3 -0
  98. package/dist/lib/host/icons.js +97 -0
  99. package/dist/lib/host/index.d.ts +40 -0
  100. package/dist/lib/host/index.js +192 -0
  101. package/dist/lib/host/js.d.ts +5 -0
  102. package/dist/lib/host/js.js +130 -0
  103. package/dist/lib/host/locale.d.ts +40 -0
  104. package/dist/lib/host/locale.js +241 -0
  105. package/dist/lib/host/markdown.d.ts +30 -0
  106. package/dist/lib/host/markdown.js +161 -0
  107. package/dist/lib/host/modules.d.ts +14 -0
  108. package/dist/lib/host/modules.js +300 -0
  109. package/dist/lib/host/natives.d.ts +6 -0
  110. package/dist/lib/host/natives.js +98 -0
  111. package/dist/lib/host/net.d.ts +12 -0
  112. package/dist/lib/host/net.js +549 -0
  113. package/dist/lib/host/orbit.d.ts +121 -0
  114. package/dist/lib/host/orbit.js +374 -0
  115. package/dist/lib/host/page.d.ts +9 -0
  116. package/dist/lib/host/page.js +55 -0
  117. package/dist/lib/host/rows.d.ts +29 -0
  118. package/dist/lib/host/rows.js +109 -0
  119. package/dist/lib/host/scheduler.d.ts +51 -0
  120. package/dist/lib/host/scheduler.js +197 -0
  121. package/dist/lib/host/theme.d.ts +58 -0
  122. package/dist/lib/host/theme.js +1667 -0
  123. package/dist/lib/ui/i18n.trb +117 -0
  124. package/dist/lib/ui/test.trb +565 -0
  125. package/dist/lib/ui/ui.trb +1678 -0
  126. package/dist/trebol.js +1427 -138
  127. package/editors/vscode/README.md +15 -0
  128. package/editors/vscode/language-configuration.json +28 -0
  129. package/editors/vscode/package.json +42 -0
  130. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  131. package/package.json +23 -7
  132. package/src/core/boot.ts +1 -1
  133. package/src/core/func.ts +4 -0
  134. package/src/core/natives/control.ts +1 -1
  135. package/src/core/natives/series.ts +9 -1
  136. package/src/core/natives/text.ts +2 -0
  137. package/src/host/browser.ts +1235 -83
  138. package/src/host/devlog.ts +16 -0
  139. package/src/host/devtools.ts +641 -0
  140. package/src/host/fonts/OFL.txt +93 -0
  141. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  142. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  143. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  144. package/src/host/fonts/inter-greek.woff2 +0 -0
  145. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  146. package/src/host/fonts/inter-latin.woff2 +0 -0
  147. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  148. package/src/host/fonts.ts +39 -0
  149. package/src/host/index.ts +5 -3
  150. package/src/host/js.ts +127 -0
  151. package/src/host/markdown.ts +9 -0
  152. package/src/host/modules.ts +41 -2
  153. package/src/host/net.ts +9 -1
  154. package/src/host/orbit.ts +432 -0
  155. package/src/host/rows.ts +30 -0
  156. package/src/host/scheduler.ts +62 -36
  157. package/src/host/theme.ts +270 -6
  158. package/src/ui/i18n.trb +10 -0
  159. package/src/ui/test.trb +565 -0
  160. package/src/ui/ui.trb +564 -90
@@ -0,0 +1,161 @@
1
+ // The Markdown a rich text field keeps as its value: headings, paragraphs, bold,
2
+ // italic, links and lists. Parsed to a small tree that the host draws with its
3
+ // own nodes, so text from outside never becomes HTML.
4
+ const HEADING = /^(#{1,3}) +(.*)$/;
5
+ const BULLET = /^[-*] +(.*)$/;
6
+ const NUMBER = /^\d+\. +(.*)$/;
7
+ export function parseMd(src) {
8
+ const lines = src.replace(/\r\n?/g, '\n').split('\n');
9
+ const out = [];
10
+ let i = 0;
11
+ while (i < lines.length) {
12
+ const line = lines[i];
13
+ if (line.trim() === '') {
14
+ i++;
15
+ continue;
16
+ }
17
+ const h = HEADING.exec(line);
18
+ if (h !== null) {
19
+ out.push({ k: 'h', level: h[1].length, kids: parseInline(h[2]) });
20
+ i++;
21
+ continue;
22
+ }
23
+ const marker = BULLET.test(line) ? BULLET : NUMBER.test(line) ? NUMBER : null;
24
+ if (marker !== null) {
25
+ const items = [];
26
+ for (let m = marker.exec(lines[i] ?? ''); m !== null; m = marker.exec(lines[i] ?? '')) {
27
+ items.push(parseInline(m[1]));
28
+ i++;
29
+ }
30
+ out.push({ k: marker === BULLET ? 'ul' : 'ol', items });
31
+ continue;
32
+ }
33
+ const text = [];
34
+ while (i < lines.length && lines[i].trim() !== '' && !HEADING.test(lines[i]) && !BULLET.test(lines[i]) && !NUMBER.test(lines[i])) {
35
+ text.push(lines[i++]);
36
+ }
37
+ out.push({ k: 'p', kids: parseInline(text.join('\n')) });
38
+ }
39
+ return out;
40
+ }
41
+ /** Where `mark` closes after `from`, skipping escapes; a run of stars closes at its end. */
42
+ function closing(s, mark, from) {
43
+ for (let i = from; i < s.length; i++) {
44
+ if (s[i] === '\\') {
45
+ i++;
46
+ continue;
47
+ }
48
+ if (!s.startsWith(mark, i))
49
+ continue;
50
+ if (mark === '*' && s[i + 1] === '*') {
51
+ i++;
52
+ continue;
53
+ }
54
+ if (mark === '**')
55
+ while (s[i + 2] === '*')
56
+ i++;
57
+ return i;
58
+ }
59
+ return -1;
60
+ }
61
+ /** The `)` that ends a link, which may hold balanced ones: a(b).html */
62
+ function closingParen(s, from) {
63
+ let depth = 0;
64
+ for (let i = from; i < s.length && s[i] !== '\n'; i++) {
65
+ if (s[i] === '(')
66
+ depth++;
67
+ else if (s[i] === ')' && depth-- === 0)
68
+ return i;
69
+ }
70
+ return -1;
71
+ }
72
+ function parseInline(s) {
73
+ const out = [];
74
+ const text = (t) => {
75
+ const last = out[out.length - 1];
76
+ if (last?.k === 'text')
77
+ last.text += t;
78
+ else
79
+ out.push({ k: 'text', text: t });
80
+ };
81
+ let i = 0;
82
+ while (i < s.length) {
83
+ const c = s[i];
84
+ if (c === '\\' && i + 1 < s.length) {
85
+ text(s[i + 1]);
86
+ i += 2;
87
+ }
88
+ else if (c === '\n') {
89
+ out.push({ k: 'br' });
90
+ i++;
91
+ }
92
+ else if (c === '*') {
93
+ const mark = s.startsWith('**', i) ? '**' : '*';
94
+ const end = closing(s, mark, i + mark.length);
95
+ if (end <= i + mark.length) {
96
+ text(c);
97
+ i++;
98
+ }
99
+ else {
100
+ out.push({ k: mark === '**' ? 'b' : 'i', kids: parseInline(s.slice(i + mark.length, end)) });
101
+ i = end + mark.length;
102
+ }
103
+ }
104
+ else if (c === '[') {
105
+ const end = closing(s, ']', i + 1);
106
+ const close = end > 0 && s[end + 1] === '(' ? closingParen(s, end + 2) : -1;
107
+ if (close < 0) {
108
+ text(c);
109
+ i++;
110
+ }
111
+ else {
112
+ out.push({ k: 'a', href: s.slice(end + 2, close), kids: parseInline(s.slice(i + 1, end)) });
113
+ i = close + 1;
114
+ }
115
+ }
116
+ else {
117
+ text(c);
118
+ i++;
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+ function printInline(items) {
124
+ return items.map(x => {
125
+ switch (x.k) {
126
+ case 'text': return x.text.replace(/[\\*[\]]/g, '\\$&');
127
+ case 'br': return '\n';
128
+ case 'b': return `**${printInline(x.kids)}**`;
129
+ case 'i': return `*${printInline(x.kids)}*`;
130
+ case 'a': return `[${printInline(x.kids)}](${x.href})`;
131
+ }
132
+ }).join('');
133
+ }
134
+ /** A text that would read as a heading or a list keeps its meaning with an escape. */
135
+ function printText(items) {
136
+ return printInline(items).split('\n').map(line => line.replace(/^(#{1,3} |- )/, '\\$1').replace(/^(\d+)\. /, '$1\\. ')).join('\n');
137
+ }
138
+ export function printMd(blocks) {
139
+ return blocks.map(b => {
140
+ switch (b.k) {
141
+ case 'p': return printText(b.kids);
142
+ case 'h': return `${'#'.repeat(b.level)} ${printInline(b.kids)}`;
143
+ case 'ul': return b.items.map(x => `- ${printInline(x).replace(/\n/g, ' ')}`).join('\n');
144
+ case 'ol': return b.items.map((x, i) => `${i + 1}. ${printInline(x).replace(/\n/g, ' ')}`).join('\n');
145
+ }
146
+ }).join('\n\n');
147
+ }
148
+ /** Markdown with plain text added at its end, in its last paragraph or a new one after a heading or list. */
149
+ export function appendText(src, text) {
150
+ const blocks = parseMd(src);
151
+ const last = blocks[blocks.length - 1];
152
+ if (last?.k === 'p')
153
+ last.kids.push({ k: 'text', text });
154
+ else
155
+ blocks.push({ k: 'p', kids: [{ k: 'text', text }] });
156
+ return printMd(blocks);
157
+ }
158
+ /** Only web and mail links open; anything else (javascript:...) is shown as plain text. */
159
+ export function safeHref(href) {
160
+ return /^(https?:|mailto:)/i.test(href.trim());
161
+ }
@@ -0,0 +1,14 @@
1
+ import { type Runtime } from '../core/index.ts';
2
+ export interface Loader {
3
+ /** Base for resolving the first file: the page URL, or the working directory as a file: URL. */
4
+ base: string;
5
+ /** Reads a module's source by its resolved URL. */
6
+ read: (href: string) => Promise<string>;
7
+ /** Loads a JavaScript module by its resolved URL; the platform's import when not given. */
8
+ importJs?: (href: string) => Promise<Record<string, unknown>>;
9
+ }
10
+ export declare function setLoader(rt: Runtime, loader: Loader): void;
11
+ export declare function defaultLoader(): Loader;
12
+ export declare function addBuiltIn(href: string, src: string): void;
13
+ /** The source built in under a URL, or undefined. */
14
+ export declare function builtInText(href: string): string | undefined;
@@ -0,0 +1,300 @@
1
+ // Modules and local storage.
2
+ //
3
+ // `import %clients.trb` loads a file once per runtime and evaluates it as an
4
+ // object (its top-level set-words are its fields), resolving the path
5
+ // against the file that imports it. The words listed in the module header's
6
+ // `exports:` are also set in the user context, and so is every top-level
7
+ // set-word marked with `export` (as R3):
8
+ //
9
+ // Trebol [exports: [load-clients]]
10
+ // export save-client: func [...] [...]
11
+ //
12
+ // A `.js` file is a JavaScript module instead (js.ts).
13
+ //
14
+ // `do %file` runs a script in the user context each time; `read` gives a
15
+ // file's text and `load %file` its values.
16
+ //
17
+ // Local storage keeps values molded with mold/all, so they load back exact.
18
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
19
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
20
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
21
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
22
+ });
23
+ }
24
+ return path;
25
+ };
26
+ import { K, NONE, UNSET, native, value, text, load, mold, string, context, collectSetWords, bindSeries, bindSelf, copyDeep, setWord, getWord, splice, currentFile, throwError, makeError, scriptStart, LoadError, T, canon, intern, } from "../core/index.js";
27
+ import { jsModule } from "./js.js";
28
+ const loaders = new WeakMap();
29
+ const modules = new WeakMap();
30
+ export function setLoader(rt, loader) {
31
+ loaders.set(rt, loader);
32
+ modules.set(rt, new Map());
33
+ }
34
+ export function defaultLoader() {
35
+ const g = globalThis;
36
+ return {
37
+ base: g.location?.href ?? 'file:///',
38
+ read: async (href) => {
39
+ // in Node, fetch opens no file: URL; asking Node for its module keeps a browser bundle free of it
40
+ const fs = href.startsWith('file:') ? g.process?.getBuiltinModule?.('node:fs/promises') : undefined;
41
+ if (fs !== undefined)
42
+ return fs.readFile(new URL(href), 'utf8');
43
+ const res = await fetch(href);
44
+ if (!res.ok)
45
+ throw new Error(`HTTP ${res.status}`);
46
+ return res.text();
47
+ },
48
+ };
49
+ }
50
+ function resolve(base, from, path) {
51
+ const fromHref = from === null ? base : new URL(from, base).href;
52
+ return new URL(path, fromHref).href;
53
+ }
54
+ const EXPORTS = canon(intern('exports'));
55
+ const EXPORT = canon(intern('export'));
56
+ const TYPE = canon(intern('type'));
57
+ const MODULE = canon(intern('module'));
58
+ /** The value after `name:` in a script header, or null. */
59
+ function headerField(header, name) {
60
+ if (header === null)
61
+ return null;
62
+ const hd = header.s.data;
63
+ for (let i = header.i; i + 1 < hd.length; i++) {
64
+ const c = hd[i];
65
+ if (c.t === K.SetWord && canon(c.sym) === name)
66
+ return hd[i + 1];
67
+ }
68
+ return null;
69
+ }
70
+ /** Takes the `export` marks out of a module body, giving the words they export. */
71
+ function takeExports(body) {
72
+ const out = [];
73
+ const d = body.data;
74
+ for (let i = 0; i < d.length; i++) {
75
+ const c = d[i];
76
+ if (c.t !== K.Word || canon(c.sym) !== EXPORT)
77
+ continue;
78
+ const next = d[i + 1];
79
+ if (next?.t === K.SetWord) {
80
+ out.push({ t: K.Word, sym: next.sym, bind: null });
81
+ splice(body, i, 1, []);
82
+ i--;
83
+ }
84
+ else if (next?.t === K.Block) {
85
+ for (const w of next.s.data)
86
+ if (w.t === K.Word)
87
+ out.push(w);
88
+ splice(body, i, 2, []);
89
+ i--;
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+ function hrefOf(t, loader, path) {
95
+ return resolve(loader.base, currentFile(t), text(path));
96
+ }
97
+ /** Sources built into a bundle (dist/), by URL: they are read without asking the loader. */
98
+ const builtIn = new Map();
99
+ export function addBuiltIn(href, src) {
100
+ builtIn.set(href, src);
101
+ }
102
+ /** The source built in under a URL, or undefined. */
103
+ export function builtInText(href) {
104
+ return builtIn.get(href);
105
+ }
106
+ function readText(loader, href, path) {
107
+ const src = builtIn.get(href);
108
+ if (src !== undefined)
109
+ return Promise.resolve(string(src));
110
+ return loader.read(href).then(src => string(src), (e) => {
111
+ throw makeError('access', 'cannot-open', `cannot open ${mold(path)}: ${e.message}`);
112
+ });
113
+ }
114
+ native('read', '["The text of a file or a web address." source [file! url!]]', (t, f, v) => {
115
+ if (f.phase === 1)
116
+ return value(v);
117
+ const loader = loaders.get(t.rt);
118
+ if (loader === undefined)
119
+ return throwError('access', 'no-loader', 'this host cannot read files');
120
+ f.phase = 1;
121
+ return { k: 'await', p: readText(loader, hrefOf(t, loader, f.args[0]), f.args[0]) };
122
+ });
123
+ native('do-file', '["Runs the script in a file, as do does; a module is imported." file [file! url!]]', (t, f, v) => {
124
+ if (f.phase === 2)
125
+ return value(v);
126
+ const loader = loaders.get(t.rt);
127
+ if (loader === undefined)
128
+ return throwError('access', 'no-loader', 'this host cannot read files');
129
+ if (f.phase === 0) {
130
+ const href = hrefOf(t, loader, f.args[0]);
131
+ f.data = { href };
132
+ f.phase = 1;
133
+ return { k: 'await', p: readText(loader, href, f.args[0]) };
134
+ }
135
+ const { href } = f.data;
136
+ let code;
137
+ try {
138
+ code = load(text(v), { file: href });
139
+ }
140
+ catch (e) {
141
+ // LoadError is the one exception on the normal path; it becomes a value here.
142
+ if (!(e instanceof LoadError))
143
+ throw e;
144
+ return throwError('syntax', 'load', e.message);
145
+ }
146
+ const { header, start } = scriptStart(code);
147
+ f.phase = 2;
148
+ const type = headerField(header, TYPE);
149
+ if (type !== null && type.t === K.Word && canon(type.sym) === MODULE) {
150
+ return { k: 'call', fn: getWord({ t: K.Word, sym: intern('import'), bind: t.rt.lib }), args: [f.args[0]] };
151
+ }
152
+ bindSeries(code.s, t.rt.user, true);
153
+ return { k: 'do', s: code.s, i: start };
154
+ });
155
+ native('import', '["Runs a module and gives its exports." source [file! url! string!]]', (t, f, v) => {
156
+ const rt = t.rt;
157
+ const loader = loaders.get(rt);
158
+ const mods = modules.get(rt);
159
+ if (loader === undefined || mods === undefined)
160
+ return throwError('access', 'no-loader', 'this host cannot load modules');
161
+ if (f.phase === 0) {
162
+ const href = hrefOf(t, loader, f.args[0]);
163
+ const known = mods.get(href);
164
+ if (known !== undefined) {
165
+ if (known.obj !== null)
166
+ return value(known.obj);
167
+ f.phase = 3;
168
+ return { k: 'await', p: known.done };
169
+ }
170
+ let settle = () => { };
171
+ const done = new Promise((ok, fail) => {
172
+ settle = (good, x) => (good ? ok(x) : fail(x));
173
+ });
174
+ done.catch(() => { }); // a failed import is reported to the importer, not as unhandled
175
+ const entry = { obj: null, done, settle };
176
+ mods.set(href, entry);
177
+ f.data = { href, entry, ctx: null, exports: [] };
178
+ if (/\.m?js$/i.test(new URL(href).pathname)) {
179
+ f.phase = 4;
180
+ const load = loader.importJs ?? ((h) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ h)));
181
+ return {
182
+ k: 'await',
183
+ p: load(href).then(ns => {
184
+ const obj = jsModule(ns);
185
+ if (typeof obj === 'string')
186
+ throw makeError('script', 'bad-module', obj);
187
+ return obj;
188
+ }, (e) => {
189
+ throw makeError('access', 'cannot-open', `cannot open ${mold(f.args[0])}: ${e?.message ?? String(e)}`);
190
+ }).then(obj => {
191
+ entry.obj = obj;
192
+ entry.settle(true, obj);
193
+ return obj;
194
+ }, (err) => {
195
+ mods.delete(href);
196
+ entry.settle(false, err);
197
+ throw err;
198
+ }),
199
+ };
200
+ }
201
+ f.phase = 1;
202
+ return {
203
+ k: 'await',
204
+ p: readText(loader, href, f.args[0]).catch((err) => {
205
+ mods.delete(href);
206
+ entry.settle(false, err);
207
+ throw err;
208
+ }),
209
+ };
210
+ }
211
+ if (f.phase === 3 || f.phase === 4)
212
+ return value(v);
213
+ const st = f.data;
214
+ const failed = (e) => {
215
+ mods.delete(st.href);
216
+ st.entry.settle(false, e);
217
+ };
218
+ if (f.phase === 1) {
219
+ let code;
220
+ try {
221
+ code = load(text(v), { file: st.href });
222
+ }
223
+ catch (e) {
224
+ // LoadError is the one exception on the normal path; it becomes a value here.
225
+ if (!(e instanceof LoadError))
226
+ throw e;
227
+ const step = throwError('syntax', 'load', e.message);
228
+ if (step.k === 'throw')
229
+ failed(step.e.v);
230
+ return step;
231
+ }
232
+ const { header, start } = scriptStart(code);
233
+ const listed = headerField(header, EXPORTS);
234
+ if (listed !== null && listed.t === K.Block)
235
+ st.exports = listed.s.data.filter(w => w.t === K.Word);
236
+ const body = copyDeep(code.s, start);
237
+ st.exports.push(...takeExports(body));
238
+ const ctx = context();
239
+ ctx.self = true;
240
+ collectSetWords(body, 0, ctx);
241
+ bindSeries(body, rt.user, true);
242
+ bindSeries(body, ctx);
243
+ bindSelf(body, ctx);
244
+ st.ctx = ctx;
245
+ f.phase = 2;
246
+ f.trap = 1 << T.Error;
247
+ return { k: 'do', s: body, i: 0 };
248
+ }
249
+ // phase 2: the module body ran
250
+ if (f.thrown !== null) {
251
+ const th = f.thrown;
252
+ f.thrown = null;
253
+ failed(th.v);
254
+ return { k: 'throw', e: th };
255
+ }
256
+ const obj = { t: K.Object, ctx: st.ctx };
257
+ for (const w of st.exports) {
258
+ const i = st.ctx.keys.findIndex(k => canon(k) === canon(w.sym));
259
+ if (i < 0) {
260
+ const step = throwError('script', 'bad-export', `${mold(w)} is exported but not defined`);
261
+ if (step.k === 'throw')
262
+ failed(step.e.v);
263
+ return step;
264
+ }
265
+ setWord({ t: K.Word, sym: w.sym, bind: rt.user }, st.ctx.vals[i]);
266
+ }
267
+ st.entry.obj = obj;
268
+ st.entry.settle(true, obj);
269
+ return value(obj);
270
+ });
271
+ const memory = new Map();
272
+ const store = globalThis.localStorage ?? {
273
+ getItem: k => memory.get(k) ?? null,
274
+ setItem: (k, v) => void memory.set(k, v),
275
+ removeItem: k => void memory.delete(k),
276
+ };
277
+ const PREFIX = 'trebol:';
278
+ const keyOf = (c) => PREFIX + (c.t === K.Word || c.t === K.LitWord ? mold({ ...c, t: K.Word }) : text(c));
279
+ native('save-local', '["Keeps a value in the browser, under a key." key [string! word!] value [any-value!]]', (_t, f) => {
280
+ store.setItem(keyOf(f.args[0]), mold(f.args[1], { all: true }));
281
+ return value(f.args[1]);
282
+ });
283
+ native('load-local', '["The value kept in the browser under a key, or none." key [string! word!]]', (_t, f) => {
284
+ const saved = store.getItem(keyOf(f.args[0]));
285
+ if (saved === null)
286
+ return value(NONE);
287
+ try {
288
+ return value(load(saved).s.data[0] ?? NONE);
289
+ }
290
+ catch (e) {
291
+ // a value that no longer loads is treated as missing
292
+ if (e instanceof LoadError)
293
+ return value(NONE);
294
+ throw e;
295
+ }
296
+ });
297
+ native('remove-local', '["Forgets the value kept in the browser under a key." key [string! word!]]', (_t, f) => {
298
+ store.removeItem(keyOf(f.args[0]));
299
+ return value(UNSET);
300
+ });
@@ -0,0 +1,6 @@
1
+ /** Where `print` writes; the browser host points this at the page console. */
2
+ export declare const output: {
3
+ line: (text: string) => void;
4
+ };
5
+ /** Anything cancellable registers here by handle kind. */
6
+ export declare const cancellers: Record<string, (obj: unknown) => void>;
@@ -0,0 +1,98 @@
1
+ // Host natives that are not about the network: console, time, tasks and
2
+ // timers. They work wherever there is a JS event loop (browser or Node).
3
+ import { K, NONE, UNSET, I64, native, value, form, mold, date, word, pick, throwError, getWord, } from "../core/index.js";
4
+ import { schedulerOf, spawn, spawnHandler, cancelTask, taskResult, makeHandle, handleOf, dropHandle, } from "./scheduler.js";
5
+ /** Where `print` writes; the browser host points this at the page console. */
6
+ export const output = { line: (text) => console.log(text) };
7
+ native('write-line', '["Writes a value and a new line to the output." value [any-type!]]', (_t, f) => {
8
+ output.line(form(f.args[0]));
9
+ return value(UNSET);
10
+ });
11
+ native('probe', '["Prints a value as mold shows it; gives the value." value [any-type!]]', (_t, f) => {
12
+ output.line(mold(f.args[0]));
13
+ return value(f.args[0]);
14
+ });
15
+ /** Milliseconds for a number of seconds or a time!. */
16
+ function millis(c) {
17
+ if (c.t === K.Time)
18
+ return c.v / 1e6;
19
+ if (c.t === K.Integer)
20
+ return I64.toNumber(c.v) * 1000;
21
+ return c.v * 1000;
22
+ }
23
+ // As in R3: whole seconds unless /precise, and one part of the date with the
24
+ // other refinements (now/date, now/weekday, now/time...).
25
+ const NOW_PARTS = ['year', 'month', 'day', 'time', 'zone', 'date', 'weekday', 'yearday'];
26
+ native('now', '["The date and time now." /year /month /day /time /zone /date /weekday /yearday /precise /utc]', (_t, f) => {
27
+ const d = new Date();
28
+ const on = (i) => f.args[i].t === K.Logic;
29
+ const zone = on(9) ? 0 : -d.getTimezoneOffset();
30
+ const local = new Date(d.getTime() + zone * 60000);
31
+ const ns = ((local.getUTCHours() * 60 + local.getUTCMinutes()) * 60 + local.getUTCSeconds()) * 1e9 +
32
+ (on(8) ? local.getUTCMilliseconds() * 1e6 : 0);
33
+ const v = date({ y: local.getUTCFullYear(), m: local.getUTCMonth() + 1, d: local.getUTCDate(), time: ns, zone });
34
+ const part = NOW_PARTS.find((_p, i) => on(i));
35
+ return value(part === undefined ? v : pick(v, word(part)));
36
+ });
37
+ native('wait', '["Waits a number of seconds, or for tasks to finish; other tasks run meanwhile." value [number! time! handle! block!]]', (t, f, v) => {
38
+ if (f.phase === 1)
39
+ return value(v);
40
+ f.phase = 1;
41
+ const x = f.args[0];
42
+ const sch = schedulerOf(t);
43
+ const me = sch.byTask.get(t);
44
+ if (x.t === K.Handle || x.t === K.Block) {
45
+ // words in a block are looked up, as R3 does: wait [a b]
46
+ const handles = x.t === K.Block ? x.s.data.slice(x.i).map(c => (c.t === K.Word ? getWord(c) ?? c : c)) : [x];
47
+ const tasks = handles.map(h => handleOf(h, 'task'));
48
+ if (tasks.some(ht => ht === null))
49
+ return throwError('script', 'bad-wait', 'wait needs tasks or a duration');
50
+ const all = Promise.all(tasks.map(ht => taskResult(ht)));
51
+ return { k: 'await', p: x.t === K.Block ? all.then(vs => ({ t: K.Block, s: { data: vs }, i: 0 })) : all.then(vs => vs[0]) };
52
+ }
53
+ const ms = millis(x);
54
+ return {
55
+ k: 'await',
56
+ p: new Promise(resolve => {
57
+ const id = setTimeout(() => resolve(NONE), ms);
58
+ if (me)
59
+ me.abort = () => clearTimeout(id);
60
+ }),
61
+ };
62
+ });
63
+ native('spawn', '["Starts a task that evaluates a block on its own; gives a handle at once." body [block!]]', (t, f) => {
64
+ const b = f.args[0];
65
+ const ht = spawn(schedulerOf(t), b.s, b.i);
66
+ return value(makeHandle('task', ht));
67
+ });
68
+ native('delay', '["Evaluates a block once, after a while; gives a handle." time [number! time!] body [block!]]', (t, f) => {
69
+ const sch = schedulerOf(t);
70
+ const body = f.args[1];
71
+ const id = setTimeout(() => spawnHandler(sch, body, {}), millis(f.args[0]));
72
+ return value(makeHandle('timer', { stop: () => clearTimeout(id) }));
73
+ });
74
+ native('every', '["Evaluates a block again and again, every so often; gives a handle." time [number! time!] body [block!]]', (t, f) => {
75
+ const sch = schedulerOf(t);
76
+ const body = f.args[1];
77
+ const id = setInterval(() => spawnHandler(sch, body, {}), Math.max(1, millis(f.args[0])));
78
+ return value(makeHandle('timer', { stop: () => clearInterval(id) }));
79
+ });
80
+ /** Anything cancellable registers here by handle kind. */
81
+ export const cancellers = {
82
+ timer: obj => obj.stop(),
83
+ };
84
+ native('cancel', '["Stops a task, timer or request." target [handle!]]', (t, f) => {
85
+ const h = f.args[0];
86
+ const kind = h.p.kind;
87
+ if (kind === 'task') {
88
+ const ht = handleOf(h, 'task');
89
+ if (ht !== null)
90
+ cancelTask(schedulerOf(t), ht);
91
+ return value(UNSET);
92
+ }
93
+ const obj = handleOf(h, kind);
94
+ if (obj !== null)
95
+ cancellers[kind]?.(obj);
96
+ dropHandle(h);
97
+ return value(UNSET);
98
+ });
@@ -0,0 +1,12 @@
1
+ import { type Cell } from '../core/index.ts';
2
+ /** A handle for a file the user chose. */
3
+ export declare function fileHandle(file: Blob): Cell;
4
+ /** Where `download` hands a file; false when this host has no browser. Tests point it elsewhere. */
5
+ export declare const saver: {
6
+ save: (name: string, blob: Blob) => boolean;
7
+ };
8
+ /**
9
+ * The file name a server gives in content-disposition: filename*=UTF-8''... (which
10
+ * carries accents) wins over filename=...; '' when there is none.
11
+ */
12
+ export declare function dispositionName(header: string): string;