diff --git a/packages/core/package.json b/packages/core/package.json index d4ca4c6..d33678b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -82,7 +82,6 @@ }, "homepage": "https://bundlejs.com", "dependencies": { - "@okikio/emitter": "^2.1.7", "esbuild": "0.17.8", "esbuild-wasm": "0.17.8" }, diff --git a/packages/core/src/build.ts b/packages/core/src/build.ts index 2c85ba2..2953803 100644 --- a/packages/core/src/build.ts +++ b/packages/core/src/build.ts @@ -6,16 +6,17 @@ import { ALIAS } from "./plugins/alias.ts"; import { HTTP } from "./plugins/http.ts"; import { CDN } from "./plugins/cdn.ts"; -import { EVENTS } from "./configs/events.ts"; import { createConfig } from "./configs/config.ts"; import { PLATFORM_AUTO } from "./configs/platform.ts"; import { createState, getState, setState } from "./configs/state.ts"; -import { getFile, setFile, getResolvedPath, useFileSystem, IFileSystem } from "./utils/filesystem.ts"; +import { useFileSystem } from "./utils/filesystem.ts"; import { createNotice } from "./utils/create-notice.ts"; import { DEFAULT_CDN_HOST } from "./utils/util-cdn.ts"; import { init } from "./init.ts"; +import { BUILD_ERROR, INIT_LOADING, LOGGER_ERROR, LOGGER_LOG, dispatchEvent } from "./configs/events.ts"; + /** * Local state available to all plugins */ @@ -91,11 +92,11 @@ export type BuildResult = (ESBUILD.BuildResult) & { contents: ESBUILD.OutputFile[]; }; -export const TheFileSystem = useFileSystem(EVENTS); +export const TheFileSystem = useFileSystem(); export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): Promise { if (!getState("initialized")) - EVENTS.emit("init.loading"); + dispatchEvent(INIT_LOADING); const CONFIG = createConfig("build", opts); const STATE = createState({ @@ -135,11 +136,11 @@ export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): write: false, outdir: "/", plugins: [ - ALIAS(EVENTS, STATE, CONFIG), - EXTERNAL(EVENTS, STATE, CONFIG), - HTTP(EVENTS, STATE, CONFIG), - CDN(EVENTS, STATE, CONFIG), - VIRTUAL_FS(EVENTS, STATE, CONFIG), + ALIAS(STATE, CONFIG), + EXTERNAL(STATE, CONFIG), + HTTP(STATE, CONFIG), + CDN(STATE, CONFIG), + VIRTUAL_FS(STATE, CONFIG), ], ...esbuildOpts, }); @@ -148,11 +149,10 @@ export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): // Log errors with added color info. to the virtual console const asciMsgs = [...await createNotice(e.errors, "error", false)]; const htmlMsgs = [...await createNotice(e.errors, "error")]; + dispatchEvent(LOGGER_ERROR, new Error(JSON.stringify({ asciMsgs, htmlMsgs }))); - EVENTS.emit("logger.error", asciMsgs, htmlMsgs); - - const message = (htmlMsgs.length > 1 ? `${htmlMsgs.length} error(s) ` : "") + "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundle)"; - EVENTS.emit("logger.error", message); + const message = (htmlMsgs.length > 1 ? `${htmlMsgs.length} error(s) ` : "") + "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundlejs)"; + dispatchEvent(LOGGER_ERROR, new Error(message)); return; } else throw e; } @@ -173,9 +173,9 @@ export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): if (esbuildOpts?.logLevel == "verbose") { const ignoreFile = /\.(wasm|png|jpeg|webp)$/.test(path); if (ignoreFile) { - EVENTS.emit("logger.log", "Output File: " + path); + dispatchEvent(LOGGER_LOG, "Output File: " + path); } else { - EVENTS.emit("logger.log", "Output File: " + path + "\n" + text); + dispatchEvent(LOGGER_LOG, "Output File: " + path + "\n" + text); } } @@ -204,6 +204,6 @@ export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): ...result }; } catch (e) { - EVENTS.emit("build.error", e); + dispatchEvent(BUILD_ERROR, e); } } \ No newline at end of file diff --git a/packages/core/src/configs/events.ts b/packages/core/src/configs/events.ts index 45d947e..d538b91 100644 --- a/packages/core/src/configs/events.ts +++ b/packages/core/src/configs/events.ts @@ -1,17 +1,89 @@ -import { EventEmitter } from "@okikio/emitter"; -export const EVENTS_OPTS = { - "init.start": console.log, - "init.complete": console.info, - "init.error": console.error, - "init.loading": console.warn, - - "logger.log": console.log, - "logger.error": console.error, - "logger.warn": console.warn, - "logger.info": console.info, - - "build.error": console.error, -}; - -export const EVENTS = new EventEmitter(); -EVENTS.on(EVENTS_OPTS); \ No newline at end of file +export const EVENT_NAME_PREFIX = "bundlejs"; +export function EventName(name: T) { + return `${EVENT_NAME_PREFIX}.${name}` as const; +} + +export const INIT_START = EventName("init.start"); +export const INIT_COMPLETE = EventName("init.complete"); +export const INIT_ERROR = EventName("init.error"); +export const INIT_LOADING = EventName("init.loading"); + +export const LOGGER_LOG = EventName("logger.log"); +export const LOGGER_ERROR = EventName("logger.error"); +export const LOGGER_WARN = EventName("logger.warn"); +export const LOGGER_INFO = EventName("logger.info"); + +export const BUILD_ERROR = EventName("build.error"); +export const TRANSFORM_ERROR = EventName("transform.error"); + +export interface IEVENT_MAP { + [INIT_START]: void, + [INIT_COMPLETE]: void, + [INIT_ERROR]: Error, + [INIT_LOADING]: any, + + [LOGGER_LOG]: any, + [LOGGER_ERROR]: Error, + [LOGGER_WARN]: any, + [LOGGER_INFO]: any, + + [BUILD_ERROR]: Error, + [TRANSFORM_ERROR]: Error, +} + +export const EVENT_TARGET = new EventTarget(); + +export class CustomEvent extends Event { + readonly detail: T; + constructor(type: string, options?: CustomEventInit) { + super(type, options) + this.detail = Object(options).detail + } +} + +/** + * Registers an event listener in the global scope, which will be called synchronously whenever the event type is dispatched. + */ +export function addEventListener( + type: K, + listener: (this: Window, ev: CustomEvent) => any | EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, +) { + return EVENT_TARGET.addEventListener(type, listener, options) +} + +/** + * Registers an event listener in the global scope, which will be called synchronously whenever the event type is dispatched. + */ +export function removeEventListener( + type: K, + listener: (this: Window, ev: CustomEvent) => any | EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, +) { + return EVENT_TARGET.removeEventListener(type, listener, options) +} + +/** + * Dispatches an event in the global scope, synchronously invoking any registered event listeners for this event in the appropriate order. + * Returns false if event is cancelable and at least one of the event handlers which handled this event called Event.preventDefault(). + * Otherwise it returns true. + */ +export function dispatchEvent( + event: K | (string & {}) | CustomEvent, + args?: A +) { + return EVENT_TARGET.dispatchEvent( + typeof event === "string" ? + new CustomEvent(event, { detail: args }) : + event + ); +} + +addEventListener(INIT_START, (e) => console.log(e.detail)); +addEventListener(INIT_COMPLETE, (e) => console.info(e.detail)); +addEventListener(INIT_ERROR, (e) => console.error(e.detail)); +addEventListener(LOGGER_LOG, (e) => console.log(e.detail)); +addEventListener(LOGGER_ERROR, (e) => console.error(e.detail)); +addEventListener(LOGGER_WARN, (e) => console.warn(e.detail)); +addEventListener(LOGGER_INFO, (e) => console.info(e.detail)); +addEventListener(BUILD_ERROR, (e) => console.error(e.detail)); \ No newline at end of file diff --git a/packages/core/src/init.ts b/packages/core/src/init.ts index 4a1e603..c677c67 100644 --- a/packages/core/src/init.ts +++ b/packages/core/src/init.ts @@ -3,9 +3,9 @@ import type * as ESBUILD from "esbuild-wasm"; import type { Platform } from "./configs/platform.ts"; import { PLATFORM_AUTO } from "./configs/platform.ts"; -import { EVENTS } from "./configs/events.ts"; import { getState, setState } from "./configs/state.ts"; import { getEsbuild } from "./utils/get-esbuild.ts"; +import { INIT_COMPLETE, INIT_ERROR, INIT_START, dispatchEvent } from "./configs/events.ts"; /** * Configures how esbuild running in wasm is initialized @@ -16,7 +16,7 @@ export async function init(platform = PLATFORM_AUTO, opts: ESBUILD.InitializeOpt try { if (!getState("initialized")) { setState("initialized", true); - EVENTS.emit("init.start"); + dispatchEvent(INIT_START); const esbuild = await getEsbuild(platform); setState("esbuild", esbuild); @@ -37,12 +37,12 @@ export async function init(platform = PLATFORM_AUTO, opts: ESBUILD.InitializeOpt } } - EVENTS.emit("init.complete"); + dispatchEvent(INIT_COMPLETE); } return getState("esbuild"); } catch (error) { - EVENTS.emit("init.error", error); + dispatchEvent(INIT_ERROR, error); console.error(error); } } \ No newline at end of file diff --git a/packages/core/src/plugins/alias.ts b/packages/core/src/plugins/alias.ts index 4561409..d7f4dfa 100644 --- a/packages/core/src/plugins/alias.ts +++ b/packages/core/src/plugins/alias.ts @@ -1,6 +1,5 @@ import type { BuildConfig, LocalState } from "../build.ts"; import type { StateArray } from "../configs/state.ts"; -import type { EVENTS } from "../configs/events.ts"; import type { ESBUILD } from "../types.ts"; import { EXTERNALS_NAMESPACE } from "./external.ts"; @@ -38,7 +37,7 @@ export const isAlias = (id: string, aliases = {}) => { * @param host The default host origin to use if an import doesn't already have one * @param logger Console log */ -export const ALIAS_RESOLVE = (aliases = {}, host = DEFAULT_CDN_HOST, events: typeof EVENTS) => { +export const ALIAS_RESOLVE = (aliases = {}, host = DEFAULT_CDN_HOST) => { return async (args: ESBUILD.OnResolveArgs): Promise => { const path = args.path.replace(/^node\:/, ""); const { path: argPath } = getCDNUrl(path); @@ -46,7 +45,7 @@ export const ALIAS_RESOLVE = (aliases = {}, host = DEFAULT_CDN_HOST, events: typ if (isAlias(argPath, aliases)) { const pkgDetails = parsePackageName(argPath); const aliasPath = aliases[pkgDetails.name]; - return HTTP_RESOLVE(host, events)({ + return HTTP_RESOLVE(host)({ ...args, path: aliasPath }); @@ -61,7 +60,7 @@ export const ALIAS_RESOLVE = (aliases = {}, host = DEFAULT_CDN_HOST, events: typ * @param host The default host origin to use if an import doesn't already have one * @param logger Console log */ -export const ALIAS = (events: typeof EVENTS, state: StateArray, config: BuildConfig): ESBUILD.Plugin => { +export const ALIAS = (state: StateArray, config: BuildConfig): ESBUILD.Plugin => { // Convert CDN values to URL origins const { origin: host } = !/:/.test(config?.cdn) ? getCDNUrl(config?.cdn + ":") : getCDNUrl(config?.cdn); const aliases = config.alias ?? {}; @@ -74,7 +73,7 @@ export const ALIAS = (events: typeof EVENTS, state: StateArray, conf // this plugin. build.onResolve({ filter: /^node\:.*/ }, (args) => { if (isAlias(args.path, aliases)) - return ALIAS_RESOLVE(aliases, host, events)(args); + return ALIAS_RESOLVE(aliases, host)(args); return { path: args.path, @@ -88,8 +87,8 @@ export const ALIAS = (events: typeof EVENTS, state: StateArray, conf // files will be in the "http-url" namespace. Make sure to keep // the newly resolved URL in the "http-url" namespace so imports // inside it will also be resolved as URLs recursively. - build.onResolve({ filter: /.*/ }, ALIAS_RESOLVE(aliases, host, events)); - build.onResolve({ filter: /.*/, namespace: ALIAS_NAMESPACE }, ALIAS_RESOLVE(aliases, host, events)); + build.onResolve({ filter: /.*/ }, ALIAS_RESOLVE(aliases, host)); + build.onResolve({ filter: /.*/, namespace: ALIAS_NAMESPACE }, ALIAS_RESOLVE(aliases, host)); }, }; }; \ No newline at end of file diff --git a/packages/core/src/plugins/cdn.ts b/packages/core/src/plugins/cdn.ts index dbdd005..585bdce 100644 --- a/packages/core/src/plugins/cdn.ts +++ b/packages/core/src/plugins/cdn.ts @@ -1,13 +1,13 @@ import type { BuildConfig, LocalState } from "../build.ts"; import type { StateArray } from "../configs/state.ts"; -import type { EVENTS } from "../configs/events.ts"; import type { ESBUILD } from "../types.ts"; +import { dispatchEvent, LOGGER_WARN } from "../configs/events.ts"; + import { HTTP_NAMESPACE } from "./http.ts"; import { resolveExports, legacy } from "../utils/resolve-exports.ts"; import { parsePackageName as parsePackageName } from "../utils/parse-package-name.ts"; - import { isBareImport } from "../utils/path.ts"; import { getRequest } from "../utils/fetch-and-cache.ts"; @@ -23,7 +23,7 @@ export const CDN_NAMESPACE = "cdn-url"; * @param cdn The default CDN to use * @param logger Console log */ -export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST, events: typeof EVENTS) => { +export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST) => { return async (args: ESBUILD.OnResolveArgs): Promise => { if (isBareImport(args.path)) { // Support a different default CDN + allow for custom CDN url schemes @@ -36,6 +36,7 @@ export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST, events: typeof EVENTS) => { const parsed = parsePackageName(argPath); let subpath = parsed.path; let pkg = args.pluginData?.pkg ?? {}; + let oldPkg = pkg; // Resolving imports from the package.json, if said import starts with "#" // If an import starts with "#" then it's a subpath-import @@ -94,12 +95,8 @@ export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST, events: typeof EVENTS) => { if (subpath && subpath[0] !== "/") subpath = `/${subpath}`; } catch (e) { - events - .emit( - "logger.warn", - `You may want to change CDNs. The current CDN ${!/unpkg\.com/.test(origin) ? `"${origin}" doesn't` : `path "${origin}${argPath}" may not`} support package.json files.\nThere is a chance the CDN you're using doesn't support looking through the package.json of packages. bundlejs will switch to inaccurate guesses for package versions. For package.json support you may wish to use https://unpkg.com or other CDN's that support package.json.` - ) - .emit("logger.warn", e); + dispatchEvent(LOGGER_WARN, `You may want to change CDNs. The current CDN ${!/unpkg\.com/.test(origin) ? `"${origin}" doesn't` : `path "${origin}${argPath}" may not`} support package.json files.\nThere is a chance the CDN you're using doesn't support looking through the package.json of packages. bundlejs will switch to inaccurate guesses for package versions. For package.json support you may wish to use https://unpkg.com or other CDN's that support package.json.`); + dispatchEvent(LOGGER_WARN, e); } } @@ -107,10 +104,21 @@ export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST, events: typeof EVENTS) => { // e.g. https://unpkg.com/spring-easing@v1.0.0/ const version = NPM_CDN ? "@" + parsed.version : ""; const { url } = getCDNUrl(`${parsed.name}${version}${subpath}`, origin); + + let deps = Object.assign({}, oldPkg.peerDependencies, oldPkg.devDependencies, oldPkg.dependencies); + let peerDeps = pkg.peerDependencies ?? {}; + let peerDepsKeys = Object.keys(peerDeps); + for (let depKey of peerDepsKeys) { + peerDeps[depKey] = deps[depKey] ?? peerDeps[depKey]; + } + let newPkg = { + ...pkg, + peerDependencies: peerDeps + } return { namespace: HTTP_NAMESPACE, path: url.toString(), - pluginData: { pkg } + pluginData: { pkg: newPkg } }; } }; @@ -122,15 +130,15 @@ export const CDN_RESOLVE = (cdn = DEFAULT_CDN_HOST, events: typeof EVENTS) => { * @param cdn The default CDN to use * @param logger Console log */ -export function CDN (events: typeof EVENTS, state: StateArray, config: BuildConfig): ESBUILD.Plugin { +export function CDN (state: StateArray, config: BuildConfig): ESBUILD.Plugin { // Convert CDN values to URL origins const { origin: cdn } = !/:/.test(config?.cdn) ? getCDNUrl(config?.cdn + ":") : getCDNUrl(config?.cdn); return { name: CDN_NAMESPACE, setup(build) { // Resolve bare imports to the CDN required using different URL schemes - build.onResolve({ filter: /.*/ }, CDN_RESOLVE(cdn, events)); - build.onResolve({ filter: /.*/, namespace: CDN_NAMESPACE }, CDN_RESOLVE(cdn, events)); + build.onResolve({ filter: /.*/ }, CDN_RESOLVE(cdn)); + build.onResolve({ filter: /.*/, namespace: CDN_NAMESPACE }, CDN_RESOLVE(cdn)); }, }; } diff --git a/packages/core/src/plugins/external.ts b/packages/core/src/plugins/external.ts index 729caed..b805759 100644 --- a/packages/core/src/plugins/external.ts +++ b/packages/core/src/plugins/external.ts @@ -1,6 +1,5 @@ import type { BuildConfig, LocalState } from "../build.ts"; import type { StateArray } from "../configs/state.ts"; -import type { EVENTS } from "../configs/events.ts"; import type { ESBUILD } from "../types.ts"; import { encode } from "../utils/encode-decode.ts"; @@ -81,7 +80,7 @@ export const isExternal = (id: string, external: string[] = []) => { * * @param external List of packages to marks as external */ -export function EXTERNAL (events: typeof EVENTS, state: StateArray, config: BuildConfig): ESBUILD.Plugin { +export function EXTERNAL (state: StateArray, config: BuildConfig): ESBUILD.Plugin { const { external = [] } = config?.esbuild ?? {}; return { name: EXTERNALS_NAMESPACE, diff --git a/packages/core/src/plugins/http.ts b/packages/core/src/plugins/http.ts index 0e799f0..17950c7 100644 --- a/packages/core/src/plugins/http.ts +++ b/packages/core/src/plugins/http.ts @@ -1,9 +1,10 @@ /** Based on https://github.com/hardfist/neo-tools/blob/main/packages/bundler/src/plugins/http.ts */ import type { BuildConfig, LocalState } from "../build.ts"; import type { StateArray } from "../configs/state.ts"; -import type { EVENTS } from "../configs/events.ts"; import type { ESBUILD } from "../types.ts"; +import { dispatchEvent, LOGGER_ERROR, LOGGER_INFO, LOGGER_WARN } from "../configs/events.ts"; + import { CDN_RESOLVE } from "./cdn.ts"; import { getRequest } from "../utils/fetch-and-cache.ts"; import { decode } from "../utils/encode-decode.ts"; @@ -23,13 +24,13 @@ export const HTTP_NAMESPACE = "http-url"; * @param url package url to fetch * @param logger Console log */ -export const fetchPkg = async (url: string, events: typeof EVENTS) => { +export const fetchPkg = async (url: string) => { try { const response = await getRequest(url); if (!response.ok) throw new Error(`Couldn't load ${response.url} (${response.status} code)`); - events.emit("logger.info", `Fetch ${url}`); + dispatchEvent(LOGGER_INFO, `Fetch ${url}`); return { // Deno doesn't have a `response.url` which is odd but whatever @@ -51,8 +52,11 @@ export const fetchPkg = async (url: string, events: typeof EVENTS) => { * @param namespace esbuild plugin namespace * @param logger Console log */ -export const fetchAssets = async (path: string, content: Uint8Array, namespace: string, events: typeof EVENTS, state: StateArray) => { - const rgx = /new URL\(['"`](.*)['"`],(?:\s+)?import\.meta\.url(?:\s+)?\)/g; +export const fetchAssets = async (path: string, content: Uint8Array, namespace: string, state: StateArray) => { + // Regex for `new URL("./path.js", import.meta.url)`, + // I added support for comments so you can add comments and the regex + // will ignore the comments + const rgx = /new(?:\s|\n?)+URL\((?:\s*(?:\/\*(?:.*\n)*\*\/)?(?:\/\/.*\n)?)*(?:(?!\`.*\$\{)['"`](.*)['"`]),(?:\s*(?:\/\*(?:.*\n)*\*\/)?(?:\/\/.*\n)?)*import\.meta\.url(?:\s*(?:\/\*(?:.*\n)*\*\/)?(?:\/\/.*\n)?)*\)/g; const parentURL = new URL("./", path).toString(); // const FileSystem = config.filesystem; @@ -63,7 +67,7 @@ export const fetchAssets = async (path: string, content: Uint8Array, namespace: const matches = Array.from(code.matchAll(rgx)) as RegExpMatchArray[]; const promises = matches.map(async ([, assetURL]) => { - const { content: asset, url } = await fetchPkg(urlJoin(parentURL, assetURL), events); + const { content: asset, url } = await fetchPkg(urlJoin(parentURL, assetURL)); // Create a virtual file system for storing assets // This is for building a package bundle analyzer @@ -84,7 +88,7 @@ export const fetchAssets = async (path: string, content: Uint8Array, namespace: * @param host The default host origin to use if an import doesn't already have one * @param logger Console log */ -export const HTTP_RESOLVE = (host = DEFAULT_CDN_HOST, events: typeof EVENTS) => { +export const HTTP_RESOLVE = (host = DEFAULT_CDN_HOST) => { return async (args: ESBUILD.OnResolveArgs): Promise => { // Some packages use "../../" with the assumption that "/" is equal to "/index.js", this is supposed to fix that bug const argPath = args.path.replace(/\/$/, "/index"); @@ -111,7 +115,7 @@ export const HTTP_RESOLVE = (host = DEFAULT_CDN_HOST, events: typeof EVENTS) => // If the import is a bare import, use the CDN plugins resolution algorithm if (isBareImport(argPath)) { - return CDN_RESOLVE(origin, events)(args); + return CDN_RESOLVE(origin)(args); } else { /** * If the import is neither an http import or a bare import (module import), then it is an absolute import. @@ -152,7 +156,7 @@ export const HTTP_RESOLVE = (host = DEFAULT_CDN_HOST, events: typeof EVENTS) => * @param host The default host origin to use if an import doesn't already have one * @param logger Console log */ -export function HTTP (events: typeof EVENTS, state: StateArray, config: BuildConfig): ESBUILD.Plugin { +export function HTTP (state: StateArray, config: BuildConfig): ESBUILD.Plugin { // Convert CDN values to URL origins const { origin: host } = !/:/.test(config?.cdn) ? getCDNUrl(config?.cdn + ":") : getCDNUrl(config?.cdn); @@ -180,7 +184,7 @@ export function HTTP (events: typeof EVENTS, state: StateArray, conf // files will be in the "http-url" namespace. Make sure to keep // the newly resolved URL in the "http-url" namespace so imports // inside it will also be resolved as URLs recursively. - build.onResolve({ filter: /.*/, namespace: HTTP_NAMESPACE }, HTTP_RESOLVE(host, events)); + build.onResolve({ filter: /.*/, namespace: HTTP_NAMESPACE }, HTTP_RESOLVE(host)); // When a URL is loaded, we want to actually download the content // from the internet. This has just enough logic to be able to @@ -201,7 +205,7 @@ export function HTTP (events: typeof EVENTS, state: StateArray, conf for (let i = 0; i < extLength; i++) { const extPath = exts[i]; try { - ({ content, url } = await fetchPkg(argPath(extPath), events)); + ({ content, url } = await fetchPkg(argPath(extPath))); break; } catch (e) { if (i == 0) @@ -210,7 +214,7 @@ export function HTTP (events: typeof EVENTS, state: StateArray, conf // If after checking all the different file extensions none of them are valid // Throw the first fetch error encountered, as that is generally the most accurate error if (i >= extLength - 1) { - events.emit("logger.error", e.toString()); + dispatchEvent(LOGGER_ERROR, e); throw err; } } @@ -223,10 +227,10 @@ export function HTTP (events: typeof EVENTS, state: StateArray, conf await setFile(FileSystem, args.namespace + ":" + args.path, content) const _assetResults = - (await fetchAssets(url, content, args.namespace, events, state)) + (await fetchAssets(url, content, args.namespace, state)) .filter((result) => { if (result.status == "rejected") { - events.emit("logger:warn", "Asset fetch failed.\n" + result?.reason?.toString()); + dispatchEvent(LOGGER_WARN, "Asset fetch failed.\n" + result?.reason?.toString()) return false; } else return true; }) diff --git a/packages/core/src/plugins/virtual-fs.ts b/packages/core/src/plugins/virtual-fs.ts index 121cdfb..6b1e39d 100644 --- a/packages/core/src/plugins/virtual-fs.ts +++ b/packages/core/src/plugins/virtual-fs.ts @@ -1,13 +1,12 @@ // Based on https://github.com/okikio/bundle/blob/main/src/ts/plugins/virtual-fs.ts import type { BuildConfig, LocalState } from "../build.ts"; import type { StateArray } from "../configs/state.ts"; -import type { EVENTS } from "../configs/events.ts"; import type { ESBUILD } from "../types.ts"; import { inferLoader } from "../utils/loader.ts"; import { getResolvedPath, getFile } from "../util.ts"; export const VIRTUAL_FILESYSTEM_NAMESPACE = "virtual-filesystem"; -export const VIRTUAL_FS = (events: typeof EVENTS, state: StateArray, config: BuildConfig): ESBUILD.Plugin => { +export const VIRTUAL_FS = (state: StateArray, config: BuildConfig): ESBUILD.Plugin => { const [getState] = state; const FileSystem = getState().filesystem; diff --git a/packages/core/src/transform.ts b/packages/core/src/transform.ts index 2cbad26..fc5d8c6 100644 --- a/packages/core/src/transform.ts +++ b/packages/core/src/transform.ts @@ -3,10 +3,10 @@ import type { CommonConfigOptions, ESBUILD } from "./types.ts"; import { getState } from "./configs/state.ts"; import { PLATFORM_AUTO } from "./configs/platform.ts"; import { createConfig } from "./configs/config.ts"; -import { EVENTS } from "./configs/events.ts"; import { createNotice } from "./utils/create-notice.ts"; import { init } from "./init.ts"; +import { INIT_LOADING, LOGGER_ERROR, dispatchEvent } from "./configs/events.ts"; export type TransformConfig = CommonConfigOptions & { /* https://esbuild.github.io/api/#transform-api */ @@ -32,7 +32,7 @@ export const TRANSFORM_CONFIG: TransformConfig = { export async function transform(input: string | Uint8Array, opts: TransformConfig = {}) { if (!getState("initialized")) - EVENTS.emit("init.loading"); + dispatchEvent(INIT_LOADING); const CONFIG = createConfig("transform", opts); @@ -60,10 +60,10 @@ export async function transform(input: string | Uint8Array, opts: TransformConfi const asciMsgs = [...await createNotice(e.errors, "error", false)]; const htmlMsgs = [...await createNotice(e.errors, "error")]; - EVENTS.emit("logger.error", asciMsgs, htmlMsgs); + dispatchEvent(LOGGER_ERROR, new Error(JSON.stringify({ asciMsgs, htmlMsgs }))); - const message = (htmlMsgs.length > 1 ? `${htmlMsgs.length} error(s) ` : "") + "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundle)"; - EVENTS.emit("logger.error", message); + const message = (htmlMsgs.length > 1 ? `${htmlMsgs.length} error(s) ` : "") + "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundlejs)"; + dispatchEvent(LOGGER_ERROR, new Error(message)); return; } else throw e; } diff --git a/packages/core/src/utils/ansi.ts b/packages/core/src/utils/ansi.ts index f508161..1e8b995 100644 --- a/packages/core/src/utils/ansi.ts +++ b/packages/core/src/utils/ansi.ts @@ -104,7 +104,15 @@ export function render(ansi: string) { if (i < ansi.length) { buffer.text(ansi.slice(i)); } - return buffer.done(); + + /** + * Based on https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string + * Based on http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/ + */ + return buffer.done().replace( + /\b(?:(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#/%?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]|((?:mailto:)?[A-Z0-9._%+-]+@[A-Z0-9._%-]+\.[A-Z]{2,4})\b)|"(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^"\r\n]+"?|'(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^'\r\n]+'?/gi, + (match) => `${match}` + ); } export { render as ansi }; diff --git a/packages/core/src/utils/create-notice.ts b/packages/core/src/utils/create-notice.ts index 1db7fd4..03a05bc 100644 --- a/packages/core/src/utils/create-notice.ts +++ b/packages/core/src/utils/create-notice.ts @@ -1,13 +1,14 @@ import type { PartialMessage } from "esbuild-wasm"; import { ansi } from "./ansi.ts"; +import { getEsbuild } from "./get-esbuild.ts"; /** * 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", color = true) => { - const { formatMessages } = await import("esbuild-wasm"); +export async function createNotice (errors: PartialMessage[], kind: "error" | "warning" = "error", color = true) { + const { formatMessages } = await getEsbuild(); const notices = await formatMessages(errors, { color, kind }); return notices.map((msg) => !color ? msg : ansi(msg.replace(/(\s+)(\d+)(\s+)\│/g, "\n$1$2$3│"))); }; diff --git a/packages/core/src/utils/filesystem.ts b/packages/core/src/utils/filesystem.ts index f5e6839..36aebc6 100644 --- a/packages/core/src/utils/filesystem.ts +++ b/packages/core/src/utils/filesystem.ts @@ -1,6 +1,7 @@ import { decode, encode } from "./encode-decode.ts"; import { dirname, basename, resolve, sep } from "../deno/path/mod.ts"; -import type { EVENTS } from "../configs/events.ts"; + +import { LOGGER_WARN, dispatchEvent } from "../configs/events.ts"; export interface IFileSystem { /** Direct Access to Virtual Filesystem Storage, if requred for some specific use case */ @@ -112,6 +113,7 @@ export async function deleteFile>(fs: F, path: strin try { const file = await fs.get(resolvedPath); + console.log({ file }) if (file === undefined) return false; return await fs.delete(resolvedPath); @@ -288,7 +290,7 @@ export async function createOPFSFileSystem() { * Selects the OPFS File System if possible, otherwise fallback to the default Map based Virtual File System * @param type Virtual File System to use */ -export async function useFileSystem(events: typeof EVENTS, type: "OPFS" | "DEFAULT" = "OPFS") { +export async function useFileSystem(type: "OPFS" | "DEFAULT" = "OPFS") { try { switch (type) { case "DEFAULT": @@ -299,7 +301,7 @@ export async function useFileSystem(events: typeof EVENTS, type: "OPFS" | "DEFAU return createDefaultFileSystem(); } catch (e) { - events.emit('logger.warn', e); + dispatchEvent(LOGGER_WARN, e); } return createDefaultFileSystem(); diff --git a/packages/website/package.json b/packages/website/package.json index a3d3be3..6b0ef28 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -37,6 +37,8 @@ "@astrojs/solid-js": "^2.0.2", "@astrojs/tailwind": "^3.0.1", "@babel/core": "^7.20.12", + "@iconify-json/fluent": "^1.1.18", + "@iconify-json/mdi": "^1.1.47", "@iconify/json": "^2.2.21", "@types/offscreencanvas": "^2019.7.0", "astro": "2.0.9", diff --git a/packages/website/src/components/MainSection/EditorSection/Console.tsx b/packages/website/src/components/MainSection/EditorSection/Console.tsx index 15bf422..1478f13 100644 --- a/packages/website/src/components/MainSection/EditorSection/Console.tsx +++ b/packages/website/src/components/MainSection/EditorSection/Console.tsx @@ -1,5 +1,6 @@ import type { ComponentProps } from "solid-js"; import { createEffect, createSignal, For } from "solid-js"; +import { ansi } from "@bundlejs/core/src/utils/ansi"; import { ConsoleButtons } from "./ConsoleButtons"; import { Log } from "./ConsoleLogs"; @@ -8,8 +9,13 @@ import { TASK_RUNNER } from "../../../scripts"; import { Details } from "../../Details"; import { expose } from "comlink"; -export const [logsList, setLogsList] = createSignal([]); -export function addLogs(...args: unknown[]) { +export interface ILog { + type: string, + detail: string +} + +export const [logsList, setLogsList] = createSignal([]); +export function addLogs(...args: T[]) { setLogsList([...logsList(), ...args]); } @@ -26,21 +32,31 @@ export function Console(props?: ComponentProps<"div">) {
- - -

No logs...

-
- - }> - {(value) => ( - {value.data} - )} + + +

No logs...

+
+ + } + > + {(value) => { + const [title, ...detail] = value.detail.split(/\n/); + return detail.length > 0 ? ( +
+ +
+ ) : ( + + ); + }}
{/*
What do you mean? -
*/} + */}
); diff --git a/packages/website/src/scripts/utils/build.tsx b/packages/website/src/scripts/utils/build.tsx index f0ab7af..ddb76c7 100644 --- a/packages/website/src/scripts/utils/build.tsx +++ b/packages/website/src/scripts/utils/build.tsx @@ -1,4 +1,4 @@ - +import type { ESBUILD } from "@bundlejs/core"; import toast from "../../components/SolidToast"; import { setState, state } from "./store"; @@ -51,8 +51,13 @@ export async function build() { })(), { loading: "Building...", - success: () => <>Build Done with a size of {result.size} {timeFormatter.format(elapsed, "seconds")}, - error: "Build Error" + success: () => ( + <> + Build Done with a size of {result.size}{" "} + {timeFormatter.format(elapsed, "seconds")} + + ), + error: "Build Error", } ); @@ -64,7 +69,12 @@ export async function build() { setState("bundleSize", result.size); } - addLogs({ type: "info", data: `Build Done with a size of ${result.size} ${timeFormatter.format(elapsed, "seconds")}` }) + addLogs({ + type: "info", + detail: `Build Done with a size of ${ + result.size + } ${timeFormatter.format(elapsed, "seconds")}`, + }); // Signifier to no longer hold results in memory result = null; @@ -72,8 +82,8 @@ export async function build() { console.warn(e); setState("bundleSize", "ERROR!"); throw e; - } finally { + } finally { setState("bundling", false); } } -} \ No newline at end of file +} diff --git a/packages/website/src/scripts/workers/task-runner.ts b/packages/website/src/scripts/workers/task-runner.ts index 79772af..afca836 100644 --- a/packages/website/src/scripts/workers/task-runner.ts +++ b/packages/website/src/scripts/workers/task-runner.ts @@ -7,7 +7,7 @@ import { createShareURL } from "./tasks/create-share-url"; import { bundle } from "./tasks/build"; import { parseConfig } from "./tasks/parse-config"; -import { EVENTS } from "@bundlejs/core/src/index"; +import { addEventListener, INIT_COMPLETE, LOGGER_INFO } from "@bundlejs/core/src/index"; import * as Comlink from "comlink"; import "../utils/transferhandle"; @@ -24,13 +24,13 @@ export const connect = async (port: MessagePort | typeof globalThis) => { Comlink.expose(TaskRunner, port); const addLog = Comlink.wrap(port); - EVENTS.on("init.complete", (data) => { - addLog({ type: "info", data: "Initialized 🚀✨" }); - }); + addEventListener(INIT_COMPLETE, () => { + addLog({ type: "info", detail: "Initialized 🚀✨" }); + }) - EVENTS.on("logger.info", (data) => { - addLog({ type: "log", data }); - }); + addEventListener(LOGGER_INFO, (e) => { + addLog({ type: "log", detail: e.detail }); + }) }; (self as unknown as SharedWorkerGlobalScope).onconnect = (e) => { diff --git a/packages/website/src/scripts/workers/tasks/build.ts b/packages/website/src/scripts/workers/tasks/build.ts index 4455d34..5d69080 100644 --- a/packages/website/src/scripts/workers/tasks/build.ts +++ b/packages/website/src/scripts/workers/tasks/build.ts @@ -2,7 +2,7 @@ import type { ConfigOptions } from "../../configs/options"; import type { BuildConfig, ESBUILD } from "@bundlejs/core"; -import { build, compress, setFile, deepAssign, TheFileSystem } from "@bundlejs/core/src/index"; +import { build, compress, setFile, deepAssign, TheFileSystem, deleteFile } from "@bundlejs/core/src/index"; import { parseConfig } from "./parse-config"; import { DefaultConfig } from "../../configs/options"; @@ -13,6 +13,14 @@ export async function bundle(fileName: string, content: string, _config = "expor const fs = await TheFileSystem; const start = performance.now(); + try { + // await deleteFile(fs, "/index.tsx"); + } catch (e) { + console.log({ e }) + } + console.log({ + content + }) await setFile(fs, "/index.tsx", content); const newConfig = await parseConfig(_config); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1667f44..e4ab49b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -105,7 +105,6 @@ importers: packages/core: specifiers: - '@okikio/emitter': ^2.1.7 '@types/node': ^18.13.0 del-cli: ^5.0.0 esbuild: 0.17.8 @@ -118,7 +117,6 @@ importers: vite-plugin-cp: ^1.0.0 vitest: ^0.28.5 dependencies: - '@okikio/emitter': 2.1.7 esbuild: 0.17.8 esbuild-wasm: 0.17.8 devDependencies: @@ -141,6 +139,8 @@ importers: '@babel/core': ^7.20.12 '@bundlejs/core': workspace:^0.0.0 '@dprint/formatter': ^0.2.0 + '@iconify-json/fluent': ^1.1.18 + '@iconify-json/mdi': ^1.1.47 '@iconify/json': ^2.2.21 '@okikio/emitter': ^2.1.7 '@okikio/native': ^3.0.1 @@ -194,6 +194,8 @@ importers: '@astrojs/solid-js': 2.0.2_uetsbz2jlqumfuihdmj3dvs7je '@astrojs/tailwind': 3.0.1_yroyefrquwvghcn3xhop6h6pcy '@babel/core': 7.20.12 + '@iconify-json/fluent': 1.1.18 + '@iconify-json/mdi': 1.1.47 '@iconify/json': 2.2.21 '@types/offscreencanvas': 2019.7.0 astro: 2.0.9_sass@1.58.1 @@ -2194,6 +2196,18 @@ packages: requiresBuild: true optional: true + /@iconify-json/fluent/1.1.18: + resolution: {integrity: sha512-tdfnNxTJW39t5FhGzf+LPMJyaW9lTIhVYpHReGbbK7Ivt/GksbbOFpXntUgAgrMqglxSmSOz7u0xBARS1a3waQ==} + dependencies: + '@iconify/types': 2.0.0 + dev: true + + /@iconify-json/mdi/1.1.47: + resolution: {integrity: sha512-5E5mazdQaMNl3gmLL7whteh61weJBRfW2R9Rq0/pgAe9B0j22mViyADm/ooHZx07Vkc0ZqnkgUrpT6OsS9Qhzg==} + dependencies: + '@iconify/types': 2.0.0 + dev: true + /@iconify/json/2.2.21: resolution: {integrity: sha512-6nhAe77/n08xnstU+Aow0brbb3R0nHQpVi2FUpYexR0XkCjp8TuAuSk2mJW1vbwOFBuYXGuBY7CRxZoKnTJMHQ==} dependencies: @@ -10008,7 +10022,7 @@ packages: vite: optional: true dependencies: - vite: 4.1.1_@types+node@18.13.0 + vite: 4.1.1_sass@1.58.1 dev: true /vitest/0.28.5: