@b9g/shovel 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2023 Brian Kim
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/bin/shovel.js ADDED
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node --experimental-vm-modules --experimental-fetch --no-warnings
2
+ import * as Path from "path";
3
+ import * as FS from "fs/promises";
4
+ import {createServer} from "http";
5
+ import * as VM from "vm";
6
+ import {pathToFileURL} from "url";
7
+ import {parseArgs} from "@pkgjs/parseargs";
8
+ import * as ESBuild from "esbuild";
9
+ import {SourceMapConsumer} from "source-map";
10
+ import MagicString from "magic-string";
11
+ import StackTracey from "stacktracey";
12
+ import resolve from "../resolve.js";
13
+
14
+ // TODO: replace with yargs or commander
15
+ const {values, positionals} = parseArgs({
16
+ allowPositionals: true,
17
+ options: {
18
+ port: {
19
+ type: "string",
20
+ },
21
+ },
22
+ });
23
+
24
+ const path = Path.resolve(positionals[0] || "");
25
+ const cwd = process.cwd();
26
+ const port = parseInt(values["port"] || "1337");
27
+
28
+ let sourceMapConsumer;
29
+ let namespace;
30
+ const plugin = {
31
+ name: "loader",
32
+ setup(build) {
33
+ // TODO: correct filters
34
+ build.onLoad({filter: /\.(js|ts|jsx|tsx)$/}, async (args) => {
35
+ let code = await FS.readFile(args.path, "utf8");
36
+ const magicString = new MagicString(code);
37
+ magicString.prepend(
38
+ `import.meta.url = "${pathToFileURL(args.path).href}";`,
39
+ );
40
+
41
+ code = magicString.toString();
42
+ const map = magicString.generateMap({
43
+ file: args.path,
44
+ source: args.path,
45
+ hires: true,
46
+ includeContent: true,
47
+ });
48
+
49
+ code = code + "\n//# sourceMappingURL=" + map.toUrl();
50
+ return {
51
+ contents: code,
52
+ loader: Path.extname(args.path).slice(1),
53
+ };
54
+ });
55
+
56
+ // TODO: Error handling
57
+ build.onEnd(async (result) => {
58
+ const url = pathToFileURL(build.initialOptions.entryPoints[0]).href;
59
+ console.log("built:", url);
60
+ // TODO: handle build errors
61
+ if (result.errors && result.errors.length) {
62
+ const formatted = await ESBuild.formatMessages(result.errors, {
63
+ kind: "error",
64
+ color: true,
65
+ });
66
+ console.error(formatted.join("\n"));
67
+ return;
68
+ }
69
+
70
+ const code = result.outputFiles.find((file) => file.path.endsWith(".js"))?.text;
71
+ const map = result.outputFiles.find((file) => file.path.endsWith(".map"))?.text;
72
+ if (map) {
73
+ sourceMapConsumer = await new SourceMapConsumer(map);
74
+ }
75
+
76
+ const module = new VM.SourceTextModule(code, {
77
+ identifier: url,
78
+ });
79
+
80
+ await module.link(async (specifier) => {
81
+ const resolved = await resolve(specifier, cwd);
82
+ try {
83
+ const child = await import(resolved);
84
+ const exports = Object.keys(child);
85
+ return new VM.SyntheticModule(
86
+ exports,
87
+ function () {
88
+ for (const key of exports) {
89
+ this.setExport(key, child[key]);
90
+ }
91
+ },
92
+ );
93
+ } catch (err) {
94
+ // TODO: Log a message
95
+ console.error("await import threw", err);
96
+ return new VM.SyntheticModule([], function () {});
97
+ }
98
+ });
99
+
100
+ try {
101
+ await module.evaluate();
102
+ } catch (err) {
103
+ if (sourceMapConsumer) {
104
+ fixStack(err, sourceMapConsumer);
105
+ }
106
+
107
+ console.error(err);
108
+ return;
109
+ }
110
+
111
+ namespace?.default?.cleanup?.();
112
+ namespace = module.namespace;
113
+ });
114
+ },
115
+ };
116
+
117
+ function fixStack(err, sourceMapConsumer) {
118
+ let [message, ...lines] = err.stack.split("\n");
119
+ lines = lines.map((line, i) => {
120
+ // parse the stack trace line
121
+ return line.replace(new RegExp(`${path}:(\\d+):(\\d+)`), (match, line, column) => {
122
+ const pos = sourceMapConsumer.originalPositionFor({
123
+ line: parseInt(line),
124
+ column: parseInt(column),
125
+ });
126
+
127
+ const source = pos.source ? Path.resolve(
128
+ Path.dirname(path),
129
+ pos.source
130
+ ) : url;
131
+ return `${source}:${pos.line}:${pos.column}`;
132
+ });
133
+ });
134
+ err.stack = [message, ...lines].join("\n");
135
+ }
136
+
137
+ const ctx = await ESBuild.context({
138
+ format: "esm",
139
+ platform: "node",
140
+ absWorkingDir: cwd,
141
+ entryPoints: [path],
142
+ bundle: true,
143
+ metafile: true,
144
+ write: false,
145
+ packages: "external",
146
+ sourcemap: "both",
147
+ plugins: [plugin],
148
+ outdir: cwd,
149
+ logLevel: "silent",
150
+ });
151
+
152
+ await ctx.watch();
153
+
154
+ function readableStreamFromMessage(req) {
155
+ return new ReadableStream({
156
+ start(controller) {
157
+ req.on("data", (chunk) => {
158
+ controller.enqueue(chunk);
159
+ });
160
+
161
+ req.on("end", () => {
162
+ controller.close();
163
+ });
164
+ },
165
+
166
+ cancel() {
167
+ req.destroy();
168
+ },
169
+ });
170
+ }
171
+
172
+ async function webRequestFromNode(req) {
173
+ const url = new URL(req.url || "/", "http://" + req.headers.host);
174
+ const headers = new Headers();
175
+ for (const key in req.headers) {
176
+ if (req.headers[key]) {
177
+ headers.append(key, req.headers[key]);
178
+ }
179
+ }
180
+
181
+ return new Request(url, {
182
+ method: req.method,
183
+ headers,
184
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : readableStreamFromMessage(req),
185
+ });
186
+ }
187
+
188
+ async function callNodeResponse(res, webRes) {
189
+ const headers = {};
190
+ webRes.headers.forEach((value, key) => {
191
+ headers[key] = value;
192
+ });
193
+ res.writeHead(webRes.status, headers);
194
+ // TODO: stream the body
195
+ res.end(await webRes.text());
196
+ }
197
+
198
+ const server = createServer(async (req, res) => {
199
+ const webReq = await webRequestFromNode(req);
200
+ if (typeof namespace?.default?.fetch === "function") {
201
+ let webRes;
202
+ try {
203
+ webRes = await namespace?.default?.fetch(webReq);
204
+ } catch (err) {
205
+ console.error(err);
206
+ res.writeHead(500);
207
+ res.end();
208
+ return;
209
+ }
210
+
211
+ callNodeResponse(res, webRes);
212
+ } else {
213
+ res.write("waiting for namespace to be set");
214
+ res.end();
215
+ }
216
+ });
217
+
218
+ console.log("listening on port:", port);
219
+ server.listen(port);
220
+
221
+ process.on("uncaughtException", (err) => {
222
+ if (sourceMapConsumer) {
223
+ fixStack(err, sourceMapConsumer);
224
+ }
225
+
226
+ console.error(err);
227
+ });
228
+
229
+ process.on("unhandledRejection", (err) => {
230
+ if (sourceMapConsumer) {
231
+ fixStack(err, sourceMapConsumer);
232
+ }
233
+
234
+ console.error(err);
235
+ });
package/noop.ts ADDED
@@ -0,0 +1,8 @@
1
+ function thrower(): never {
2
+ console.log("hi");
3
+ throw new Error("This is an error");
4
+ }
5
+
6
+ export default function noop() {
7
+ thrower();
8
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@b9g/shovel",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Dig for treasure",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "license": "MIT",
10
+ "dependencies": {
11
+ "@b9g/crank": "^0.5.3",
12
+ "@pkgjs/parseargs": "^0.11.0",
13
+ "chokidar": "^3.5.3",
14
+ "esbuild": "^0.17.11",
15
+ "is-core-module": "^2.11.0",
16
+ "magic-string": "^0.30.0",
17
+ "resolve.exports": "^2.0.1",
18
+ "source-map": "^0.7.4"
19
+ },
20
+ "bin": {
21
+ "shovel": "bin/shovel.js"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ }
26
+ }
package/poop.ts ADDED
@@ -0,0 +1,13 @@
1
+ import {jsx} from "@b9g/crank/standalone";
2
+ import {renderer} from "@b9g/crank/html";
3
+ import noop from "./noop.ts";
4
+
5
+ export default {
6
+ fetch(req: Request) {
7
+ console.log("serving:", req.url);
8
+ const html = renderer.render(jsx`<div>Hello from Crank</div>`);
9
+ return new Response(html, {
10
+ headers: {"content-type": "text/html; charset=UTF-8"},
11
+ });
12
+ }
13
+ };
package/resolve.js ADDED
@@ -0,0 +1,197 @@
1
+ // Adapted from https://github.com/browserify/resolve because the original code
2
+ // was truly ass and didn't support ES modules.
3
+ // TODO: Support ES modules, clean up, double check it works according to the node resolution algorithm.
4
+ // MIT License
5
+ // Copyright (c) 2012 James Halliday
6
+ import * as FS from "fs/promises";
7
+ import * as Path from "path";
8
+ import isCore from 'is-core-module';
9
+
10
+ function nodeModulesPaths(start) {
11
+ let prefix = '/';
12
+ if ((/^([A-Za-z]:)/).test(start)) {
13
+ prefix = '';
14
+ } else if ((/^\\\\/).test(start)) {
15
+ prefix = '\\\\';
16
+ }
17
+
18
+ const paths = [start];
19
+ let parsed = Path.parse(start);
20
+ while (parsed.dir !== paths[paths.length - 1]) {
21
+ paths.push(parsed.dir);
22
+ parsed = Path.parse(parsed.dir);
23
+ }
24
+
25
+ return paths.reduce(function (dirs, aPath) {
26
+ return dirs.concat([Path.resolve(prefix, aPath, "node_modules")]);
27
+ }, []);
28
+ }
29
+
30
+ async function isFile(file) {
31
+ let stat;
32
+ try {
33
+ stat = await FS.stat(file);
34
+ } catch (err) {
35
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
36
+ return false;
37
+ }
38
+
39
+ throw err;
40
+ }
41
+
42
+ return stat.isFile() || stat.isFIFO();
43
+ }
44
+
45
+ async function isDirectory(dir) {
46
+ let stat;
47
+ try {
48
+ stat = await FS.stat(dir);
49
+ } catch (err) {
50
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
51
+ return false;
52
+ }
53
+
54
+ throw err;
55
+ }
56
+
57
+ return stat.isDirectory();
58
+ }
59
+
60
+ const localRealpath =
61
+ process.platform !== 'win32' && FS.realpath && typeof FS.realpath.native === 'function'
62
+ ? FS.realpath.native
63
+ : FS.realpath;
64
+ async function realpath(x) {
65
+ try {
66
+ return await localRealpath(x);
67
+ } catch (err) {
68
+ if (err.code === 'ENOENT') {
69
+ return x;
70
+ }
71
+
72
+ throw err;
73
+ }
74
+ }
75
+
76
+ function maybeRealpath(realpath, x, opts) {
77
+ if (!opts || !opts.preserveSymlinks) {
78
+ return realpath(x);
79
+ } else {
80
+ return x;
81
+ }
82
+ }
83
+
84
+ async function readPackage(pkgfile) {
85
+ const body = await FS.readFile(pkgfile);
86
+ return JSON.parse(body);
87
+ }
88
+
89
+ function getPackageCandidates(x, start) {
90
+ const dirs = nodeModulesPaths(start);
91
+ for (let i = 0; i < dirs.length; i++) {
92
+ dirs[i] = Path.join(dirs[i], x);
93
+ }
94
+
95
+ return dirs;
96
+ }
97
+
98
+ async function loadAsFile(x) {
99
+ const extensions = ["", ".js"];
100
+ for (const ext of extensions) {
101
+ const file = x + ext;
102
+ if (await isFile(file)) {
103
+ return file;
104
+ }
105
+ }
106
+
107
+ return x;
108
+ }
109
+
110
+ async function loadpkg(dir) {
111
+ if (dir === '' || dir === '/') {
112
+ return null;
113
+ }
114
+
115
+ if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
116
+ return null;
117
+ }
118
+
119
+ if ((/[/\\]node_modules[/\\]*$/).test(dir)) {
120
+ return null;
121
+ }
122
+
123
+ dir = await maybeRealpath(realpath, dir);
124
+ const pkgfile = Path.join(dir, 'package.json');
125
+ if (!await isFile(pkgfile)) {
126
+ return loadpkg(Path.dirname(dir));
127
+ }
128
+
129
+ return await readPackage(pkgfile);
130
+ }
131
+
132
+ async function loadAsDirectory(x) {
133
+ let pkgdir;
134
+ try {
135
+ pkgdir = await maybeRealpath(realpath, x);
136
+ } catch (err) {
137
+ throw err;
138
+ }
139
+
140
+ const pkgfile = Path.join(pkgdir, 'package.json');
141
+ if (!await isFile(pkgfile)) {
142
+ return loadAsFile(Path.join(x, '/index'));
143
+ }
144
+
145
+ const pkg = await readPackage(pkgfile);
146
+ if (pkg && pkg.main) {
147
+ return loadAsFile(Path.join(x, pkg.main));
148
+ } else if (pkg && pkg.module) {
149
+ return loadAsFile(Path.join(x, pkg.module));
150
+ }
151
+
152
+ return loadAsFile(Path.join(x, '/index'));
153
+ }
154
+
155
+ async function processDirs(dirs) {
156
+ for (const dir of dirs) {
157
+ if (await isDirectory(dir)) {
158
+ return loadAsDirectory(dir);
159
+ }
160
+
161
+ const result = await loadAsFile(dir);
162
+ if (result) {
163
+ return result;
164
+ }
165
+ }
166
+ }
167
+
168
+ async function loadNodeModules(x, start) {
169
+ const dirs = getPackageCandidates(x, start);
170
+ return processDirs(dirs) || x;
171
+ }
172
+
173
+ export default async function resolve(specifier, basedir) {
174
+ if (typeof specifier !== 'string') {
175
+ throw new TypeError('specifier must be a string');
176
+ }
177
+
178
+ // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
179
+ let absoluteStart = Path.resolve(basedir);
180
+
181
+ absoluteStart = await maybeRealpath(
182
+ realpath,
183
+ absoluteStart,
184
+ );
185
+
186
+ if (!isDirectory(absoluteStart)) {
187
+ throw new Error(`Cannot resolve ${basedir} to a directory`);
188
+ }
189
+
190
+ if (isCore(specifier)) {
191
+ return specifier;
192
+ } else if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(specifier)) {
193
+ throw new Error("This shouldn't happen");
194
+ }
195
+
196
+ return loadNodeModules(specifier, basedir);
197
+ }