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,93 @@
1
+ Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
Binary file
@@ -0,0 +1,39 @@
1
+ // Inter, the font of the default theme, as variable woff2 files in fonts/:
2
+ // one per script, so a browser downloads only those its text needs (the
3
+ // unicode-range of each face). They come from @fontsource-variable/inter
4
+ // 5.3.0, under the SIL Open Font License (fonts/OFL.txt).
5
+ //
6
+ // trebol.js declares them with addresses next to itself; a page made by
7
+ // `trebol build` carries the files inside and declares them in its own
8
+ // <style data-tb-fonts>, which the host then leaves alone.
9
+
10
+ export interface FontFile {
11
+ /** File name in fonts/. */
12
+ file: string;
13
+ /** The characters the file has, as CSS unicode-range. */
14
+ range: string;
15
+ }
16
+
17
+ // The order of @fontsource: where ranges overlap, the last face declared wins.
18
+ export const INTER: readonly FontFile[] = [
19
+ { file: 'inter-cyrillic-ext.woff2', range: 'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F' },
20
+ { file: 'inter-cyrillic.woff2', range: 'U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116' },
21
+ { file: 'inter-greek-ext.woff2', range: 'U+1F00-1FFF' },
22
+ { file: 'inter-greek.woff2', range: 'U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF' },
23
+ { file: 'inter-vietnamese.woff2', range: 'U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB' },
24
+ { file: 'inter-latin-ext.woff2', range: 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF' },
25
+ { file: 'inter-latin.woff2', range: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD' },
26
+ ];
27
+
28
+ /** The @font-face rules of Inter, each file at the address `src` gives it. */
29
+ export function interCss(src: (file: string) => string, faces: readonly FontFile[] = INTER): string {
30
+ return faces.map(f => `@font-face { font-family: Inter; font-style: normal; font-weight: 100 900; font-display: swap; src: url(${src(f.file)}) format("woff2"); unicode-range: ${f.range}; }`).join('\n');
31
+ }
32
+
33
+ /** Whether a code point is in a unicode-range. */
34
+ export function inRange(range: string, cp: number): boolean {
35
+ return range.split(',').some(r => {
36
+ const [lo, hi] = r.slice(2).split('-').map(h => parseInt(h, 16));
37
+ return cp >= lo! && cp <= (hi ?? lo!);
38
+ });
39
+ }
package/src/host/index.ts CHANGED
@@ -36,14 +36,14 @@ fetch: func [
36
36
  ]
37
37
 
38
38
  show-progress: func [
39
- "Shows how far a request went on a face: a progress bar's value, or the bar of an upload."
39
+ "Shows how far a request went on a face: a progress bar's value, or the bar of an upload or a photo."
40
40
  face [object!]
41
41
  done [integer! none!] "Bytes done; none once the request is over"
42
42
  total [integer! none!] "Bytes in all, when known"
43
43
  /local part
44
44
  ][
45
45
  part: either all [done total total > 0] [done / to decimal! total] [none]
46
- either 'upload = select face 'style [face/sent: part] [if done [face/value: part]]
46
+ either find [upload photo] select face 'style [face/sent: part] [if done [face/value: part]]
47
47
  ]
48
48
 
49
49
  save: func [
@@ -194,8 +194,10 @@ export function startHost(opts: HostOptions = {}): Host {
194
194
  export const UI_SOURCE = new URL('../ui/ui.trb', import.meta.url).href;
195
195
  /** URL of the languages module (i18n, tr, translated). */
196
196
  export const I18N_SOURCE = new URL('../ui/i18n.trb', import.meta.url).href;
197
+ /** URL of the words of screen tests (click, type, see...), which `trebol test` loads. */
198
+ export const TEST_SOURCE = new URL('../ui/test.trb', import.meta.url).href;
197
199
  // Trebol's own code: its errors point at the program's call (see LIBRARY_FILES).
198
- LIBRARY_FILES.add('host').add(UI_SOURCE).add(I18N_SOURCE);
200
+ LIBRARY_FILES.add('host').add(UI_SOURCE).add(I18N_SOURCE).add(TEST_SOURCE);
199
201
 
200
202
  /** Loads languages and the UI dialect (view, layout, stylize, theme...) into the user context. */
201
203
  export function startUi(host: Host): Promise<Cell> {
package/src/host/js.ts ADDED
@@ -0,0 +1,127 @@
1
+ // JavaScript modules as Trebol modules.
2
+ //
3
+ // `import %pdf-tools.js` loads a JavaScript module and gives an object with a
4
+ // function for each function it exports, named in Trebol's way (countPages is
5
+ // count-pages), and the other exports as values:
6
+ //
7
+ // pdf: import %pdf-tools.js
8
+ // pages: pdf/count-pages %contract.pdf
9
+ //
10
+ // Arguments and results cross as JSON, so text, numbers, blocks, maps, logic
11
+ // and none keep their shape; a promise is awaited while other tasks run, and
12
+ // a JavaScript exception is a Trebol error. A function's spec comes from its
13
+ // parameters, or from a `spec` property written as Trebol source:
14
+ //
15
+ // export function countPages(file) { ... }
16
+ // countPages.spec = '["The pages of a PDF." file [file! url!]]';
17
+ //
18
+ // No Trebol value holds the JavaScript function: each is a native built on one
19
+ // hidden native, carrying the function's index in a table here as its data.
20
+
21
+ import {
22
+ K, NONE, registerNative, load, parseSpec, parseJson, toJson, context, ctxAdd, intern, makeError, value, throwError,
23
+ type Cell, type BlockCell, type ObjectCell, type NativeDef, type Step,
24
+ } from '../core/index.ts';
25
+
26
+ type JsFunction = (...args: unknown[]) => unknown;
27
+
28
+ const functions: JsFunction[] = [];
29
+
30
+ const call = registerNative({
31
+ name: 'js-function', hidden: true, spec: parseSpec(load('[]').s.data[0] as BlockCell) as NativeDef['spec'],
32
+ specBlock: load('[]').s.data[0] as BlockCell,
33
+ }, (_t, f, v): Step => {
34
+ if (f.phase === 1) return value(v!);
35
+ const fn = functions[f.def.data!]!;
36
+ const name = f.def.name;
37
+ let result: unknown;
38
+ try {
39
+ result = fn(...f.args.map(a => JSON.parse(toJson(a)) as unknown));
40
+ } catch (e) {
41
+ return throwError('script', 'js-error', `${name}: ${(e as Error)?.message ?? String(e)}`);
42
+ }
43
+ if (!(result instanceof Promise)) return toTrebol(result, name);
44
+ f.phase = 1;
45
+ return {
46
+ k: 'await',
47
+ p: result.then(r => {
48
+ const step = toTrebol(r, name);
49
+ if (step.k === 'value') return step.v;
50
+ throw (step as Extract<Step, { k: 'throw' }>).e.v;
51
+ }, (e: unknown) => {
52
+ throw makeError('script', 'js-error', `${name}: ${(e as Error)?.message ?? String(e)}`);
53
+ }),
54
+ };
55
+ }).p as NativeDef;
56
+
57
+ function toTrebol(r: unknown, name: string): Step {
58
+ if (r === undefined) return value(NONE);
59
+ let json: string | undefined;
60
+ try {
61
+ json = JSON.stringify(r);
62
+ } catch {
63
+ json = undefined;
64
+ }
65
+ if (json === undefined) return throwError('script', 'js-error', `${name} gave a value that is not JSON`);
66
+ const v = parseJson(json);
67
+ return typeof v === 'string' ? throwError('script', 'js-error', `${name}: ${v}`) : value(v);
68
+ }
69
+
70
+ /** countPages is count-pages, as Trebol names words. */
71
+ export function trebolName(js: string): string {
72
+ return js.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/_/g, '-').toLowerCase();
73
+ }
74
+
75
+ /** The parameter names of a plain function or an arrow, or none when they cannot be read. */
76
+ function params(fn: JsFunction): string[] | null {
77
+ const src = fn.toString();
78
+ const m = /^\s*(?:async\s+)?([\w$]+)\s*=>/.exec(src) ?? /^[^(=]*\(([^)]*)\)/.exec(src);
79
+ if (m === null) return null;
80
+ const names = m[1]!.split(',').map(p => p.trim()).filter(p => p !== '');
81
+ return names.every(p => /^[A-Za-z_$][\w$]*$/.test(p)) ? names.map(trebolName) : null;
82
+ }
83
+
84
+ function specOf(fn: JsFunction, name: string): { spec: NativeDef['spec']; specBlock: BlockCell } | string {
85
+ const own = (fn as { spec?: unknown }).spec;
86
+ const src = typeof own === 'string' ? own
87
+ : `[${(params(fn) ?? Array.from({ length: fn.length }, (_, i) => `arg${i + 1}`)).join(' ')}]`;
88
+ let specBlock: BlockCell;
89
+ try {
90
+ specBlock = load(src).s.data[0] as BlockCell;
91
+ } catch (e) {
92
+ return `${name}: bad spec: ${(e as Error).message}`;
93
+ }
94
+ if (specBlock?.t !== K.Block) return `${name}: its spec is not a block`;
95
+ const spec = parseSpec(specBlock);
96
+ return typeof spec === 'string' ? `${name}: ${spec}` : { spec, specBlock };
97
+ }
98
+
99
+ /** The object for a loaded JavaScript module, or an error message. */
100
+ export function jsModule(ns: Record<string, unknown>): ObjectCell | string {
101
+ const ctx = context();
102
+ ctx.self = true;
103
+ for (const [key, x] of Object.entries(ns)) {
104
+ if (key === 'default') continue;
105
+ const name = trebolName(key);
106
+ let v: Cell;
107
+ if (typeof x === 'function') {
108
+ const spec = specOf(x as JsFunction, name);
109
+ if (typeof spec === 'string') return spec;
110
+ functions.push(x as JsFunction);
111
+ v = { t: K.Native, p: { ...call, ...spec, name, data: functions.length - 1, hidden: true } satisfies NativeDef };
112
+ } else {
113
+ let json: string | undefined;
114
+ try {
115
+ json = JSON.stringify(x);
116
+ } catch {
117
+ json = undefined;
118
+ }
119
+ if (json === undefined) continue;
120
+ const parsed = parseJson(json);
121
+ if (typeof parsed === 'string') continue;
122
+ v = parsed;
123
+ }
124
+ ctxAdd(ctx, intern(name), v);
125
+ }
126
+ return { t: K.Object, ctx };
127
+ }
@@ -144,6 +144,15 @@ export function printMd(blocks: Block[]): string {
144
144
  }).join('\n\n');
145
145
  }
146
146
 
147
+ /** Markdown with plain text added at its end, in its last paragraph or a new one after a heading or list. */
148
+ export function appendText(src: string, text: string): string {
149
+ const blocks = parseMd(src);
150
+ const last = blocks[blocks.length - 1];
151
+ if (last?.k === 'p') last.kids.push({ k: 'text', text });
152
+ else blocks.push({ k: 'p', kids: [{ k: 'text', text }] });
153
+ return printMd(blocks);
154
+ }
155
+
147
156
  /** Only web and mail links open; anything else (javascript:...) is shown as plain text. */
148
157
  export function safeHref(href: string): boolean {
149
158
  return /^(https?:|mailto:)/i.test(href.trim());
@@ -9,6 +9,8 @@
9
9
  // Trebol [exports: [load-clients]]
10
10
  // export save-client: func [...] [...]
11
11
  //
12
+ // A `.js` file is a JavaScript module instead (js.ts).
13
+ //
12
14
  // `do %file` runs a script in the user context each time; `read` gives a
13
15
  // file's text and `load %file` its values.
14
16
  //
@@ -19,12 +21,15 @@ import {
19
21
  copyDeep, setWord, getWord, splice, currentFile, throwError, makeError, scriptStart, LoadError, T, canon, intern,
20
22
  type Cell, type BlockCell, type StringCell, type ObjectCell, type Runtime, type WordCell, type Series, type Task,
21
23
  } from '../core/index.ts';
24
+ import { jsModule } from './js.ts';
22
25
 
23
26
  export interface Loader {
24
27
  /** Base for resolving the first file: the page URL, or the working directory as a file: URL. */
25
28
  base: string;
26
29
  /** Reads a module's source by its resolved URL. */
27
30
  read: (href: string) => Promise<string>;
31
+ /** Loads a JavaScript module by its resolved URL; the platform's import when not given. */
32
+ importJs?: (href: string) => Promise<Record<string, unknown>>;
28
33
  }
29
34
 
30
35
  interface ModuleEntry {
@@ -42,10 +47,17 @@ export function setLoader(rt: Runtime, loader: Loader): void {
42
47
  }
43
48
 
44
49
  export function defaultLoader(): Loader {
45
- const g = globalThis as { location?: { href: string } };
50
+ type ReadFile = (path: URL, encoding: 'utf8') => Promise<string>;
51
+ const g = globalThis as {
52
+ location?: { href: string };
53
+ process?: { getBuiltinModule?: (name: string) => { readFile: ReadFile } | undefined };
54
+ };
46
55
  return {
47
56
  base: g.location?.href ?? 'file:///',
48
57
  read: async href => {
58
+ // in Node, fetch opens no file: URL; asking Node for its module keeps a browser bundle free of it
59
+ const fs = href.startsWith('file:') ? g.process?.getBuiltinModule?.('node:fs/promises') : undefined;
60
+ if (fs !== undefined) return fs.readFile(new URL(href), 'utf8');
49
61
  const res = await fetch(href);
50
62
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
51
63
  return res.text();
@@ -106,6 +118,11 @@ export function addBuiltIn(href: string, src: string): void {
106
118
  builtIn.set(href, src);
107
119
  }
108
120
 
121
+ /** The source built in under a URL, or undefined. */
122
+ export function builtInText(href: string): string | undefined {
123
+ return builtIn.get(href);
124
+ }
125
+
109
126
  function readText(loader: Loader, href: string, path: Cell): Promise<Cell> {
110
127
  const src = builtIn.get(href);
111
128
  if (src !== undefined) return Promise.resolve(string(src));
@@ -176,6 +193,28 @@ native('import', '["Runs a module and gives its exports." source [file! url! str
176
193
  const entry: ModuleEntry = { obj: null, done, settle };
177
194
  mods.set(href, entry);
178
195
  f.data = { href, entry, ctx: null, exports: [] } satisfies ImportState;
196
+ if (/\.m?js$/i.test(new URL(href).pathname)) {
197
+ f.phase = 4;
198
+ const load = loader.importJs ?? ((h: string) => import(/* @vite-ignore */ h) as Promise<Record<string, unknown>>);
199
+ return {
200
+ k: 'await',
201
+ p: load(href).then(ns => {
202
+ const obj = jsModule(ns);
203
+ if (typeof obj === 'string') throw makeError('script', 'bad-module', obj);
204
+ return obj;
205
+ }, (e: unknown) => {
206
+ throw makeError('access', 'cannot-open', `cannot open ${mold(f.args[0]!)}: ${(e as Error)?.message ?? String(e)}`);
207
+ }).then(obj => {
208
+ entry.obj = obj;
209
+ entry.settle(true, obj);
210
+ return obj;
211
+ }, (err: unknown) => {
212
+ mods.delete(href);
213
+ entry.settle(false, err as Cell);
214
+ throw err;
215
+ }),
216
+ };
217
+ }
179
218
  f.phase = 1;
180
219
  return {
181
220
  k: 'await',
@@ -186,7 +225,7 @@ native('import', '["Runs a module and gives its exports." source [file! url! str
186
225
  }),
187
226
  };
188
227
  }
189
- if (f.phase === 3) return value(v!);
228
+ if (f.phase === 3 || f.phase === 4) return value(v!);
190
229
  const st = f.data as ImportState;
191
230
  const failed = (e: Cell) => {
192
231
  mods.delete(st.href);
package/src/host/net.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  } from '../core/index.ts';
13
13
  import { schedulerOf, spawn, spawnHandler, makeHandle, handleOf, type Scheduler } from './scheduler.ts';
14
14
  import { cancellers } from './natives.ts';
15
+ import { devLog } from './devlog.ts';
15
16
 
16
17
  // --- files -----------------------------------------------------------------------
17
18
  //
@@ -164,7 +165,8 @@ function decodeBody(type: string, bytes: Uint8Array): Cell {
164
165
  const r = parseJson(new TextDecoder().decode(bytes));
165
166
  return typeof r === 'string' ? string(new TextDecoder().decode(bytes)) : r;
166
167
  }
167
- if (/^text\/|xml|javascript|x-www-form-urlencoded/i.test(type) || type === '') {
168
+ // xml only as the subtype or its +xml suffix: the type of an Excel file (…openxmlformats…) is binary
169
+ if (/^text\/|^[^;]*\/(?:xml|[^;]*\+xml)\s*(?:;|$)|javascript|x-www-form-urlencoded/i.test(type) || type === '') {
168
170
  return string(new TextDecoder().decode(bytes));
169
171
  }
170
172
  return { t: K.Binary, s: { data: [...bytes] }, i: 0 };
@@ -339,11 +341,15 @@ native('http-request', '["Sends an HTTP request; used by fetch." url [url! strin
339
341
  const watch = field(opts, 'progress');
340
342
  const shown = watch === null ? null : progressOf(t, watch);
341
343
  const p = (async (): Promise<Cell> => {
344
+ const started = Date.now();
345
+ let status: number | null = null;
346
+ let problem: string | null = null;
342
347
  try {
343
348
  const init: RequestInit = { method: verb, headers, body, credentials, signal: ctl.signal };
344
349
  const res = shown !== null && typeof XMLHttpRequest !== 'undefined'
345
350
  ? await sendXhr(url, init, shown.tell)
346
351
  : await sendFetch(url, init, shown === null ? null : shown.tell);
352
+ status = res.status;
347
353
  const type = res.headers.find(([k]) => k === 'content-type')?.[1] ?? '';
348
354
  const data = decodeBody(type, res.bytes);
349
355
  if (full) {
@@ -362,12 +368,14 @@ native('http-request', '["Sends an HTTP request; used by fetch." url [url! strin
362
368
  return data;
363
369
  } catch (e) {
364
370
  if ((e as Cell).t === K.Error) throw e;
371
+ problem = timedOut ? 'timed out' : ctl.signal.aborted ? 'cancelled' : (e as Error).message;
365
372
  if (timedOut) throw makeError('access', 'timeout', `request to ${url} timed out`);
366
373
  if (ctl.signal.aborted) throw makeError('access', 'cancelled', `request to ${url} was cancelled`);
367
374
  throw makeError('access', 'network', `cannot reach ${url}: ${(e as Error).message}`);
368
375
  } finally {
369
376
  if (timer !== null) clearTimeout(timer);
370
377
  shown?.end();
378
+ devLog.request(verb, url, status, Date.now() - started, problem);
371
379
  }
372
380
  })();
373
381
  return { k: 'await', p };