beam.com 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +97 -0
  3. package/README.md +369 -0
  4. package/js/beam.com.mjs +33 -0
  5. package/js/download.mjs +78 -0
  6. package/js/node.mjs +75 -0
  7. package/package.json +36 -0
  8. package/runtime/app-com.js +203 -0
  9. package/runtime/beam.mjs +2 -0
  10. package/runtime/beam.wasm +0 -0
  11. package/runtime/browser/beam-wasm.js +2 -0
  12. package/runtime/browser/net.js +7 -0
  13. package/runtime/browser/none.js +4 -0
  14. package/runtime/browser.js +161 -0
  15. package/runtime/cloudflare/durable.js +361 -0
  16. package/runtime/cloudflare/index.js +76 -0
  17. package/runtime/cloudflare/release.js +42 -0
  18. package/runtime/cloudflare/snapshot.js +3 -0
  19. package/runtime/cloudflare/worker.js +1891 -0
  20. package/runtime/deno/app.js +8 -0
  21. package/runtime/deno/beam-wasm.js +3 -0
  22. package/runtime/deno/none.js +3 -0
  23. package/runtime/deno/release-bin.js +46 -0
  24. package/runtime/deno/snapshot-bin.js +11 -0
  25. package/runtime/deno/worker.js +1891 -0
  26. package/runtime/deno.js +346 -0
  27. package/runtime/deno.json +5 -0
  28. package/runtime/durable-global.js +40 -0
  29. package/runtime/durable.js +361 -0
  30. package/runtime/global.js +26 -0
  31. package/runtime/licenses/LICENSE +202 -0
  32. package/runtime/licenses/NOTICE +97 -0
  33. package/runtime/licenses/bcrypt_elixir.txt +87 -0
  34. package/runtime/licenses/cosmopolitan.txt +16 -0
  35. package/runtime/licenses/elixir/Apache-2.0.txt +73 -0
  36. package/runtime/licenses/elixir/LicenseRef-elixir-trademark-policy.txt +98 -0
  37. package/runtime/licenses/elixir/LicenseRef-scancode-unicode.txt +58 -0
  38. package/runtime/licenses/emscripten.txt +102 -0
  39. package/runtime/licenses/exqlite.txt +21 -0
  40. package/runtime/licenses/llvm.txt +311 -0
  41. package/runtime/licenses/musl.txt +193 -0
  42. package/runtime/licenses/otp/BSD-2-Clause.txt +22 -0
  43. package/runtime/licenses/otp/BSD-3-Clause.txt +25 -0
  44. package/runtime/licenses/otp/LicenseRef-IETF-MIB.txt +9 -0
  45. package/runtime/licenses/otp/LicenseRef-RSA-PKCS3.txt +23 -0
  46. package/runtime/licenses/otp/LicenseRef-RSA-PKCS5v2-0.txt +17 -0
  47. package/runtime/licenses/otp/LicenseRef-scancode-ietf-trust.txt +296 -0
  48. package/runtime/licenses/otp/LicenseRef-scancode-ietf.txt +23 -0
  49. package/runtime/licenses/otp/LicenseRef-scancode-w3c-docs-19990405.txt +26 -0
  50. package/runtime/licenses/otp/LicenseRef-scancode-wxwindows-free-doc-3.txt +57 -0
  51. package/runtime/licenses/otp/MIT.txt +17 -0
  52. package/runtime/licenses/otp/SGI-B-2.0.txt +25 -0
  53. package/runtime/licenses/otp/W3C-19980720.txt +55 -0
  54. package/runtime/licenses/picosat.txt +19 -0
  55. package/runtime/licenses/wamr.txt +219 -0
  56. package/runtime/nifs.js +2 -0
  57. package/runtime/package.json +1 -0
  58. package/runtime/page/404.html +49 -0
  59. package/runtime/page/app-com.js +203 -0
  60. package/runtime/page/beam.mjs +2 -0
  61. package/runtime/page/browser/beam-wasm.js +2 -0
  62. package/runtime/page/browser/net.js +7 -0
  63. package/runtime/page/browser/none.js +4 -0
  64. package/runtime/page/browser.js +161 -0
  65. package/runtime/page/index.html +50 -0
  66. package/runtime/page/licenses/LICENSE +202 -0
  67. package/runtime/page/licenses/NOTICE +97 -0
  68. package/runtime/page/licenses/bcrypt_elixir.txt +87 -0
  69. package/runtime/page/licenses/cosmopolitan.txt +16 -0
  70. package/runtime/page/licenses/elixir/Apache-2.0.txt +73 -0
  71. package/runtime/page/licenses/elixir/LicenseRef-elixir-trademark-policy.txt +98 -0
  72. package/runtime/page/licenses/elixir/LicenseRef-scancode-unicode.txt +58 -0
  73. package/runtime/page/licenses/emscripten.txt +102 -0
  74. package/runtime/page/licenses/exqlite.txt +21 -0
  75. package/runtime/page/licenses/llvm.txt +311 -0
  76. package/runtime/page/licenses/musl.txt +193 -0
  77. package/runtime/page/licenses/otp/BSD-2-Clause.txt +22 -0
  78. package/runtime/page/licenses/otp/BSD-3-Clause.txt +25 -0
  79. package/runtime/page/licenses/otp/LicenseRef-IETF-MIB.txt +9 -0
  80. package/runtime/page/licenses/otp/LicenseRef-RSA-PKCS3.txt +23 -0
  81. package/runtime/page/licenses/otp/LicenseRef-RSA-PKCS5v2-0.txt +17 -0
  82. package/runtime/page/licenses/otp/LicenseRef-scancode-ietf-trust.txt +296 -0
  83. package/runtime/page/licenses/otp/LicenseRef-scancode-ietf.txt +23 -0
  84. package/runtime/page/licenses/otp/LicenseRef-scancode-w3c-docs-19990405.txt +26 -0
  85. package/runtime/page/licenses/otp/LicenseRef-scancode-wxwindows-free-doc-3.txt +57 -0
  86. package/runtime/page/licenses/otp/MIT.txt +17 -0
  87. package/runtime/page/licenses/otp/SGI-B-2.0.txt +25 -0
  88. package/runtime/page/licenses/otp/W3C-19980720.txt +55 -0
  89. package/runtime/page/licenses/picosat.txt +19 -0
  90. package/runtime/page/licenses/wamr.txt +219 -0
  91. package/runtime/page/main.js +176 -0
  92. package/runtime/page/runtime-id.js +3 -0
  93. package/runtime/page/scope.js +17 -0
  94. package/runtime/page/sw.js +111 -0
  95. package/runtime/page/vm.js +148 -0
  96. package/runtime/page/worker.js +1891 -0
  97. package/runtime/page/ws-shim.js +143 -0
  98. package/runtime/release/app.js +17 -0
  99. package/runtime/release.json +1 -0
  100. package/runtime/runtime-id.js +3 -0
  101. package/runtime/tcp-proxy.mjs +30 -0
  102. package/runtime/worker.js +1891 -0
@@ -0,0 +1,219 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
203
+
204
+ --- LLVM Exceptions to the Apache 2.0 License ----
205
+
206
+ As an exception, if, as a result of your compiling your source code, portions
207
+ of this Software are embedded into an Object form of such source code, you
208
+ may redistribute such embedded portions in such Object form without complying
209
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
210
+
211
+ In addition, if you combine or link compiled forms of this Software with
212
+ software that is licensed under the GPLv2 ("Combined Software") and if a
213
+ court of competent jurisdiction determines that the patent provision (Section
214
+ 3), the indemnity provision (Section 9) or other Section of the License
215
+ conflicts with the conditions of the GPLv2, you may retroactively and
216
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
217
+ the License, but only in their entirety and only with respect to the Combined
218
+ Software.
219
+
@@ -0,0 +1,176 @@
1
+ // The start of the page (index.html): the VM in a SharedWorker (vm.js), the
2
+ // service worker of the frame of the app (sw.js), and the frame. The page
3
+ // of beam.com INPUT -o DIR --target wasm32 imports it next to it, and a
4
+ // site that runs a native app.com imports it from the npm package beam.com
5
+ // (a CDN), with the options:
6
+ // - app: the URL of app.com, relative to the page;
7
+ // - vm: the URL of the script of the VM on the site (default ./vm.js). A
8
+ // SharedWorker and a service worker must come from the origin of the
9
+ // site, so its vm.js and sw.js import the ones of the package.
10
+ const status = document.getElementById('status'), bar = document.getElementById('bar');
11
+ const say = (text, error = false) => { status.textContent = text; status.className = error ? 'err' : ''; };
12
+ const fail = (text) => { bar.remove(); say(text, true); };
13
+ // The site is the directory of this page. The app is in the frame app/.
14
+ const SITE = new URL('./', location.href);
15
+ const APP = new URL('./app/', SITE);
16
+
17
+ // The path of the frame is in the fragment of the URL of this page
18
+ // (SITE#/users/log-in), so a reload and a link keep the page of the app.
19
+ // Only a path: it starts with "/", not with "//", and it stays in app/ of
20
+ // this origin. Another fragment opens the home page of the app.
21
+ function startUrl() {
22
+ const path = location.hash.slice(1);
23
+ if (!path.startsWith('/') || path.startsWith('//')) return APP.href;
24
+ const url = new URL(APP.pathname.replace(/\/$/, '') + path, SITE);
25
+ return url.origin === SITE.origin && url.pathname.startsWith(APP.pathname) ? url.href : APP.href;
26
+ }
27
+
28
+ // The variables of the VM (env.json, from the build). A secret gets a
29
+ // random value, one for each browser. It stays in localStorage, so that
30
+ // the snapshot of the VM (its key has the variables) serves the next visit.
31
+ function secret(name) {
32
+ const key = `beam-page:${SITE.pathname}:${name}`;
33
+ try {
34
+ const old = localStorage.getItem(key);
35
+ if (old) return old;
36
+ } catch {}
37
+ const bytes = crypto.getRandomValues(new Uint8Array(48));
38
+ const value = btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_');
39
+ try { localStorage.setItem(key, value); } catch {}
40
+ return value;
41
+ }
42
+
43
+ // The name of the app on the page.
44
+ function named(name) {
45
+ document.title = name;
46
+ document.getElementById('name').textContent = name;
47
+ document.getElementById('app').title = name;
48
+ }
49
+
50
+ async function main({ app = null, vm: vmScript = './vm.js' } = {}) {
51
+ // A native app.com: its release has the name and the environment of the
52
+ // app, so the page gives only the variables of a page. Else env.json of
53
+ // the build (beam.com INPUT -o DIR --target wasm32).
54
+ const config = app
55
+ ? { name: null, env: { PORT: '4000', HOME: '/tmp', PHX_HOST: 'localhost' }, secrets: ['SECRET_KEY_BASE'] }
56
+ : await (await fetch(new URL('env.json', SITE))).json();
57
+ if (config.name) named(config.name);
58
+ // JSPI (WebAssembly JavaScript Promise Integration) is in Chrome and
59
+ // Edge 137 or later, and in Firefox 153 or later. Safari 27 also has
60
+ // it, but nobody has tested this page in Safari yet.
61
+ if (typeof WebAssembly.Suspending !== 'function' || !('serviceWorker' in navigator)) {
62
+ return fail('This browser cannot run the VM. Open this page in Chrome or Edge 137 or later, or in Firefox 153 or later.');
63
+ }
64
+ const env = { ...config.env };
65
+ for (const name of config.secrets ?? []) env[name] = secret(name);
66
+ const start = { type: 'start', base: APP.pathname.replace(/\/$/, ''), env, app: app && new URL(app, SITE).href };
67
+ const t0 = performance.now();
68
+ say('Loading the runtime and the release…');
69
+ // vm: the port of the SharedWorker of the VM, or the Worker of the VM in
70
+ // this tab. With no VM, this tab answers noVm to the service worker,
71
+ // which then gives the request to another tab.
72
+ let vm = null;
73
+ const relay = (data, port) => (vm ? vm.postMessage(data, [port]) : port.postMessage({ noVm: true }));
74
+ // The requests of the service worker (sw.js, not another worker of this
75
+ // origin) go to the VM with their reply port.
76
+ const SW = new URL('./sw.js', SITE).href;
77
+ navigator.serviceWorker.addEventListener('message', (e) => {
78
+ if (e.source?.scriptURL === SW && e.data?.type === 'fetch') relay(e.data, e.ports[0]);
79
+ });
80
+ // The WebSockets and the requests of the frame of the app, and of the
81
+ // frames in it (ws-shim.js).
82
+ const inFrame = (w) => {
83
+ for (let n = 0; w && n < 10; n++, w = w.parent) {
84
+ if (w === document.getElementById('app').contentWindow) return true;
85
+ if (w === w.parent) return false;
86
+ }
87
+ return false;
88
+ };
89
+ addEventListener('message', (e) => {
90
+ if (e.origin === location.origin && ['ws', 'fetch'].includes(e.data?.type) && inFrame(e.source)) relay(e.data, e.ports[0]);
91
+ // The path of the frame of the app (ws-shim.js), for the fragment.
92
+ if (e.origin === location.origin && e.data?.type === 'path' && e.source === document.getElementById('app').contentWindow
93
+ && typeof e.data.path === 'string' && e.data.path.startsWith('/') && !e.data.path.startsWith('//')) {
94
+ history.replaceState(history.state, '', e.data.path === '/' ? location.pathname + location.search : `#${e.data.path}`);
95
+ }
96
+ });
97
+ // This page is outside the scope, so navigator.serviceWorker.ready does
98
+ // not apply: wait for the registration to be active.
99
+ const active = navigator.serviceWorker.register(SW, { scope: APP.pathname, type: 'module' }).then((reg) =>
100
+ new Promise((resolve) => {
101
+ const check = () => { if (reg.active) resolve(reg.active); };
102
+ check();
103
+ for (const w of [reg.installing, reg.waiting]) w?.addEventListener('statechange', check);
104
+ reg.addEventListener('updatefound', () => reg.installing?.addEventListener('statechange', check));
105
+ }));
106
+ // The answer of the VM to start: ready or error. An error that the VM
107
+ // answered (vm: true) can go away at a second start, for example a
108
+ // network error on release.bin. An error event of the worker (its script
109
+ // did not load) occurs one time only.
110
+ const started = (port, worker) => new Promise((resolve, reject) => {
111
+ port.onmessage = (e) => {
112
+ if (e.data.type === 'ready') resolve(e.data);
113
+ else if (e.data.type === 'error') reject(Object.assign(new Error(e.data.message), { vm: true }));
114
+ };
115
+ worker.addEventListener('error', (e) => reject(new Error(e.message || 'the VM stopped')));
116
+ port.postMessage(start);
117
+ });
118
+ const script = new URL(vmScript, SITE);
119
+ let info = null, where = 'shared';
120
+ // One VM for all the tabs of the site, in a SharedWorker. The sites of
121
+ // one origin (USER.github.io/A/ and USER.github.io/B/) have different
122
+ // scripts, so different VMs.
123
+ // The VM stops 30 s after the last tab of the site leaves (vm.js), so a
124
+ // reload keeps the VM and its data. A tab says "bye" when it leaves, and
125
+ // "hello" when it comes back from the back/forward cache.
126
+ // extendedLifetime (Chrome 148 or later) lets the SharedWorker live
127
+ // after its last tab, until that timer of vm.js ends.
128
+ if (typeof SharedWorker === 'function') {
129
+ try {
130
+ const shared = new SharedWorker(script, { type: 'module', name: `beam-page:${SITE.pathname}`, extendedLifetime: true });
131
+ vm = shared.port;
132
+ // A failed boot of the VM gets one more start on the same port, so that
133
+ // an error that occurs one time does not make two VMs for one site.
134
+ info = await started(shared.port, shared).catch((e) => {
135
+ if (!e.vm) throw e;
136
+ console.log(`beam: the VM did not start in the SharedWorker (${e.message}): one more start`);
137
+ return started(shared.port, shared);
138
+ });
139
+ addEventListener('pagehide', () => shared.port.postMessage({ type: 'bye' }));
140
+ addEventListener('pageshow', (e) => { if (e.persisted) shared.port.postMessage({ type: 'hello' }); });
141
+ } catch (e) {
142
+ console.log(`beam: the VM did not start in a SharedWorker (${e.message}): it runs in this tab`);
143
+ vm?.postMessage({ type: 'bye' });
144
+ vm?.close();
145
+ vm = null;
146
+ }
147
+ }
148
+ // Else one VM in one tab: the other tabs of the site show a message.
149
+ if (!info) {
150
+ where = 'tab';
151
+ const lock = await new Promise((resolve) =>
152
+ navigator.locks.request(`beam-page:${SITE.pathname}`, { ifAvailable: true }, (l) => {
153
+ resolve(l);
154
+ return l ? new Promise(() => {}) : undefined;
155
+ }));
156
+ if (!lock) return fail('The app runs in another tab of this site. Use that tab, or close it and load this page again.');
157
+ const worker = new Worker(script, { type: 'module' });
158
+ vm = worker;
159
+ info = await started(worker, worker);
160
+ }
161
+ (await active).postMessage({ type: 'boot' }); // this tab can reach the VM
162
+ if (info.name) named(info.name);
163
+ const ms = Math.round(performance.now() - t0);
164
+ // For the browser check (tests/page/check.mjs).
165
+ document.body.dataset.vm = where;
166
+ document.body.dataset.restored = String(info.restored);
167
+ console.log(`beam: the VM started in ${ms} ms (${where === 'shared' ? 'a SharedWorker' : 'this tab'}${info.restored ? ', from the snapshot' : ''})`);
168
+ say(`Opening the app (the VM started in ${ms} ms)…`);
169
+ const frame = document.getElementById('app');
170
+ frame.addEventListener('load', () => document.body.classList.add('running'), { once: true });
171
+ frame.src = startUrl();
172
+ }
173
+
174
+ export function start(options) {
175
+ main(options).catch((e) => { fail(e.message); console.error(e); });
176
+ }
@@ -0,0 +1,3 @@
1
+ // The identity of this runtime (beam_com_wasm:runtime_id/1): the SHA-256 of
2
+ // the output of "sha256sum app-com.js beam.mjs beam.wasm worker.js".
3
+ export default '8f7af69ef48fc70da056a5684afc43055a33cfd9efb3099d858b0f75b33e351b';
@@ -0,0 +1,17 @@
1
+ // The rule of the scope of the frame of the app (app/ of the site). An app
2
+ // can write a path without its base path (href="/", or a redirect to "/").
3
+ // A URL of this origin outside the scope is such a path: it goes to the same
4
+ // path in the scope. sw.js applies it to a redirect, and ws-shim.js (a
5
+ // classic script, which cannot import this module) has a copy of it for the
6
+ // links and the forms.
7
+
8
+ // true: url (a URL) is of the origin of scope and outside it.
9
+ export function outside(url, scope) {
10
+ return url.origin === scope.origin && !`${url.pathname}/`.startsWith(scope.pathname);
11
+ }
12
+
13
+ // The href of url in the scope: the same path, with the prefix of the scope.
14
+ export function inScope(url, scope) {
15
+ if (!outside(url, scope)) return url.href;
16
+ return new URL(scope.pathname.replace(/\/$/, '') + url.pathname + url.search + url.hash, url).href;
17
+ }
@@ -0,0 +1,111 @@
1
+ // The service worker of the page (index.html), for the requests of its
2
+ // scope app/ (the frames of the app):
3
+ // - a static file (app/static.json lists the files of priv/static of the
4
+ // app) comes from the site, as it is;
5
+ // - another request goes to the VM, with a port for the reply. A service
6
+ // worker cannot open a SharedWorker, so a page gives the request to the
7
+ // VM. First the frame that sent the request (its ws-shim.js gives the
8
+ // request to its tab), else a tab of index.html that said "boot" (a
9
+ // visible one first), else any tab of index.html. A tab with no VM
10
+ // answers noVm, and the next one gets the request.
11
+ // The VM gets the path without the prefix of the scope, as behind a
12
+ // proxy. The app makes its links with the prefix (BEAM_BASE_PATH, see
13
+ // wasm_host_base).
14
+ // A navigation of a top window in the scope goes to the page, with the path
15
+ // of the app in the fragment (SITE#/PATH).
16
+ // The page of an HTML reply gets ws-shim.js: the WebSocket of LiveView
17
+ // then goes to the VM too. The sw.js of a site that runs a native app.com
18
+ // imports this module from the npm package (a CDN): this module finds the
19
+ // site from its scope, not from its own URL. A redirect to a path of this origin outside the
20
+ // scope goes to the same path in the scope (scope.js).
21
+ import { inScope } from './scope.js';
22
+
23
+ const SCOPE = new URL(registration.scope);
24
+ const BOOT = new URL('../', SCOPE);
25
+ const tabs = new Set(); // the tabs of index.html that said "boot"
26
+ const frames = new Set(); // the frames with ws-shim.js
27
+ let statics = null;
28
+
29
+ self.addEventListener('install', () => self.skipWaiting());
30
+ self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
31
+ // Only the page index.html (a tab of the VM) can say "boot", and only a page
32
+ // of the scope can say "frame": another page of this origin cannot take the
33
+ // requests of the app.
34
+ const isBootPage = (href) => {
35
+ const u = new URL(href);
36
+ return u.origin === BOOT.origin && (u.pathname === BOOT.pathname || u.pathname === `${BOOT.pathname}index.html`);
37
+ };
38
+ const isFramePage = (href) => {
39
+ const u = new URL(href);
40
+ return u.origin === SCOPE.origin && u.pathname.startsWith(SCOPE.pathname);
41
+ };
42
+ self.addEventListener('message', (e) => {
43
+ if (!e.source?.url) return;
44
+ if (e.data?.type === 'boot' && isBootPage(e.source.url)) tabs.add(e.source.id);
45
+ else if (e.data?.type === 'frame' && isFramePage(e.source.url)) frames.add(e.source.id);
46
+ });
47
+
48
+ async function staticFiles() {
49
+ statics ??= fetch(new URL('static.json', SCOPE)).then((r) => (r.ok ? r.json() : []))
50
+ .catch(() => []).then((list) => new Set(list));
51
+ return statics;
52
+ }
53
+
54
+ // The pages that can give a request to the VM, in order.
55
+ async function relays(clientId) {
56
+ const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
57
+ const alive = new Set(all.map((c) => c.id));
58
+ for (const set of [tabs, frames]) for (const id of set) if (!alive.has(id)) set.delete(id);
59
+ const frame = frames.has(clientId) ? all.filter((c) => c.id === clientId) : [];
60
+ const rank = (c) => (tabs.has(c.id) ? 0 : 4) + (c.focused ? 0 : 1) + (c.visibilityState === 'visible' ? 0 : 2);
61
+ return [...frame, ...all.filter((c) => isBootPage(c.url)).sort((a, b) => rank(a) - rank(b))];
62
+ }
63
+
64
+ self.addEventListener('fetch', (e) => {
65
+ const url = new URL(e.request.url);
66
+ if (url.origin !== SCOPE.origin || !url.pathname.startsWith(SCOPE.pathname)) return;
67
+ // A page of the app in a top window (a reload, a link from another site,
68
+ // a new tab) goes to the page of the site, with its path in the fragment.
69
+ // The page then opens that path in the frame (index.html).
70
+ if (e.request.mode === 'navigate' && e.request.destination === 'document') {
71
+ const path = url.pathname.slice(SCOPE.pathname.length - 1) + url.search;
72
+ e.respondWith(Response.redirect(path === '/' ? BOOT.href : `${BOOT.href}#${path}`, 302));
73
+ return;
74
+ }
75
+ e.respondWith(handle(e.request, url, e.clientId));
76
+ });
77
+
78
+ async function handle(request, url, clientId) {
79
+ const rest = url.pathname.slice(SCOPE.pathname.length - 1); // "/..." of the app
80
+ if (request.method === 'GET' && (await staticFiles()).has(rest)) return fetch(request);
81
+ const body = ['GET', 'HEAD'].includes(request.method) ? null : await request.arrayBuffer();
82
+ const req = { path: rest + url.search, method: request.method, headers: [...request.headers], body };
83
+ let r = null;
84
+ for (const client of await relays(clientId)) {
85
+ const { port1, port2 } = new MessageChannel();
86
+ const reply = new Promise((resolve) => { port1.onmessage = (m) => resolve(m.data); });
87
+ client.postMessage({ type: 'fetch', req }, [port2]);
88
+ r = await reply;
89
+ if (!r.noVm) break;
90
+ }
91
+ if (!r || r.noVm) {
92
+ return new Response(`<p>The app runs in the tab of <a href="${BOOT.href}" target="_top">this page</a>. Open it again.</p>`,
93
+ { status: 503, headers: { 'content-type': 'text/html; charset=utf-8' } });
94
+ }
95
+ if (r.error) return new Response(r.error, { status: 502 });
96
+ if (r.status >= 300 && r.status < 400 && r.location) {
97
+ return Response.redirect(inScope(new URL(r.location, url), SCOPE), [301, 302, 303, 307, 308].includes(r.status) ? r.status : 302);
98
+ }
99
+ const headers = new Headers(r.headers);
100
+ let data = r.body;
101
+ if ((headers.get('content-type') ?? '').startsWith('text/html') && data) {
102
+ const html = new TextDecoder().decode(data);
103
+ // ws-shim.js next to this module (the site, or the CDN of a site that
104
+ // runs a native app.com), with the scope of the frame.
105
+ const shim = `<script src="${new URL('./ws-shim.js', import.meta.url).href}" data-app="${SCOPE.pathname}"></script>`;
106
+ data = html.replace(/<head[^>]*>/i, (h) => h + shim);
107
+ headers.delete('content-length');
108
+ }
109
+ const nullBody = [101, 204, 205, 304].includes(r.status);
110
+ return new Response(nullBody ? null : data, { status: r.status, statusText: r.statusText, headers });
111
+ }