element
+ this.summary = null;
+ // Store the element
+ this.content = null;
+
+ // Store the animation object (so we can cancel it if needed)
+ this.animation = null;
+ // Store if the element is closing
+ this.isClosing = null;
+ // Store if the element is expanding
+ this.isExpanding = null;
+ }
+ }
}
export const run = () => {
let details = Array.from(document.querySelectorAll("details"));
if (details.length > 0) {
details.forEach((el) => {
- new Accordion(el);
+ if (el && !detailsEls.has(el))
+ detailsEls.set(el, new Accordion(el));
});
}
}
\ No newline at end of file
diff --git a/src/ts/plugins/cdn.ts b/src/ts/plugins/cdn.ts
index 37d7419..497b4a1 100644
--- a/src/ts/plugins/cdn.ts
+++ b/src/ts/plugins/cdn.ts
@@ -13,7 +13,7 @@ export const CDN_RESOLVE = (host?: string): (args: OnResolveArgs) => OnResolveRe
return async (args) => {
if (isBareImport(args.path)) {
// Heavily based off of https://github.com/egoist/play-esbuild/blob/main/src/lib/esbuild.ts
- const parsed = parsePackageName(args.path);
+ let parsed = parsePackageName(args.path);
let subpath = parsed.path;
let pkg = args.pluginData?.pkg ?? {};
let path;
@@ -37,6 +37,15 @@ export const CDN_RESOLVE = (host?: string): (args: OnResolveArgs) => OnResolveRe
pluginData: { pkg }
};
}
+ } else if (("dependencies" in pkg || "devDependencies" in pkg) && !/\S+@\S+/.test(args.path)) {
+ let { devDependencies = {}, dependencies = {} } = pkg;
+ let deps = Object.assign({}, devDependencies, dependencies);
+ let keys = Object.keys(deps);
+
+ if (keys.includes(args.path)) {
+ parsed = parsePackageName(args.path + "@" + deps[args.path]);
+ subpath = parsed.path;
+ }
}
if (!subpath) {
@@ -55,7 +64,7 @@ export const CDN_RESOLVE = (host?: string): (args: OnResolveArgs) => OnResolveRe
if (subpath && subpath[0] !== "/")
subpath = `/${subpath}`;
- let { url } = getCDNHost(`${parsed.name}@${parsed.version}${subpath}`);
+ let { url } = getCDNHost(`${parsed.name}@${parsed.version}${subpath}`, host);
return {
namespace: HTTP_NAMESPACE,
path: url,
diff --git a/src/ts/register-sw.ts b/src/ts/register-sw.ts
index f1147fb..de03a87 100644
--- a/src/ts/register-sw.ts
+++ b/src/ts/register-sw.ts
@@ -1,7 +1,8 @@
import { Workbox } from "workbox-window";
import { animate } from "@okikio/animate";
+
+import { ENABLE_SW } from "../../env";
-export const ENABLE_SW = true;
export default () => {
// Check that service workers are supported
(async () => {
diff --git a/src/ts/util/ansi.ts b/src/ts/util/ansi.ts
new file mode 100644
index 0000000..efb19f4
--- /dev/null
+++ b/src/ts/util/ansi.ts
@@ -0,0 +1,109 @@
+// Based off of @hyrious esbuild-repl https://github.com/hyrious/esbuild-repl/blob/main/src/helpers/ansi.ts
+// https://github.com/evanw/esbuild/blob/master/internal/logger/logger.go
+const ESCAPE_TO_COLOR = {
+ "37": "dim",
+ "31": "red",
+ "32": "green",
+ "34": "blue",
+ "36": "cyan",
+ "35": "magenta",
+ "33": "yellow",
+ "41;31": "red-bg-red",
+ "41;97": "red-bg-white",
+ "42;32": "green-bg-green",
+ "42;97": "green-bg-white",
+ "44;34": "blue-bg-blue",
+ "44;97": "blue-bg-white",
+ "46;36": "cyan-bg-cyan",
+ "46;30": "cyan-bg-black",
+ "45;35": "magenta-bg-magenta",
+ "45;30": "magenta-bg-black",
+ "43;33": "yellow-bg-yellow",
+ "43;30": "yellow-bg-black",
+ } as const;
+
+ type Escape = "0" | "1" | "4" | keyof typeof ESCAPE_TO_COLOR;
+
+ type Color = typeof ESCAPE_TO_COLOR[keyof typeof ESCAPE_TO_COLOR];
+
+ // https://github.com/sindresorhus/escape-goat
+ function htmlEscape(string: string) {
+ return string
+ .replace(/\
/g, "\n")
+ .replace(/\&/g, "&")
+ .replace(/\"/g, """)
+ .replace(/\'/g, "'")
+ .replace(/\/g, ">");
+ }
+
+ class AnsiBuffer {
+ result = "";
+ _stack: string[] = [];
+ _bold = false;
+ _underline = false;
+ _link = false;
+ text(text: string) {
+ this.result += htmlEscape(text);
+ }
+ reset() {
+ let close: string | undefined;
+ while ((close = this._stack.pop())) {
+ this.result += close;
+ }
+ }
+ bold() {
+ if (!this._bold) {
+ this._bold = true;
+ this.result += "";
+ this._stack.push("");
+ }
+ }
+ underline() {
+ if (!this._underline) {
+ this._underline = true;
+ this.result += "";
+ this._stack.push("");
+ }
+ }
+ last() {
+ return this._stack[this._stack.length - 1];
+ }
+ color(color: Color) {
+ let close: string | undefined;
+ while ((close = this.last()) === "") {
+ this._stack.pop();
+ this.result += close;
+ }
+ this.result += ``;
+ this._stack.push("");
+ }
+ done() {
+ this.reset();
+ return this.result;
+ }
+ }
+
+ export function render(ansi: string) {
+ ansi = ansi.trimEnd();
+ let i = 0;
+ const buffer = new AnsiBuffer();
+ for (let m of ansi.matchAll(/\x1B\[([\d;]+)m/g)) {
+ const escape = m[1] as Escape;
+ buffer.text(ansi.slice(i, m.index));
+ i = m.index! + m[0].length;
+ /* */ if (escape === "0") {
+ buffer.reset();
+ } else if (escape === "1") {
+ buffer.bold();
+ } else if (escape === "4") {
+ buffer.underline();
+ } else if (ESCAPE_TO_COLOR[escape]) {
+ buffer.color(ESCAPE_TO_COLOR[escape]);
+ }
+ }
+ if (i < ansi.length) {
+ buffer.text(ansi.slice(i));
+ }
+ return buffer.done();
+ }
\ No newline at end of file
diff --git a/src/ts/util/cache.ts b/src/ts/util/cache.ts
index bc69b61..eb5c20b 100644
--- a/src/ts/util/cache.ts
+++ b/src/ts/util/cache.ts
@@ -11,6 +11,9 @@ export const getRequest = async (url: RequestInfo, permanent: boolean = false) =
let cacheResponse = await cache.match(request);
response = cacheResponse;
+ // If permanent is true, primarily use the cache, and only go to network
+ // if there is nothing in cache,
+ // otherwise, use network request
if (permanent) {
if (!cacheResponse) {
let networkResponse = await fetch(request);
@@ -26,6 +29,9 @@ export const getRequest = async (url: RequestInfo, permanent: boolean = false) =
let cacheResponse = CACHE.get(request);
let response = cacheResponse;
+ // If permanent is true, primarily use the cache, and only go to network
+ // if there is nothing in cache,
+ // otherwise, use network request
if (permanent) {
if (!cacheResponse) {
let networkResponse = await fetch(request);
diff --git a/src/ts/util/loader.ts b/src/ts/util/loader.ts
index f388154..d0593e9 100644
--- a/src/ts/util/loader.ts
+++ b/src/ts/util/loader.ts
@@ -1,16 +1,10 @@
import type { Loader } from 'esbuild';
+import { isAbsolute, extname } from './path';
-// Based on https://github.com/sindresorhus/path-is-absolute/blob/main/index.js
-export const isAbsolute = (path: string) => {
- return path.length > 0 && path.charAt(0) === '/';
+export const isBareImport = (url: string) => {
+ return /^(?!\.).*/.test(url) && !isAbsolute(url);
}
-// Based on https://github.com/egoist/play-esbuild/blob/main/src/lib/path.ts
-export const extname = (path: string) => {
- const m = /(\.[a-zA-Z0-9]+)$/.exec(path);
- return m ? m[1] : "";
- }
-
// Based on https://github.com/egoist/play-esbuild/blob/main/src/lib/esbuild.ts
export const RESOLVE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".css", ".json"];
export const inferLoader = (url: string): Loader => {
@@ -30,28 +24,25 @@ export const inferLoader = (url: string): Loader => {
return ext.length ? "text" : "ts";
}
-export const isBareImport = (url: string) => {
- return /^(?!\.).*/.test(url) && !isAbsolute(url);
-}
-
-export const HOST = 'https://cdn.skypack.dev/';
-export const getCDNHost = (url: string) => {
+export const HOST = 'https://unpkg.com';
+export const getCDNHost = (url: string, host = HOST) => {
let argPath = url.replace(/^(skypack|esm|esm\.sh|unpkg|jsdelivr|esm\.run)\:/, "");
- let host = HOST;
if (/^skypack\:/.test(url)) {
- host = `https://cdn.skypack.dev/`;
+ host = `https://cdn.skypack.dev`;
} else if (/^(esm\.sh|esm)\:/.test(url)) {
- host = `https://cdn.esm.sh/`;
+ host = `https://cdn.esm.sh`;
} else if (/^unpkg\:/.test(url)) {
- host = `https://unpkg.com/`;
+ host = `https://unpkg.com`;
} else if (/^(jsdelivr|esm\.run)\:/.test(url)) {
- host = `https://cdn.jsdelivr.net/npm/`;
+ host = `https://cdn.jsdelivr.net/npm`;
}
// typescript will only work on esm.sh
else if (/^typescript/.test(url)) {
- host = `https://unpkg.com/`;
+ host = `https://unpkg.com`;
}
+
+ host = /\/$/.test(host) ? host : `${host}/`;
+ return { argPath, host, url: host + argPath.replace(/^\//, "") };
+}
- return { argPath, host };
-}
\ No newline at end of file
diff --git a/src/ts/util/path.ts b/src/ts/util/path.ts
new file mode 100644
index 0000000..3fabbab
--- /dev/null
+++ b/src/ts/util/path.ts
@@ -0,0 +1,136 @@
+// Based on https://github.com/sindresorhus/path-is-absolute/blob/main/index.js
+export const isAbsolute = (path: string) => {
+ return path.length > 0 && path.charAt(0) === '/';
+}
+
+// Based on https://github.com/egoist/play-esbuild/blob/main/src/lib/path.ts
+export const extname = (path: string) => {
+ const m = /(\.[a-zA-Z0-9]+)$/.exec(path);
+ return m ? m[1] : "";
+}
+
+/**
+ * Everything below this line is based off of https://github.com/egoist/play-esbuild/blob/main/src/lib/path.ts
+ */
+ export const assertPath = (path: string) => {
+ if (typeof path !== "string") {
+ throw new TypeError(
+ `Path must be a string. Received ${JSON.stringify(path)}`
+ )
+ }
+}
+
+export const CHAR_DOT = 46; /* . */
+export const CHAR_FORWARD_SLASH = 47; /* / */
+
+// Resolves . and .. elements in a path with directory names
+export const normalizeString = (
+ path: string,
+ allowAboveRoot: boolean,
+ separator: string,
+ isPathSeparator: (code: number) => boolean
+): string => {
+ let res = ""
+ let lastSegmentLength = 0
+ let lastSlash = -1
+ let dots = 0
+ let code: number | undefined
+ for (let i = 0, len = path.length; i <= len; ++i) {
+ if (i < len) code = path.charCodeAt(i)
+ else if (isPathSeparator(code!)) break
+ else code = CHAR_FORWARD_SLASH
+
+ if (isPathSeparator(code!)) {
+ if (lastSlash === i - 1 || dots === 1) {
+ // NOOP
+ } else if (lastSlash !== i - 1 && dots === 2) {
+ if (
+ res.length < 2 ||
+ lastSegmentLength !== 2 ||
+ res.charCodeAt(res.length - 1) !== CHAR_DOT ||
+ res.charCodeAt(res.length - 2) !== CHAR_DOT
+ ) {
+ if (res.length > 2) {
+ const lastSlashIndex = res.lastIndexOf(separator)
+ if (lastSlashIndex === -1) {
+ res = ""
+ lastSegmentLength = 0
+ } else {
+ res = res.slice(0, lastSlashIndex)
+ lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
+ }
+ lastSlash = i
+ dots = 0
+ continue
+ } else if (res.length === 2 || res.length === 1) {
+ res = ""
+ lastSegmentLength = 0
+ lastSlash = i
+ dots = 0
+ continue
+ }
+ }
+ if (allowAboveRoot) {
+ if (res.length > 0) res += `${separator}..`
+ else res = ".."
+ lastSegmentLength = 2
+ }
+ } else {
+ if (res.length > 0) res += separator + path.slice(lastSlash + 1, i)
+ else res = path.slice(lastSlash + 1, i)
+ lastSegmentLength = i - lastSlash - 1
+ }
+ lastSlash = i
+ dots = 0
+ } else if (code === CHAR_DOT && dots !== -1) {
+ ++dots
+ } else {
+ dots = -1
+ }
+ }
+ return res
+}
+
+export const isPosixPathSeparator = (code: number): boolean => {
+ return code === CHAR_FORWARD_SLASH
+}
+
+export const normalize = (path: string): string => {
+ assertPath(path)
+
+ if (path.length === 0) return "."
+
+ const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
+ const trailingSeparator =
+ path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH
+
+ // Normalize the path
+ path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator)
+
+ if (path.length === 0 && !isAbsolute) path = "."
+ if (path.length > 0 && trailingSeparator) path += "/"
+
+ if (isAbsolute) return `/${path}`
+ return path
+}
+
+export const join = (...paths: string[]): string => {
+ if (paths.length === 0) return "."
+ let joined: string | undefined
+ for (let i = 0, len = paths.length; i < len; ++i) {
+ const path = paths[i]
+ assertPath(path)
+ if (path.length > 0) {
+ if (!joined) joined = path
+ else joined += `/${path}`
+ }
+ }
+ if (!joined) return "."
+ return normalize(joined)
+}
+
+export const urlJoin = (url: string, ...args: string[]) => {
+ const u = new URL(url)
+ u.pathname = join(u.pathname, ...args)
+ return u.toString()
+}
\ No newline at end of file
diff --git a/src/ts/util/resolve-imports.js b/src/ts/util/resolve-imports.js
new file mode 100644
index 0000000..03262ad
--- /dev/null
+++ b/src/ts/util/resolve-imports.js
@@ -0,0 +1,112 @@
+/** resolve.exports but for imports */
+/**
+ * @param {object} imports
+ * @param {Set} keys
+ */
+ function loop(imports, keys) {
+ if (typeof imports === 'string') {
+ return imports;
+ }
+
+ if (imports) {
+ let idx, tmp;
+ if (Array.isArray(imports)) {
+ for (idx=0; idx < imports.length; idx++) {
+ if (tmp = loop(imports[idx], keys)) return tmp;
+ }
+ } else {
+ for (idx in imports) {
+ if (keys.has(idx)) {
+ return loop(imports[idx], keys);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @param {string} name The package name
+ * @param {string} entry The target entry, eg "."
+ * @param {number} [condition] Unmatched condition?
+ */
+function bail(name, entry, condition) {
+ throw new Error(
+ condition
+ ? `No known conditions for "${entry}" entry in "${name}" package`
+ : `Missing "${entry}" import in "${name}" package`
+ );
+}
+
+/**
+ * @param {string} name the package name
+ * @param {string} entry the target path/import
+ */
+function toName(name, entry) {
+ return entry === name ? '.'
+ : entry[0] === '.' ? entry
+ : entry.replace(new RegExp('^' + name + '\/'), './');
+}
+
+/**
+ * @param {object} pkg package.json contents
+ * @param {string} [entry] entry name or import path
+ * @param {object} [options]
+ * @param {boolean} [options.browser]
+ * @param {boolean} [options.require]
+ * @param {string[]} [options.conditions]
+ * @param {boolean} [options.unsafe]
+ */
+export function resolveImports(pkg, entry='.', options={}) {
+ let { name, imports } = pkg;
+
+ if (imports) {
+ let { browser, require, unsafe, conditions=[] } = options;
+
+ let target = toName(name, entry);
+ // if (target[0] !== '.') target = './' + target;
+
+ if (typeof imports === 'string') {
+ return target === '#' ? imports : bail(name, target);
+ }
+
+ let allows = new Set(['default', ...conditions]);
+ unsafe || allows.add(require ? 'require' : 'import');
+ unsafe || allows.add(browser ? 'browser' : 'node');
+
+ let key, tmp, isSingle=false;
+
+ for (key in imports) {
+ isSingle = key[0] !== '#';
+ break;
+ }
+
+ if (isSingle) {
+ return target === '#'
+ ? loop(imports, allows) || bail(name, target, 1)
+ : bail(name, target);
+ }
+
+ if (tmp = imports[target]) {
+ return loop(tmp, allows) || bail(name, target, 1);
+ }
+
+ for (key in imports) {
+ tmp = key[key.length - 1];
+ if (tmp === '/' && target.startsWith(key)) {
+ return (tmp = loop(imports[key], allows))
+ ? (tmp + target.substring(key.length))
+ : bail(name, target, 1);
+ }
+ if (tmp === '*' && target.startsWith(key.slice(0, -1))) {
+ // do not trigger if no *content* to inject
+ if (target.substring(key.length - 1).length > 0) {
+ return (tmp = loop(imports[key], allows))
+ ? tmp.replace('*', target.substring(key.length - 1))
+ : bail(name, target, 1);
+ }
+ }
+ }
+
+ return bail(name, target);
+ }
+}
\ No newline at end of file
diff --git a/src/ts/workers/esbuild.ts b/src/ts/workers/esbuild.ts
index dcf8885..019c7eb 100644
--- a/src/ts/workers/esbuild.ts
+++ b/src/ts/workers/esbuild.ts
@@ -9,6 +9,7 @@ import { HTTP } from "../plugins/http";
import { CDN } from "../plugins/cdn";
import { encode, decode } from "../util/encode-decode";
+import { render as ansi } from "../util/ansi";
import type { BuildResult, OutputFile, BuildIncremental, PartialMessage } from "esbuild-wasm";
@@ -33,9 +34,9 @@ export const initEvent = new EventEmitter();
// Inspired by https://github.com/egoist/play-esbuild/blob/main/src/lib/esbuild.ts
// I didn't even know this was exported by esbuild, great job @egoist
-export const createNotice = async (errors: PartialMessage[], kind: "error" | "warning" = "error") => {
- let res = await formatMessages(errors, { kind });
- return res.join("\n\n");
+export const createNotice = async (errors: PartialMessage[], kind: "error" | "warning" = "error", color = true) => {
+ let notices = await formatMessages(errors, { color, kind });
+ return notices.map((msg) => !color ? msg : ansi(msg.replace(/(\s+)(\d+)(\s+)\│/, "\n$1$2$3│")));
}
export const start = async (port) => {
@@ -47,23 +48,39 @@ export const start = async (port) => {
port.postMessage(encodedMessage, [encodedMessage.buffer]);
};
- initEvent.on({
- // When the SharedWorker first loads, tell the page that esbuild has initialized
- init() {
+ const logger = (messages: string[] | any, type?: "error" | "warning" | any) => {
+ let msgs = Array.isArray(messages) ? messages : [messages];
+ if (type == "init") {
postMessage({
event: "init",
- details: {}
+ details: {
+ type: `init`,
+ message: msgs,
+ }
+ });
+ }
+
+ if (type == "error" || type == "warning") {
+ postMessage({
+ event: "log",
+ details: { messages: [`${msgs.length} ${type}(s) ${type == "error" ? "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundle)" : ""}`] }
});
+ }
+
+ postMessage({
+ event: "log",
+ details: { type, messages: msgs }
+ });
+ };
+
+ initEvent.on({
+ // When the SharedWorker first loads, tell the page that esbuild has initialized
+ init() {
+ logger("Initialized 🚀✨", "init");
},
error(error) {
let err = Array.isArray(error) ? error : error?.message;
- postMessage({
- event: "error",
- details: {
- type: `Error initializing, you may need to close and reopen all currently open pages pages`,
- error: Array.isArray(err) ? err : [err],
- }
- });
+ logger([`Error initializing, you may need to close and reopen all currently open pages pages`, ...(Array.isArray(err) ? err : [err])], "error")
}
});
@@ -72,22 +89,16 @@ export const start = async (port) => {
initEvent.emit("init");
BuildEvents.on("build", (input: string) => {
- if (!_initialized) {
- postMessage({
- event: "warn",
- details: {
- type: `esbuild worker not initialized`,
- message: [`You need to wait for a little bit before trying to bundle files`]
- }
- });
+ logger("Bundling 🚀");
+ if (!_initialized) {
+ logger([`esbuild worker not initialized\nYou need to wait for a little bit before trying to bundle files`], "warning");
return;
}
-
(async () => {
let output = "";
-
+
// Stores content from all external outputed files, this is for checking the gzip size when dealing with CSS and other external files
let content: Uint8Array[] = [];
let result: BuildResult & {
@@ -110,7 +121,7 @@ export const start = async (port) => {
treeShaking: true,
incremental: false,
target: ["esnext"],
- logLevel: 'info',
+ logLevel: 'silent',// 'info',
write: false,
outfile: "/bundle.js",
platform: "browser",
@@ -129,14 +140,21 @@ export const start = async (port) => {
},
plugins: [
EXTERNAL(),
- HTTP(),
+ HTTP(logger),
CDN(),
],
globalName: 'bundler',
});
} catch (e) {
if (e.errors) {
- throw [await createNotice(e.errors, "error")];
+ postMessage({
+ event: "error",
+ details: {
+ type: `error`,
+ error: [...await createNotice(e.errors, "error", false)]
+ }
+ });
+ return logger([...await createNotice(e.errors, "error")], "error");
} else throw e;
}
@@ -150,30 +168,36 @@ export const start = async (port) => {
postMessage({
event: "warn",
details: {
- type: `esbuild build warning`,
- message: [await createNotice(result.warnings, "warning")]
+ type: `warning`,
+ message: [...await createNotice(result.warnings, "warning", false)]
}
});
+
+ logger([...await createNotice(result.warnings, "warning")], "warning");
}
- if (result?.errors.length > 0)
- throw [await createNotice(result.errors, "error")];
+ if (result?.errors.length > 0) {
+ postMessage({
+ event: "error",
+ details: {
+ type: `error`,
+ error: [...await createNotice(result.errors, "error", false)]
+ }
+ });
+ return logger([...await createNotice(result.errors, "error")], "error");
+ }
+
+ logger("Done ✨", "info");
} catch (error) {
let err = Array.isArray(error) ? error : error?.message;
- throw {
- event: "error",
- details: {
- type: `esbuild build error`,
- error: Array.isArray(err) ? err : [err]
- }
- };
postMessage({
event: "error",
details: {
- type: `esbuild build error`,
- error: Array.isArray(err) ? err : [err]
+ type: `error`,
+ error: "notColor" in error ? error?.notColor : Array.isArray(err) ? err : [err]
}
});
+ logger(Array.isArray(err) ? err : [err], "error");
return;
}
@@ -196,20 +220,14 @@ export const start = async (port) => {
totalCompressedSize = null;
output = null;
} catch (error) {
- throw {
- event: "error",
- details: {
- type: `gzip error`,
- error
- }
- };
- postMessage({
- event: "error",
- details: {
- type: `gzip error`,
- error
- }
- });
+ // postMessage({
+ // event: "error",
+ // details: {
+ // type: `error`,
+ // error
+ // }
+ // });
+ logger([error], "error");
}
})();
});