Skip to content

Instantly share code, notes, and snippets.

@jdesrosiers
Created May 5, 2026 04:48
Show Gist options
  • Select an option

  • Save jdesrosiers/1f915bfd4f72e52f9b7766d225500fcf to your computer and use it in GitHub Desktop.

Select an option

Save jdesrosiers/1f915bfd4f72e52f9b7766d225500fcf to your computer and use it in GitHub Desktop.
esm.sh loader
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
/**
* @import { ResolveHookContext, ResolveFnOutput, Module } from "node:module"
*/
const localRequire = createRequire(pathToFileURL("."));
/**
* @type (specifier: string, context: ResolveHookContext, nextResolve: (specifier: string, context?: Partial<ResolveHookContext>) => Promise<ResolveFnOutput>) => Promise<ResolveFnOutput>
*/
export async function resolve(specifier, context, nextResolve) {
if (specifier.startsWith("https://esm.sh")) {
return {
shortCircuit: true,
url: specifier
};
}
if (context.parentURL?.startsWith("https://esm.sh")) {
if (specifier.startsWith("/")) {
// Handle relative path
return {
shortCircuit: true,
url: new URL(specifier, context.parentURL).href
};
} else {
// Handle external module
return {
shortCircuit: true,
url: pathToFileURL(localRequire.resolve(specifier)).href
};
}
}
return nextResolve(specifier, context);
}
/**
* @type (url: string, context: Module.LoadHookContext, nextLoad: (url: string, context?: Partial<Module.LoadHookContext>) => Promise<Module.LoadFnOutput>) => Promise<Module.LoadFnOutput>
*/
export async function load(url, _context, nextLoad) {
if (url.startsWith("https://esm.sh")) {
const response = await fetch(url);
return {
format: "module",
source: await response.text(),
shortCircuit: true
};
}
return nextLoad(url);
}
import { register } from "node:module";
import { registerSchema, validate } from "@hyperjump/json-schema";
register("./esm_sh-loader.mjs", import.meta.url);
const packageId = "gh/jdesrosiers/json-schema-dialect-example@5462150";
const loadDialect = await import(`https://esm.sh/${packageId}?external=@hyperjump/json-schema,@hyperjump/browser`);
loadDialect.default();
const schemaUri = "https://example.com/main";
registerSchema({
$schema: "https://example.com/dialect/example",
foo: "foo",
bar: 42
}, schemaUri);
const output = await validate(schemaUri, 42);
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment