@lincyaw/addon-exec-wasi 0.0.0-stage → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/LICENSES +326 -0
- package/README.md +32 -2
- package/package.json +44 -3
- package/src/client/env.d.ts +7 -0
- package/src/client/executors.ts +56 -0
- package/src/client/index.ts +5 -0
- package/src/client/messages.ts +26 -0
- package/src/client/plugin.ts +35 -0
- package/src/client/protocol.ts +12 -0
- package/src/client/wasi.worker.ts +28 -0
- package/src/domain/config.ts +29 -0
- package/src/domain/index.ts +2 -0
- package/src/node/executor.ts +61 -0
- package/src/node/presmium.ts +35 -0
- package/src/node/runtime.ts +45 -0
- package/src/node/runtimes.ts +24 -0
- package/src/node/vite.ts +27 -0
- package/src/node/wasi-main.mjs +30 -0
- package/src/node/wasi-thread.mjs +15 -0
- package/src/shared/wasi-runner.d.mts +25 -0
- package/src/shared/wasi-runner.mjs +153 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/LICENSES
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
Licenses of the WebAssembly runtimes in this directory
|
|
2
|
+
=======================================================
|
|
3
|
+
|
|
4
|
+
Presmium publishes these files with a deck whose code runs C, C++, Ruby or
|
|
5
|
+
SQL in the browser (only the runtimes that code needs). They are the
|
|
6
|
+
binaries of the Runno project as @runno/sandbox 0.10.2 ships them
|
|
7
|
+
(https://runno.dev, https://github.com/taybenlor/runno), unchanged:
|
|
8
|
+
|
|
9
|
+
clang.wasm, wasm-ld.wasm, clang-fs.tar.gz
|
|
10
|
+
Clang and wasm-ld of LLVM 8.0.1, and a WASI sysroot (wasi-libc,
|
|
11
|
+
libc++, libc++abi and the compiler runtime of LLVM).
|
|
12
|
+
LLVM 8: the University of Illinois/NCSA Open Source License (below);
|
|
13
|
+
libc++ and libc++abi are also under the MIT License. LLVM 9 and later
|
|
14
|
+
are under the Apache License 2.0 with LLVM Exceptions (below), as is
|
|
15
|
+
wasi-libc (also under the Apache License 2.0 or the MIT License; its
|
|
16
|
+
musl part under the MIT License).
|
|
17
|
+
https://releases.llvm.org/8.0.1/LICENSE.TXT
|
|
18
|
+
https://github.com/WebAssembly/wasi-libc/blob/main/LICENSE
|
|
19
|
+
|
|
20
|
+
ruby-3.2.0.wasm, ruby-3.2.0.tar.gz
|
|
21
|
+
Ruby 3.2.0 (ruby.wasm). Ruby is copyrighted free software by Yukihiro
|
|
22
|
+
Matsumoto, under the 2-clause BSD License (below) or the Ruby License.
|
|
23
|
+
https://www.ruby-lang.org/en/about/license.txt
|
|
24
|
+
|
|
25
|
+
sqlite.wasm
|
|
26
|
+
SQLite, in the public domain:
|
|
27
|
+
The author disclaims copyright to this source code. In place of
|
|
28
|
+
a legal notice, here is a blessing:
|
|
29
|
+
May you do good and not evil.
|
|
30
|
+
May you find forgiveness for yourself and forgive others.
|
|
31
|
+
May you share freely, never taking more than you give.
|
|
32
|
+
https://sqlite.org/copyright.html
|
|
33
|
+
|
|
34
|
+
The Runno project (@runno/sandbox, @runno/wasi), under the MIT License:
|
|
35
|
+
|
|
36
|
+
MIT License
|
|
37
|
+
|
|
38
|
+
Copyright (c) Benjamin Taylor (me@taybenlor.com) and its affiliates.
|
|
39
|
+
|
|
40
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
41
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
42
|
+
in the Software without restriction, including without limitation the rights
|
|
43
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
44
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
45
|
+
furnished to do so, subject to the following conditions:
|
|
46
|
+
|
|
47
|
+
The above copyright notice and this permission notice shall be included in all
|
|
48
|
+
copies or substantial portions of the Software.
|
|
49
|
+
|
|
50
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
51
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
52
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
53
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
54
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
55
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
56
|
+
SOFTWARE.
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
==============================================================================
|
|
60
|
+
University of Illinois/NCSA Open Source License (LLVM 8)
|
|
61
|
+
==============================================================================
|
|
62
|
+
|
|
63
|
+
Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
|
|
64
|
+
All rights reserved.
|
|
65
|
+
|
|
66
|
+
Developed by:
|
|
67
|
+
|
|
68
|
+
LLVM Team
|
|
69
|
+
|
|
70
|
+
University of Illinois at Urbana-Champaign
|
|
71
|
+
|
|
72
|
+
http://llvm.org
|
|
73
|
+
|
|
74
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
75
|
+
this software and associated documentation files (the "Software"), to deal with
|
|
76
|
+
the Software without restriction, including without limitation the rights to
|
|
77
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
78
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
79
|
+
so, subject to the following conditions:
|
|
80
|
+
|
|
81
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
82
|
+
this list of conditions and the following disclaimers.
|
|
83
|
+
|
|
84
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
85
|
+
this list of conditions and the following disclaimers in the
|
|
86
|
+
documentation and/or other materials provided with the distribution.
|
|
87
|
+
|
|
88
|
+
* Neither the names of the LLVM Team, University of Illinois at
|
|
89
|
+
Urbana-Champaign, nor the names of its contributors may be used to
|
|
90
|
+
endorse or promote products derived from this Software without specific
|
|
91
|
+
prior written permission.
|
|
92
|
+
|
|
93
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
94
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
95
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
96
|
+
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
97
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
98
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
|
|
99
|
+
SOFTWARE.
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
==============================================================================
|
|
103
|
+
2-clause BSD License (Ruby)
|
|
104
|
+
==============================================================================
|
|
105
|
+
|
|
106
|
+
Copyright (C) 1993-2013 Yukihiro Matsumoto. All rights reserved.
|
|
107
|
+
|
|
108
|
+
Redistribution and use in source and binary forms, with or without
|
|
109
|
+
modification, are permitted provided that the following conditions
|
|
110
|
+
are met:
|
|
111
|
+
1. Redistributions of source code must retain the above copyright
|
|
112
|
+
notice, this list of conditions and the following disclaimer.
|
|
113
|
+
2. Redistributions in binary form must reproduce the above copyright
|
|
114
|
+
notice, this list of conditions and the following disclaimer in the
|
|
115
|
+
documentation and/or other materials provided with the distribution.
|
|
116
|
+
|
|
117
|
+
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
|
118
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
119
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
120
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
|
121
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
122
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
|
123
|
+
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
|
124
|
+
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
|
125
|
+
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
|
126
|
+
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
|
127
|
+
SUCH DAMAGE.
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
==============================================================================
|
|
131
|
+
Apache License 2.0 with LLVM Exceptions (LLVM 9 and later, wasi-libc)
|
|
132
|
+
==============================================================================
|
|
133
|
+
|
|
134
|
+
Apache License
|
|
135
|
+
Version 2.0, January 2004
|
|
136
|
+
http://www.apache.org/licenses/
|
|
137
|
+
|
|
138
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
139
|
+
|
|
140
|
+
1. Definitions.
|
|
141
|
+
|
|
142
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
143
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
144
|
+
|
|
145
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
146
|
+
the copyright owner that is granting the License.
|
|
147
|
+
|
|
148
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
149
|
+
other entities that control, are controlled by, or are under common
|
|
150
|
+
control with that entity. For the purposes of this definition,
|
|
151
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
152
|
+
direction or management of such entity, whether by contract or
|
|
153
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
154
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
155
|
+
|
|
156
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
157
|
+
exercising permissions granted by this License.
|
|
158
|
+
|
|
159
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
160
|
+
including but not limited to software source code, documentation
|
|
161
|
+
source, and configuration files.
|
|
162
|
+
|
|
163
|
+
"Object" form shall mean any form resulting from mechanical
|
|
164
|
+
transformation or translation of a Source form, including but
|
|
165
|
+
not limited to compiled object code, generated documentation,
|
|
166
|
+
and conversions to other media types.
|
|
167
|
+
|
|
168
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
169
|
+
Object form, made available under the License, as indicated by a
|
|
170
|
+
copyright notice that is included in or attached to the work
|
|
171
|
+
(an example is provided in the Appendix below).
|
|
172
|
+
|
|
173
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
174
|
+
form, that is based on (or derived from) the Work and for which the
|
|
175
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
176
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
177
|
+
of this License, Derivative Works shall not include works that remain
|
|
178
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
179
|
+
the Work and Derivative Works thereof.
|
|
180
|
+
|
|
181
|
+
"Contribution" shall mean any work of authorship, including
|
|
182
|
+
the original version of the Work and any modifications or additions
|
|
183
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
184
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
185
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
186
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
187
|
+
means any form of electronic, verbal, or written communication sent
|
|
188
|
+
to the Licensor or its representatives, including but not limited to
|
|
189
|
+
communication on electronic mailing lists, source code control systems,
|
|
190
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
191
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
192
|
+
excluding communication that is conspicuously marked or otherwise
|
|
193
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
194
|
+
|
|
195
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
196
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
197
|
+
subsequently incorporated within the Work.
|
|
198
|
+
|
|
199
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
200
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
201
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
202
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
203
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
204
|
+
Work and such Derivative Works in Source or Object form.
|
|
205
|
+
|
|
206
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
207
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
208
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
209
|
+
(except as stated in this section) patent license to make, have made,
|
|
210
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
211
|
+
where such license applies only to those patent claims licensable
|
|
212
|
+
by such Contributor that are necessarily infringed by their
|
|
213
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
214
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
215
|
+
institute patent litigation against any entity (including a
|
|
216
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
217
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
218
|
+
or contributory patent infringement, then any patent licenses
|
|
219
|
+
granted to You under this License for that Work shall terminate
|
|
220
|
+
as of the date such litigation is filed.
|
|
221
|
+
|
|
222
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
223
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
224
|
+
modifications, and in Source or Object form, provided that You
|
|
225
|
+
meet the following conditions:
|
|
226
|
+
|
|
227
|
+
(a) You must give any other recipients of the Work or
|
|
228
|
+
Derivative Works a copy of this License; and
|
|
229
|
+
|
|
230
|
+
(b) You must cause any modified files to carry prominent notices
|
|
231
|
+
stating that You changed the files; and
|
|
232
|
+
|
|
233
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
234
|
+
that You distribute, all copyright, patent, trademark, and
|
|
235
|
+
attribution notices from the Source form of the Work,
|
|
236
|
+
excluding those notices that do not pertain to any part of
|
|
237
|
+
the Derivative Works; and
|
|
238
|
+
|
|
239
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
240
|
+
distribution, then any Derivative Works that You distribute must
|
|
241
|
+
include a readable copy of the attribution notices contained
|
|
242
|
+
within such NOTICE file, excluding those notices that do not
|
|
243
|
+
pertain to any part of the Derivative Works, in at least one
|
|
244
|
+
of the following places: within a NOTICE text file distributed
|
|
245
|
+
as part of the Derivative Works; within the Source form or
|
|
246
|
+
documentation, if provided along with the Derivative Works; or,
|
|
247
|
+
within a display generated by the Derivative Works, if and
|
|
248
|
+
wherever such third-party notices normally appear. The contents
|
|
249
|
+
of the NOTICE file are for informational purposes only and
|
|
250
|
+
do not modify the License. You may add Your own attribution
|
|
251
|
+
notices within Derivative Works that You distribute, alongside
|
|
252
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
253
|
+
that such additional attribution notices cannot be construed
|
|
254
|
+
as modifying the License.
|
|
255
|
+
|
|
256
|
+
You may add Your own copyright statement to Your modifications and
|
|
257
|
+
may provide additional or different license terms and conditions
|
|
258
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
259
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
260
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
261
|
+
the conditions stated in this License.
|
|
262
|
+
|
|
263
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
264
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
265
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
266
|
+
this License, without any additional terms or conditions.
|
|
267
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
268
|
+
the terms of any separate license agreement you may have executed
|
|
269
|
+
with Licensor regarding such Contributions.
|
|
270
|
+
|
|
271
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
272
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
273
|
+
except as required for reasonable and customary use in describing the
|
|
274
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
275
|
+
|
|
276
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
277
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
278
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
279
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
280
|
+
implied, including, without limitation, any warranties or conditions
|
|
281
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
282
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
283
|
+
appropriateness of using or redistributing the Work and assume any
|
|
284
|
+
risks associated with Your exercise of permissions under this License.
|
|
285
|
+
|
|
286
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
287
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
288
|
+
unless required by applicable law (such as deliberate and grossly
|
|
289
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
290
|
+
liable to You for damages, including any direct, indirect, special,
|
|
291
|
+
incidental, or consequential damages of any character arising as a
|
|
292
|
+
result of this License or out of the use or inability to use the
|
|
293
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
294
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
295
|
+
other commercial damages or losses), even if such Contributor
|
|
296
|
+
has been advised of the possibility of such damages.
|
|
297
|
+
|
|
298
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
299
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
300
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
301
|
+
or other liability obligations and/or rights consistent with this
|
|
302
|
+
License. However, in accepting such obligations, You may act only
|
|
303
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
304
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
305
|
+
defend, and hold each Contributor harmless for any liability
|
|
306
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
307
|
+
of your accepting any such warranty or additional liability.
|
|
308
|
+
|
|
309
|
+
END OF TERMS AND CONDITIONS
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
---- LLVM Exceptions to the Apache 2.0 License ----
|
|
313
|
+
|
|
314
|
+
As an exception, if, as a result of your compiling your source code, portions
|
|
315
|
+
of this Software are embedded into an Object form of such source code, you
|
|
316
|
+
may redistribute such embedded portions in such Object form without complying
|
|
317
|
+
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
|
318
|
+
|
|
319
|
+
In addition, if you combine or link compiled forms of this Software with
|
|
320
|
+
software that is licensed under the GPLv2 ("Combined Software") and if a
|
|
321
|
+
court of competent jurisdiction determines that the patent provision (Section
|
|
322
|
+
3), the indemnity provision (Section 9) or other Section of the License
|
|
323
|
+
conflicts with the conditions of the GPLv2, you may retroactively and
|
|
324
|
+
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
|
325
|
+
the License, but only in their entirety and only with respect to the Combined
|
|
326
|
+
Software.
|
package/README.md
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/addon-exec-wasi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Running C, C++, Ruby and SQL in WebAssembly, with the same runtime at build time and in the browser: no toolchain on the build machine, offline in the browser.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add -D @lincyaw/addon-exec-wasi
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Add this package to `metadata.plugins` in the document's `lecture.json`.
|
|
14
|
+
|
|
15
|
+
It is a Presmium plugin: its components work on the web page and in the slides. It needs `@lincyaw/cli` and the renderers in the same project, and declares the Presmium packages it shares with them as peer dependencies (Presmium 1.x).
|
|
16
|
+
|
|
17
|
+
## What it provides
|
|
18
|
+
|
|
19
|
+
- The executor `presmium.wasi` for code blocks in `c`, `cpp`, `ruby` and `sql`.
|
|
20
|
+
- Named environments of `kind: wasi`.
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
`presmium.execWasi.loadTimeoutMs`: how long the browser may take to download a runtime (default 120000). Only code run in the browser makes the build publish the runtime (about 52 MB for C and C++).
|
|
25
|
+
|
|
26
|
+
## Documentation
|
|
27
|
+
|
|
28
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/lecture.json) (Chinese: `site/guide/lecture.json`)
|
|
29
|
+
- [Document contract](https://github.com/Lincyaw/presmium/blob/main/.agents/skills/presmium-author/references/document.md): normalized entities, parameters, states and shared validation
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
Apache-2.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/addon-exec-wasi",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.1",
|
|
4
|
+
"description": "Presmium plugin: run C, C++, Ruby and SQLite programs in WebAssembly, in the browser and at build time",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/addon-exec-wasi"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/addon-exec-wasi#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22.19"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
"./domain": "./src/domain/index.ts",
|
|
25
|
+
"./client": "./src/client/index.ts",
|
|
26
|
+
"./presmium": "./src/node/presmium.ts",
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"LICENSES",
|
|
31
|
+
"src"
|
|
32
|
+
],
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@runno/sandbox": "0.10.2",
|
|
35
|
+
"@runno/wasi": "0.10.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@lincyaw/host": "^1.0.0-rc.1",
|
|
39
|
+
"@lincyaw/kernel": "^1.0.0-rc.1"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@lincyaw/host": "1.0.0-rc.1",
|
|
43
|
+
"@lincyaw/cli": "1.0.0-rc.1",
|
|
44
|
+
"@lincyaw/kernel": "1.0.0-rc.1",
|
|
45
|
+
"@lincyaw/render-notebook": "1.0.0-rc.1"
|
|
46
|
+
}
|
|
6
47
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createResidentWorker } from '@lincyaw/host'
|
|
2
|
+
import { failedRun } from '@lincyaw/kernel'
|
|
3
|
+
import type { Executor, RunRequest, RunResult } from '@lincyaw/kernel'
|
|
4
|
+
import { DEFAULT_TIMEOUT_MS } from '../domain/index.ts'
|
|
5
|
+
import { runsLanguage } from '../shared/wasi-runner.mjs'
|
|
6
|
+
import { messages } from './messages.ts'
|
|
7
|
+
import type { WorkerReply, WorkerRequest } from './protocol.ts'
|
|
8
|
+
|
|
9
|
+
export interface WasiExecutorsOptions {
|
|
10
|
+
runtimeURL: string
|
|
11
|
+
loadTimeoutMs: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The page's WASI executors, which share one resident Worker: it compiles each runtime once. */
|
|
15
|
+
export interface WasiExecutors {
|
|
16
|
+
executor(id: string, languages?: string[]): Executor
|
|
17
|
+
dispose(): void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createWasiExecutors(options: WasiExecutorsOptions): WasiExecutors {
|
|
21
|
+
const resident = createResidentWorker<WorkerRequest, WorkerReply>({
|
|
22
|
+
start: () => new Worker(new URL('./wasi.worker.ts', import.meta.url), { type: 'module', name: 'presmium-wasi' }),
|
|
23
|
+
loadTimeoutMs: options.loadTimeoutMs,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
async function run(id: string, request: RunRequest, signal?: AbortSignal): Promise<RunResult> {
|
|
27
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
28
|
+
const outcome = await resident.send({
|
|
29
|
+
request: { lang: request.lang, code: request.code, stdin: request.stdin, files: request.files ? { ...request.files } : undefined },
|
|
30
|
+
runtimeURL: new URL(options.runtimeURL, location.href).href,
|
|
31
|
+
}, { timeoutMs, signal })
|
|
32
|
+
const t = messages()
|
|
33
|
+
if ('failure' in outcome) {
|
|
34
|
+
switch (outcome.failure) {
|
|
35
|
+
case 'cancelled': return failedRun(id, t.cancelled, outcome.elapsedMs)
|
|
36
|
+
case 'load-timeout': return { ...failedRun(id, t.loadTimeout(options.loadTimeoutMs)), timedOut: true }
|
|
37
|
+
case 'run-timeout': return { ...failedRun(id, t.runTimeout(timeoutMs), outcome.elapsedMs), timedOut: true }
|
|
38
|
+
case 'crashed': return failedRun(id, t.crashed(outcome.error ?? ''), outcome.elapsedMs)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const { reply, elapsedMs } = outcome
|
|
42
|
+
if (reply.type === 'error') return failedRun(id, reply.stage === 'load' ? t.loadFailed(reply.error) : t.crashed(reply.error), elapsedMs)
|
|
43
|
+
const { stdout, stderr, exitCode, outputs } = reply.output
|
|
44
|
+
return { ok: exitCode === 0, stdout, stderr, exitCode, durationMs: elapsedMs, timedOut: false, source: 'live', executorId: id, outputs }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
executor: (id, languages) => ({
|
|
49
|
+
id,
|
|
50
|
+
runsIn: 'browser',
|
|
51
|
+
supports: lang => runsLanguage(lang, languages),
|
|
52
|
+
run: (request, signal) => run(id, request, signal),
|
|
53
|
+
}),
|
|
54
|
+
dispose: () => resident.dispose(),
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createWasiExecutors } from './executors.ts'
|
|
2
|
+
export type { WasiExecutors, WasiExecutorsOptions } from './executors.ts'
|
|
3
|
+
export { MESSAGES, messages } from './messages.ts'
|
|
4
|
+
export type { WasiMessages } from './messages.ts'
|
|
5
|
+
export { execWasiPlugin } from './plugin.ts'
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { currentLocale } from '@lincyaw/host'
|
|
2
|
+
import type { Catalog } from '@lincyaw/host'
|
|
3
|
+
|
|
4
|
+
const zhCN = {
|
|
5
|
+
cancelled: '已取消',
|
|
6
|
+
runTimeout: (ms: number) => `执行超过 ${ms} ms,已停止`,
|
|
7
|
+
loadTimeout: (ms: number) => `WebAssembly 运行时 ${ms} ms 内未加载完成,已停止`,
|
|
8
|
+
loadFailed: (error: string) => `WebAssembly 运行时加载失败:${error}`,
|
|
9
|
+
crashed: (error: string) => `WebAssembly 运行时出错:${error}`,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type WasiMessages = typeof zhCN
|
|
13
|
+
|
|
14
|
+
const en: WasiMessages = {
|
|
15
|
+
cancelled: 'Canceled',
|
|
16
|
+
runTimeout: ms => `Stopped after ${ms} ms`,
|
|
17
|
+
loadTimeout: ms => `The WebAssembly runtime did not load within ${ms} ms; stopped`,
|
|
18
|
+
loadFailed: error => `Couldn’t load the WebAssembly runtime: ${error}`,
|
|
19
|
+
crashed: error => `The WebAssembly runtime failed: ${error}`,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const MESSAGES: Catalog<WasiMessages> = { 'zh-CN': zhCN, en }
|
|
23
|
+
|
|
24
|
+
export function messages(): WasiMessages {
|
|
25
|
+
return MESSAGES[currentLocale()]
|
|
26
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { siteBase } from '@lincyaw/host'
|
|
2
|
+
import { environmentExecutor, EXECUTOR } from '@lincyaw/kernel'
|
|
3
|
+
import type { PluginDefinition } from '@lincyaw/kernel'
|
|
4
|
+
import { version } from '../../package.json'
|
|
5
|
+
import { EXEC_WASI_ID, execWasiConfig, RUNTIME_DIR, WASI_EXECUTOR_ID, WASI_KIND } from '../domain/index.ts'
|
|
6
|
+
import { createWasiExecutors } from './executors.ts'
|
|
7
|
+
import type { WasiExecutors } from './executors.ts'
|
|
8
|
+
|
|
9
|
+
let executors: WasiExecutors | undefined
|
|
10
|
+
|
|
11
|
+
export const execWasiPlugin: PluginDefinition = {
|
|
12
|
+
manifest: {
|
|
13
|
+
id: EXEC_WASI_ID,
|
|
14
|
+
name: { 'zh-CN': 'WebAssembly 运行', en: 'WebAssembly Runner' },
|
|
15
|
+
version,
|
|
16
|
+
kernel: '^1.0.0',
|
|
17
|
+
requires: [{ token: EXECUTOR, optional: true }],
|
|
18
|
+
capabilities: ['exec'],
|
|
19
|
+
},
|
|
20
|
+
setup(ctx) {
|
|
21
|
+
const router = ctx.tryGet(EXECUTOR)
|
|
22
|
+
if (!router) return
|
|
23
|
+
executors?.dispose()
|
|
24
|
+
executors = createWasiExecutors({ runtimeURL: `${siteBase()}${RUNTIME_DIR}`, loadTimeoutMs: execWasiConfig(ctx.config).loadTimeoutMs })
|
|
25
|
+
router.register(executors.executor(WASI_EXECUTOR_ID))
|
|
26
|
+
for (const [name, spec] of Object.entries(ctx.environments ?? {})) {
|
|
27
|
+
if (spec.kind === WASI_KIND) router.register(executors.executor(environmentExecutor(name), spec.languages))
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
dispose() {
|
|
31
|
+
executors?.dispose()
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default execWasiPlugin
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { WasiOutput, WasiRequest } from '../shared/wasi-runner.mjs'
|
|
2
|
+
|
|
3
|
+
export interface WorkerRequest {
|
|
4
|
+
id: number
|
|
5
|
+
request: WasiRequest
|
|
6
|
+
runtimeURL: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type WorkerReply =
|
|
10
|
+
| { id: number, type: 'started' }
|
|
11
|
+
| { id: number, type: 'done', output: WasiOutput }
|
|
12
|
+
| { id: number, type: 'error', stage: 'load' | 'run', error: string }
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
import { prepare, runWasi } from '../shared/wasi-runner.mjs'
|
|
3
|
+
import type { WorkerReply, WorkerRequest } from './protocol.ts'
|
|
4
|
+
|
|
5
|
+
declare const self: DedicatedWorkerGlobalScope
|
|
6
|
+
|
|
7
|
+
const reply = (message: WorkerReply) => self.postMessage(message)
|
|
8
|
+
const reason = (error: unknown) => (error instanceof Error ? error.message : String(error))
|
|
9
|
+
|
|
10
|
+
self.onmessage = async ({ data }: MessageEvent<WorkerRequest>) => {
|
|
11
|
+
const { id, request, runtimeURL } = data
|
|
12
|
+
const load = async (file: string) => {
|
|
13
|
+
const response = await fetch(new URL(file, runtimeURL))
|
|
14
|
+
if (!response.ok) throw new Error(`${file}: HTTP ${response.status}`)
|
|
15
|
+
return new Uint8Array(await response.arrayBuffer())
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
await prepare(request.lang, load)
|
|
19
|
+
} catch (error) {
|
|
20
|
+
return reply({ id, type: 'error', stage: 'load', error: reason(error) })
|
|
21
|
+
}
|
|
22
|
+
reply({ id, type: 'started' })
|
|
23
|
+
try {
|
|
24
|
+
reply({ id, type: 'done', output: await runWasi(request, load) })
|
|
25
|
+
} catch (error) {
|
|
26
|
+
reply({ id, type: 'error', stage: 'run', error: reason(error) })
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { isRecord } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
export const EXEC_WASI_ID = 'presmium.execWasi'
|
|
4
|
+
|
|
5
|
+
export const WASI_EXECUTOR_ID = 'presmium.wasi'
|
|
6
|
+
|
|
7
|
+
export const WASI_KIND = 'wasi'
|
|
8
|
+
|
|
9
|
+
export const RUNTIME_DIR = 'wasi/'
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_TIMEOUT_MS = 10_000
|
|
12
|
+
|
|
13
|
+
export const MEMORY_LIMIT_MB = 1024
|
|
14
|
+
|
|
15
|
+
export interface ExecWasiConfig {
|
|
16
|
+
loadTimeoutMs: number
|
|
17
|
+
runtimes: string[]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_EXEC_WASI_CONFIG: ExecWasiConfig = { loadTimeoutMs: 120_000, runtimes: [] }
|
|
21
|
+
|
|
22
|
+
export function execWasiConfig(raw: unknown): ExecWasiConfig {
|
|
23
|
+
const config = isRecord(raw) ? raw : {}
|
|
24
|
+
const load = config.loadTimeoutMs
|
|
25
|
+
return {
|
|
26
|
+
loadTimeoutMs: typeof load === 'number' && load > 0 ? load : DEFAULT_EXEC_WASI_CONFIG.loadTimeoutMs,
|
|
27
|
+
runtimes: Array.isArray(config.runtimes) ? config.runtimes.filter((r): r is string => typeof r === 'string') : [],
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { failedRun } from '@lincyaw/kernel'
|
|
5
|
+
import type { Executor, RunResult } from '@lincyaw/kernel'
|
|
6
|
+
import { directSandbox, RUN_REQUEST_FILE, runResultFile } from '@lincyaw/kernel/node'
|
|
7
|
+
import { DEFAULT_TIMEOUT_MS, MEMORY_LIMIT_MB } from '../domain/index.ts'
|
|
8
|
+
import type { WasiOutput } from '../shared/wasi-runner.mjs'
|
|
9
|
+
import { runsLanguage } from '../shared/wasi-runner.mjs'
|
|
10
|
+
import { runtimeDir, runtimeFingerprint } from './runtime.ts'
|
|
11
|
+
|
|
12
|
+
const MAIN = fileURLToPath(new URL('./wasi-main.mjs', import.meta.url))
|
|
13
|
+
const LOAD_TIMEOUT_MS = 60_000
|
|
14
|
+
const RESULT = runResultFile(0)
|
|
15
|
+
|
|
16
|
+
function readable(): string[] {
|
|
17
|
+
const wasi = dirname(dirname(createRequire(import.meta.url).resolve('@runno/wasi')))
|
|
18
|
+
return [fileURLToPath(new URL('../..', import.meta.url)), wasi, runtimeDir(), dirname(dirname(process.execPath))]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface WasiMainResult {
|
|
22
|
+
durationMs: number
|
|
23
|
+
output?: WasiOutput
|
|
24
|
+
error?: string
|
|
25
|
+
timedOut?: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Runs WASI programs at compile time, each in a child process whose thread runs the runtime. */
|
|
29
|
+
export function createWasiExecutor(id: string, languages?: string[]): Executor {
|
|
30
|
+
return {
|
|
31
|
+
id,
|
|
32
|
+
supports: lang => runsLanguage(lang, languages),
|
|
33
|
+
fingerprint: runtimeFingerprint,
|
|
34
|
+
async run(request, signal, ctx): Promise<RunResult> {
|
|
35
|
+
if (signal?.aborted) return failedRun(id, 'The run was cancelled')
|
|
36
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
37
|
+
const job = {
|
|
38
|
+
request: { lang: request.lang, code: request.code, stdin: request.stdin, files: request.files, env: { ...ctx?.env } },
|
|
39
|
+
dir: runtimeDir(),
|
|
40
|
+
timeoutMs,
|
|
41
|
+
loadTimeoutMs: LOAD_TIMEOUT_MS,
|
|
42
|
+
}
|
|
43
|
+
const sandbox = ctx?.sandbox ?? directSandbox
|
|
44
|
+
let child
|
|
45
|
+
try {
|
|
46
|
+
child = await sandbox.run({ argv: [process.execPath, `--wasm-max-mem-pages=${MEMORY_LIMIT_MB * 16}`, MAIN, RUN_REQUEST_FILE, RESULT], files: { [RUN_REQUEST_FILE]: JSON.stringify(job) }, collect: [RESULT], env: {}, read: readable(), timeoutMs: LOAD_TIMEOUT_MS + timeoutMs + 10_000, signal })
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return failedRun(id, `the ${sandbox.kind} sandbox failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
49
|
+
}
|
|
50
|
+
if (signal?.aborted) return failedRun(id, 'The run was cancelled')
|
|
51
|
+
let result: WasiMainResult | undefined
|
|
52
|
+
try {
|
|
53
|
+
result = child.files[RESULT] ? JSON.parse(Buffer.from(child.files[RESULT]).toString('utf8')) as WasiMainResult : undefined
|
|
54
|
+
} catch {}
|
|
55
|
+
if (!result) return failedRun(id, child.stderr.trim() || `The WASI runtime ended (${child.exitCode}) before the run did`)
|
|
56
|
+
if (!result.output) return { ...failedRun(id, result.error ?? 'The WASI run failed', result.durationMs), ...result.timedOut ? { timedOut: true } : {} }
|
|
57
|
+
const { stdout, stderr, exitCode, outputs } = result.output
|
|
58
|
+
return { ok: exitCode === 0, stdout, stderr, exitCode, durationMs: result.durationMs, timedOut: false, source: 'live', executorId: id, outputs }
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
import { environmentExecutor } from '@lincyaw/kernel'
|
|
3
|
+
import type { EnvironmentProvider, PresmiumNodePlugin } from '@lincyaw/kernel'
|
|
4
|
+
import { EXEC_WASI_ID, execWasiConfig, WASI_EXECUTOR_ID, WASI_KIND } from '../domain/index.ts'
|
|
5
|
+
import { wasiLanguage } from '../shared/wasi-runner.mjs'
|
|
6
|
+
import { createWasiExecutor } from './executor.ts'
|
|
7
|
+
import { missingRuntime } from './runtime.ts'
|
|
8
|
+
import { runtimesPass } from './runtimes.ts'
|
|
9
|
+
import { wasiAssets } from './vite.ts'
|
|
10
|
+
|
|
11
|
+
const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
|
|
12
|
+
|
|
13
|
+
const languagesOf = (languages: string[] | undefined) => languages?.length ? languages : ['c', 'cpp', 'ruby', 'sql']
|
|
14
|
+
|
|
15
|
+
const wasi: EnvironmentProvider = {
|
|
16
|
+
create(name, spec) {
|
|
17
|
+
return createWasiExecutor(environmentExecutor(name), spec.languages)
|
|
18
|
+
},
|
|
19
|
+
async probe(_name, spec) {
|
|
20
|
+
const problems = languagesOf(spec.languages).map(lang => wasiLanguage(lang) ? missingRuntime(lang) : `no WASI runtime runs ${lang}`)
|
|
21
|
+
return [...new Set(problems.filter(Boolean))].join('; ') || undefined
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const plugin: PresmiumNodePlugin = {
|
|
26
|
+
id: EXEC_WASI_ID,
|
|
27
|
+
version,
|
|
28
|
+
kernel: '^1.0.0',
|
|
29
|
+
passes: [runtimesPass],
|
|
30
|
+
executors: [createWasiExecutor(WASI_EXECUTOR_ID)],
|
|
31
|
+
environments: { [WASI_KIND]: wasi },
|
|
32
|
+
assets: ({ config }) => [wasiAssets(execWasiConfig(config).runtimes)],
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default plugin
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { RUNTIMES, runtimeOf } from '../shared/wasi-runner.mjs'
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url)
|
|
8
|
+
|
|
9
|
+
let found: string | undefined
|
|
10
|
+
|
|
11
|
+
export function runtimeDir(): string {
|
|
12
|
+
if (found) return found
|
|
13
|
+
for (const modules of require.resolve.paths('@runno/sandbox') ?? []) {
|
|
14
|
+
const dir = join(modules, '@runno/sandbox/dist/langs')
|
|
15
|
+
if (existsSync(dir)) return found = dir
|
|
16
|
+
}
|
|
17
|
+
throw new Error('the WASI runtimes (@runno/sandbox) are not installed')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function missingRuntime(lang: string): string | undefined {
|
|
21
|
+
const runtime = runtimeOf(lang)
|
|
22
|
+
if (!runtime) return `no WASI runtime runs ${lang}`
|
|
23
|
+
try {
|
|
24
|
+
const dir = runtimeDir()
|
|
25
|
+
const missing = RUNTIMES[runtime].filter(file => !existsSync(join(dir, file)))
|
|
26
|
+
return missing.length ? `missing runtime files: ${missing.join(', ')}` : undefined
|
|
27
|
+
} catch (error) {
|
|
28
|
+
return error instanceof Error ? error.message : String(error)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const fingerprints = new Map<string, string>()
|
|
33
|
+
|
|
34
|
+
export function runtimeFingerprint(lang: string): string {
|
|
35
|
+
const runtime = runtimeOf(lang)
|
|
36
|
+
if (!runtime) return ''
|
|
37
|
+
let fingerprint = fingerprints.get(runtime)
|
|
38
|
+
if (!fingerprint) {
|
|
39
|
+
const hash = createHash('sha256')
|
|
40
|
+
for (const file of RUNTIMES[runtime]) hash.update(readFileSync(join(runtimeDir(), file)))
|
|
41
|
+
fingerprint = `wasi ${runtime} sha256:${hash.digest('hex').slice(0, 16)}`
|
|
42
|
+
fingerprints.set(runtime, fingerprint)
|
|
43
|
+
}
|
|
44
|
+
return fingerprint
|
|
45
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { docBlocks, environmentExecutor, isRecord } from '@lincyaw/kernel'
|
|
2
|
+
import type { IRPass } from '@lincyaw/kernel'
|
|
3
|
+
import { EXEC_WASI_ID, WASI_EXECUTOR_ID, WASI_KIND } from '../domain/index.ts'
|
|
4
|
+
import { runtimeOf } from '../shared/wasi-runner.mjs'
|
|
5
|
+
|
|
6
|
+
/** Lists in the plugin's configuration the WASI runtimes that the page's live code needs, which the build then copies. */
|
|
7
|
+
export const runtimesPass: IRPass = {
|
|
8
|
+
name: 'presmium.execWasi.runtimes',
|
|
9
|
+
run(doc) {
|
|
10
|
+
const environments = Object.entries(doc.config.execute?.environments ?? {})
|
|
11
|
+
.filter(([, spec]) => spec.kind === WASI_KIND)
|
|
12
|
+
.map(([name]) => environmentExecutor(name))
|
|
13
|
+
const runtimes = new Set<string>()
|
|
14
|
+
for (const { block: { node } } of docBlocks(doc)) {
|
|
15
|
+
if (node.type !== 'code' || !node.run || node.run.when === 'compile') continue
|
|
16
|
+
const { executor, lang } = node.run
|
|
17
|
+
if (executor && executor !== WASI_EXECUTOR_ID && !environments.includes(executor)) continue
|
|
18
|
+
const runtime = runtimeOf(lang)
|
|
19
|
+
if (runtime) runtimes.add(runtime)
|
|
20
|
+
}
|
|
21
|
+
const config = doc.config.presmium[EXEC_WASI_ID]
|
|
22
|
+
doc.config.presmium[EXEC_WASI_ID] = { ...isRecord(config) ? config : {}, runtimes: [...runtimes].sort() }
|
|
23
|
+
},
|
|
24
|
+
}
|
package/src/node/vite.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import type { RuntimeAssets } from '@lincyaw/kernel'
|
|
4
|
+
import { RUNTIME_DIR } from '../domain/index.ts'
|
|
5
|
+
import { RUNTIMES } from '../shared/wasi-runner.mjs'
|
|
6
|
+
import type { Runtime } from '../shared/wasi-runner.mjs'
|
|
7
|
+
import { runtimeDir } from './runtime.ts'
|
|
8
|
+
|
|
9
|
+
const EXTENSION_TYPES: Record<string, string> = { '.wasm': 'application/wasm', '.gz': 'application/gzip' }
|
|
10
|
+
const LICENSES = 'LICENSES'
|
|
11
|
+
const LICENSES_FILE = fileURLToPath(new URL('../../LICENSES', import.meta.url))
|
|
12
|
+
|
|
13
|
+
/** Every WASI runtime at `<base>wasi/`; a build copies those the deck's live code needs, with their licenses. */
|
|
14
|
+
export function wasiAssets(runtimes: readonly string[]): RuntimeAssets {
|
|
15
|
+
const files = [...new Set(runtimes.flatMap(runtime => Object.hasOwn(RUNTIMES, runtime) ? RUNTIMES[runtime as Runtime] : []))]
|
|
16
|
+
const types = Object.fromEntries([
|
|
17
|
+
...Object.values(RUNTIMES).flat().map(file => [file, EXTENSION_TYPES[file.slice(file.lastIndexOf('.'))] ?? 'application/octet-stream']),
|
|
18
|
+
[LICENSES, 'text/plain; charset=utf-8'],
|
|
19
|
+
])
|
|
20
|
+
return {
|
|
21
|
+
name: 'presmium:wasi-runtime',
|
|
22
|
+
prefix: RUNTIME_DIR,
|
|
23
|
+
types,
|
|
24
|
+
emitted: files.length === 0 ? [] : [...files, LICENSES],
|
|
25
|
+
source: file => (file === LICENSES ? LICENSES_FILE : join(runtimeDir(), file)),
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { Worker } from 'node:worker_threads'
|
|
3
|
+
|
|
4
|
+
const [requestFile, resultFile] = process.argv.slice(2)
|
|
5
|
+
const { request, dir, timeoutMs, loadTimeoutMs } = JSON.parse(readFileSync(requestFile, 'utf8'))
|
|
6
|
+
const worker = new Worker(new URL('./wasi-thread.mjs', import.meta.url), { workerData: { request, dir }, env: {} })
|
|
7
|
+
let started = 0
|
|
8
|
+
const elapsed = () => (started ? Math.round(performance.now() - started) : 0)
|
|
9
|
+
|
|
10
|
+
function finish(result) {
|
|
11
|
+
const part = resultFile.replace(/\.json$/, '.part')
|
|
12
|
+
writeFileSync(part, JSON.stringify({ durationMs: elapsed(), ...result }))
|
|
13
|
+
renameSync(part, resultFile)
|
|
14
|
+
process.exit(0)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
let timer = setTimeout(() => finish({ error: `The WASI runtime did not load within ${loadTimeoutMs} ms` }), loadTimeoutMs)
|
|
18
|
+
worker.on('message', (reply) => {
|
|
19
|
+
if (reply.type === 'started') {
|
|
20
|
+
clearTimeout(timer)
|
|
21
|
+
started = performance.now()
|
|
22
|
+
timer = setTimeout(() => finish({ error: `Stopped after ${timeoutMs} ms`, timedOut: true }), timeoutMs)
|
|
23
|
+
} else if (reply.type === 'done') {
|
|
24
|
+
finish({ output: reply.output })
|
|
25
|
+
} else {
|
|
26
|
+
finish({ error: `The WASI runtime failed: ${reply.error}` })
|
|
27
|
+
}
|
|
28
|
+
})
|
|
29
|
+
worker.on('error', error => finish({ error: `The WASI runtime failed: ${error.message}` }))
|
|
30
|
+
worker.on('exit', code => finish({ error: `The WASI runtime ended (${code}) before the run did` }))
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { parentPort, workerData } from 'node:worker_threads'
|
|
4
|
+
import { prepare, runWasi } from '../shared/wasi-runner.mjs'
|
|
5
|
+
|
|
6
|
+
const { request, dir } = workerData
|
|
7
|
+
const load = name => readFile(join(dir, name))
|
|
8
|
+
|
|
9
|
+
try {
|
|
10
|
+
await prepare(request.lang, load)
|
|
11
|
+
parentPort.postMessage({ type: 'started' })
|
|
12
|
+
parentPort.postMessage({ type: 'done', output: await runWasi(request, load) })
|
|
13
|
+
} catch (error) {
|
|
14
|
+
parentPort.postMessage({ type: 'error', error: error instanceof Error ? error.message : String(error) })
|
|
15
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface WasiRequest {
|
|
2
|
+
lang: string
|
|
3
|
+
code: string
|
|
4
|
+
stdin?: string
|
|
5
|
+
files?: Record<string, string>
|
|
6
|
+
env?: Record<string, string>
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface WasiOutput {
|
|
10
|
+
stdout: string
|
|
11
|
+
stderr: string
|
|
12
|
+
exitCode: number
|
|
13
|
+
outputs: { output_type: 'stream', name: 'stdout' | 'stderr', text: string }[]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type RuntimeLoader = (file: string) => Promise<Uint8Array>
|
|
17
|
+
|
|
18
|
+
export type Runtime = 'clang' | 'ruby' | 'sqlite'
|
|
19
|
+
|
|
20
|
+
export const RUNTIMES: Record<Runtime, string[]>
|
|
21
|
+
export function wasiLanguage(lang: string): 'c' | 'cpp' | 'ruby' | 'sql' | undefined
|
|
22
|
+
export function runtimeOf(lang: string): Runtime | undefined
|
|
23
|
+
export function runsLanguage(lang: string, languages?: string[]): boolean
|
|
24
|
+
export function prepare(lang: string, load: RuntimeLoader): Promise<void>
|
|
25
|
+
export function runWasi(request: WasiRequest, load: RuntimeLoader): Promise<WasiOutput>
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { WASI } from '@runno/wasi'
|
|
2
|
+
|
|
3
|
+
const SYSROOT = 'clang-fs.tar.gz'
|
|
4
|
+
|
|
5
|
+
export const RUNTIMES = {
|
|
6
|
+
clang: ['clang.wasm', 'wasm-ld.wasm', SYSROOT],
|
|
7
|
+
ruby: ['ruby-3.2.0.wasm', 'ruby-3.2.0.tar.gz'],
|
|
8
|
+
sqlite: ['sqlite.wasm'],
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const LANGUAGES = { 'c': 'c', 'cpp': 'cpp', 'c++': 'cpp', 'cc': 'cpp', 'cxx': 'cpp', 'ruby': 'ruby', 'rb': 'ruby', 'sql': 'sql', 'sqlite': 'sql' }
|
|
12
|
+
const RUNTIME_OF = { c: 'clang', cpp: 'clang', ruby: 'ruby', sql: 'sqlite' }
|
|
13
|
+
|
|
14
|
+
export function wasiLanguage(lang) {
|
|
15
|
+
const id = String(lang).trim().toLowerCase()
|
|
16
|
+
return Object.hasOwn(LANGUAGES, id) ? LANGUAGES[id] : undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function runtimeOf(lang) {
|
|
20
|
+
const id = wasiLanguage(lang)
|
|
21
|
+
return id && RUNTIME_OF[id]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function runsLanguage(lang, languages) {
|
|
25
|
+
const id = wasiLanguage(lang)
|
|
26
|
+
return id !== undefined && (!languages || languages.some(other => wasiLanguage(other) === id))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const EPOCH = new Date(0)
|
|
30
|
+
const TIMES = { access: EPOCH, modification: EPOCH, change: EPOCH }
|
|
31
|
+
const file = (path, content) => ({ path, timestamps: TIMES, ...typeof content === 'string' ? { mode: 'string', content } : { mode: 'binary', content } })
|
|
32
|
+
|
|
33
|
+
const ready = new Map()
|
|
34
|
+
|
|
35
|
+
function kept(name, make) {
|
|
36
|
+
if (!ready.has(name)) {
|
|
37
|
+
const value = make()
|
|
38
|
+
ready.set(name, value)
|
|
39
|
+
value.catch(() => ready.delete(name))
|
|
40
|
+
}
|
|
41
|
+
return ready.get(name)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const compiled = (name, load) => kept(name, () => load(name).then(bytes => WebAssembly.compile(bytes)))
|
|
45
|
+
const unpacked = (name, load) => kept(name, () => load(name).then(untar))
|
|
46
|
+
|
|
47
|
+
export async function prepare(lang, load) {
|
|
48
|
+
const runtime = runtimeOf(lang)
|
|
49
|
+
if (!runtime) throw new Error(`no WASI runtime runs ${lang}`)
|
|
50
|
+
await Promise.all(RUNTIMES[runtime].map(name => name.endsWith('.wasm') ? compiled(name, load) : unpacked(name, load)))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function gunzip(bytes) {
|
|
54
|
+
if (bytes[0] !== 0x1F || bytes[1] !== 0x8B) return bytes
|
|
55
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))
|
|
56
|
+
return new Uint8Array(await new Response(stream).arrayBuffer())
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function untar(gz) {
|
|
60
|
+
const tar = await gunzip(gz)
|
|
61
|
+
const text = new TextDecoder()
|
|
62
|
+
const field = (header, at, length) => text.decode(header.subarray(at, at + length)).replace(/\0.*$/s, '')
|
|
63
|
+
const fs = {}
|
|
64
|
+
for (let at = 0; at + 512 <= tar.length;) {
|
|
65
|
+
const header = tar.subarray(at, at + 512)
|
|
66
|
+
const name = field(header, 0, 100)
|
|
67
|
+
if (!name) break
|
|
68
|
+
const prefix = field(header, 345, 155)
|
|
69
|
+
const size = Number.parseInt(field(header, 124, 12).trim() || '0', 8)
|
|
70
|
+
const type = header[156]
|
|
71
|
+
if (type === 0x30 || type === 0) {
|
|
72
|
+
const path = `/${(prefix ? `${prefix}/${name}` : name).replace(/^\.?\//, '')}`
|
|
73
|
+
fs[path] = file(path, tar.slice(at + 512, at + 512 + size))
|
|
74
|
+
}
|
|
75
|
+
at += 512 + Math.ceil(size / 512) * 512
|
|
76
|
+
}
|
|
77
|
+
return fs
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function reader(input) {
|
|
81
|
+
let rest = input
|
|
82
|
+
return (max) => {
|
|
83
|
+
if (!rest) return null
|
|
84
|
+
let n = Math.min(rest.length, Math.max(2, Math.floor(max / 3)))
|
|
85
|
+
const code = rest.charCodeAt(n - 1)
|
|
86
|
+
if (n < rest.length && code >= 0xD800 && code <= 0xDBFF) n--
|
|
87
|
+
const chunk = rest.slice(0, n)
|
|
88
|
+
rest = rest.slice(n)
|
|
89
|
+
return chunk
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function start(module, { args, env = {}, fs = {}, stdin = '', write }) {
|
|
94
|
+
const wasi = new WASI({
|
|
95
|
+
args,
|
|
96
|
+
env: { ...env },
|
|
97
|
+
fs,
|
|
98
|
+
stdin: reader(stdin),
|
|
99
|
+
stdout: text => write('stdout', text),
|
|
100
|
+
stderr: text => write('stderr', text),
|
|
101
|
+
})
|
|
102
|
+
const instance = await WebAssembly.instantiate(module, wasi.getImportObject())
|
|
103
|
+
try {
|
|
104
|
+
return wasi.start({ module, instance })
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (!(error instanceof WebAssembly.RuntimeError || error instanceof RangeError)) throw error
|
|
107
|
+
write('stderr', `${error.name}: ${error.message}\n`)
|
|
108
|
+
return { exitCode: 1, fs }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const CLANG_C = ['-cc1', '-Werror', '-triple', 'wasm32-unknown-wasi', '-isysroot', '/sys', '-internal-isystem', '/sys/include', '-internal-isystem', '/sys/lib/clang/8.0.1/include', '-ferror-limit', '4', '-fmessage-length', '80', '-O2', '-emit-obj']
|
|
113
|
+
const CLANG_CPP = ['-cc1', '-Werror', '-emit-obj', '-disable-free', '-isysroot', '/sys', '-internal-isystem', '/sys/include/c++/v1', '-internal-isystem', '/sys/include', '-internal-isystem', '/sys/lib/clang/8.0.1/include', '-ferror-limit', '4', '-fmessage-length', '80', '-O2', '-x', 'c++']
|
|
114
|
+
const LINK = ['--no-threads', '--export-dynamic', '-z', 'stack-size=1048576', '-L/sys/lib/wasm32-wasi', '/sys/lib/wasm32-wasi/crt1.o', '/program.o', '-lc']
|
|
115
|
+
|
|
116
|
+
export async function runWasi(request, load) {
|
|
117
|
+
const lang = wasiLanguage(request.lang)
|
|
118
|
+
if (!lang) throw new Error(`no WASI runtime runs ${request.lang}`)
|
|
119
|
+
const streams = { stdout: '', stderr: '' }
|
|
120
|
+
const outputs = []
|
|
121
|
+
const write = (name, text) => {
|
|
122
|
+
if (!text) return
|
|
123
|
+
streams[name] += text
|
|
124
|
+
const last = outputs.at(-1)
|
|
125
|
+
if (last?.name === name) last.text += text
|
|
126
|
+
else outputs.push({ output_type: 'stream', name, text })
|
|
127
|
+
}
|
|
128
|
+
const files = {}
|
|
129
|
+
for (const [name, content] of Object.entries(request.files ?? {})) {
|
|
130
|
+
const path = `/${name.replace(/^\/+/, '')}`
|
|
131
|
+
files[path] = file(path, content)
|
|
132
|
+
}
|
|
133
|
+
const program = { fs: files, env: request.env, stdin: request.stdin ?? '', write }
|
|
134
|
+
const done = ({ exitCode }) => ({ ...streams, exitCode, outputs })
|
|
135
|
+
|
|
136
|
+
if (lang === 'ruby') {
|
|
137
|
+
const base = await unpacked('ruby-3.2.0.tar.gz', load)
|
|
138
|
+
return done(await start(await compiled('ruby-3.2.0.wasm', load), { ...program, args: ['ruby', '-r', '/ruby-3.2.0/.rubyopts.rb', '/program.rb'], fs: { ...base, ...files, '/program.rb': file('/program.rb', request.code) } }))
|
|
139
|
+
}
|
|
140
|
+
if (lang === 'sql') {
|
|
141
|
+
return done(await start(await compiled('sqlite.wasm', load), { ...program, args: ['sqlite', ':memory:', '.read /program.sql'], fs: { ...files, '/program.sql': file('/program.sql', request.code) } }))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const source = lang === 'cpp' ? '/program.cpp' : '/program.c'
|
|
145
|
+
const sysroot = await unpacked(SYSROOT, load)
|
|
146
|
+
const tool = { write, env: {}, stdin: '' }
|
|
147
|
+
const compile = await start(await compiled('clang.wasm', load), { ...tool, args: ['clang', ...lang === 'cpp' ? CLANG_CPP : CLANG_C, '-I', '/', '-o', '/program.o', source], fs: { ...sysroot, ...files, [source]: file(source, request.code) } })
|
|
148
|
+
if (compile.exitCode !== 0) return done(compile)
|
|
149
|
+
const link = await start(await compiled('wasm-ld.wasm', load), { ...tool, args: ['wasm-ld', ...LINK, ...lang === 'cpp' ? ['-lc++', '-lc++abi'] : [], '-o', '/program.wasm'], fs: { ...sysroot, '/program.o': compile.fs['/program.o'] } })
|
|
150
|
+
if (link.exitCode !== 0) return done(link)
|
|
151
|
+
const binary = link.fs['/program.wasm']
|
|
152
|
+
return done(await start(await WebAssembly.compile(binary.content), { ...program, args: ['program'] }))
|
|
153
|
+
}
|