@hirarijs/loader 1.0.5 → 1.0.7

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.
@@ -0,0 +1,227 @@
1
+ // src/config.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ var DEFAULT_CONFIG = {
5
+ format: "cjs",
6
+ plugins: ["@hirarijs/loader-ts", "@hirarijs/loader-tsx", "@hirarijs/loader-vue"]
7
+ };
8
+ function loadHirariConfig(cwd = process.cwd()) {
9
+ const configPath = path.join(cwd, "hirari.json");
10
+ if (!fs.existsSync(configPath)) {
11
+ return { ...DEFAULT_CONFIG };
12
+ }
13
+ const raw = fs.readFileSync(configPath, "utf8");
14
+ let parsed;
15
+ try {
16
+ parsed = JSON.parse(raw);
17
+ } catch (error) {
18
+ throw new Error(`Failed to parse hirari.json: ${error.message}`);
19
+ }
20
+ const loaderConfig = parsed.loader || {};
21
+ return {
22
+ ...DEFAULT_CONFIG,
23
+ ...loaderConfig,
24
+ plugins: loaderConfig.plugins?.length ? loaderConfig.plugins : DEFAULT_CONFIG.plugins
25
+ };
26
+ }
27
+ function getFormat(config) {
28
+ return config.format === "esm" ? "esm" : "cjs";
29
+ }
30
+
31
+ // src/constants.ts
32
+ var IMPORT_META_URL_VARIABLE = "__hirari_loader_import_meta_url__";
33
+
34
+ // src/plugin-manager.ts
35
+ import { spawnSync } from "child_process";
36
+ import fs2 from "fs";
37
+ import path2 from "path";
38
+ import { createRequire } from "module";
39
+ var PACKAGE_MANAGERS = [
40
+ { lock: "pnpm-lock.yaml", command: "pnpm", args: ["add"] },
41
+ { lock: "yarn.lock", command: "yarn", args: ["add"] },
42
+ { lock: "package-lock.json", command: "npm", args: ["install"] },
43
+ { lock: "npm-shrinkwrap.json", command: "npm", args: ["install"] }
44
+ ];
45
+ function detectPackageManager(cwd) {
46
+ for (const pm of PACKAGE_MANAGERS) {
47
+ if (fs2.existsSync(path2.join(cwd, pm.lock))) return pm;
48
+ }
49
+ return { command: "npm", args: ["install"] };
50
+ }
51
+ function tryRequire(moduleId, cwd) {
52
+ const req = createRequire(path2.join(cwd, "noop.js"));
53
+ const loaded = req(moduleId);
54
+ return loaded && (loaded.default || loaded);
55
+ }
56
+ function install(pkg, cwd) {
57
+ const pm = detectPackageManager(cwd);
58
+ const result = spawnSync(pm.command, [...pm.args, pkg], {
59
+ cwd,
60
+ stdio: "inherit",
61
+ env: process.env
62
+ });
63
+ if (result.error) {
64
+ throw result.error;
65
+ }
66
+ if (result.status !== 0) {
67
+ throw new Error(`${pm.command} ${pm.args.join(" ")} ${pkg} failed`);
68
+ }
69
+ }
70
+ function resolvePlugins(config, cwd) {
71
+ const plugins = [];
72
+ for (const pluginName of config.plugins || []) {
73
+ let loaded = null;
74
+ try {
75
+ loaded = tryRequire(pluginName, cwd);
76
+ } catch (error) {
77
+ if (config.autoInstall) {
78
+ console.log(`[hirari-loader] installing missing plugin ${pluginName}`);
79
+ install(pluginName, cwd);
80
+ loaded = tryRequire(pluginName, cwd);
81
+ } else {
82
+ throw new Error(
83
+ `Plugin "${pluginName}" not found. Enable autoInstall or install manually.`
84
+ );
85
+ }
86
+ }
87
+ if (!loaded) continue;
88
+ plugins.push({
89
+ plugin: loaded,
90
+ options: config.pluginOptions?.[pluginName]
91
+ });
92
+ if (config.debug) {
93
+ console.log(`[hirari-loader] loaded plugin ${pluginName}`);
94
+ }
95
+ }
96
+ return plugins;
97
+ }
98
+
99
+ // src/runtime.ts
100
+ import fs3 from "fs";
101
+ import module from "module";
102
+ import { fileURLToPath } from "url";
103
+ import { addHook } from "pirates";
104
+ import * as sourceMapSupport from "source-map-support";
105
+ var map = {};
106
+ function installSourceMaps() {
107
+ sourceMapSupport.install({
108
+ handleUncaughtExceptions: false,
109
+ environment: "node",
110
+ retrieveSourceMap(file) {
111
+ if (map[file]) {
112
+ return { url: file, map: map[file] };
113
+ }
114
+ return null;
115
+ }
116
+ });
117
+ }
118
+ var toNodeLoaderFormat = (format) => format === "esm" ? "module" : "commonjs";
119
+ function createRuntime(cwd = process.cwd()) {
120
+ const loaderConfig = loadHirariConfig(cwd);
121
+ const resolvedPlugins = resolvePlugins(loaderConfig, cwd);
122
+ installSourceMaps();
123
+ return {
124
+ cwd,
125
+ loaderConfig,
126
+ resolvedPlugins,
127
+ format: getFormat(loaderConfig)
128
+ };
129
+ }
130
+ function pickPlugin(filename, plugins) {
131
+ return plugins.find(({ plugin }) => plugin.match(filename));
132
+ }
133
+ function applyPlugin(code, filename, runtime) {
134
+ const match = pickPlugin(filename, runtime.resolvedPlugins);
135
+ if (!match) return { code };
136
+ const ctx = {
137
+ format: runtime.format,
138
+ loaderConfig: runtime.loaderConfig,
139
+ pluginOptions: match.options
140
+ };
141
+ const result = match.plugin.transform(code, filename, ctx);
142
+ if (runtime.loaderConfig.debug) {
143
+ console.log(`[hirari-loader][${match.plugin.name}] compiled ${filename}`);
144
+ console.log(result.code);
145
+ }
146
+ if (result.map) {
147
+ map[filename] = result.map;
148
+ }
149
+ return result;
150
+ }
151
+ function collectExtensions(plugins) {
152
+ const set = /* @__PURE__ */ new Set();
153
+ for (const { plugin } of plugins) {
154
+ plugin.extensions.forEach((ext) => set.add(ext));
155
+ }
156
+ return Array.from(set);
157
+ }
158
+ function registerRequireHooks(runtime) {
159
+ const extensions = collectExtensions(runtime.resolvedPlugins);
160
+ const compile = (code, filename) => {
161
+ const result = applyPlugin(code, filename, runtime);
162
+ const banner = `const ${IMPORT_META_URL_VARIABLE} = require('url').pathToFileURL(__filename).href;`;
163
+ if (!result.code.includes(IMPORT_META_URL_VARIABLE)) {
164
+ return `${banner}${result.code}`;
165
+ }
166
+ return result.code;
167
+ };
168
+ const revert = addHook(compile, {
169
+ exts: extensions,
170
+ ignoreNodeModules: runtime.loaderConfig.hookIgnoreNodeModules ?? true
171
+ });
172
+ const extensionsObj = module.Module._extensions;
173
+ const jsHandler = extensionsObj[".js"];
174
+ extensionsObj[".js"] = function(mod, filename) {
175
+ try {
176
+ return jsHandler.call(this, mod, filename);
177
+ } catch (error) {
178
+ if (error && error.code === "ERR_REQUIRE_ESM") {
179
+ const src = fs3.readFileSync(filename, "utf8");
180
+ const result = applyPlugin(src, filename, runtime);
181
+ mod._compile(result.code, filename);
182
+ return;
183
+ }
184
+ throw error;
185
+ }
186
+ };
187
+ return () => {
188
+ revert();
189
+ extensionsObj[".js"] = jsHandler;
190
+ };
191
+ }
192
+ async function loaderResolve(specifier, context, next) {
193
+ if (next) return next(specifier, context);
194
+ return { url: specifier };
195
+ }
196
+ async function loaderLoad(url, context, next, runtime) {
197
+ const { format: expectedFormat } = runtime;
198
+ if (url.startsWith("file://")) {
199
+ const filename = fileURLToPath(url);
200
+ const match = pickPlugin(filename, runtime.resolvedPlugins);
201
+ if (match) {
202
+ const source = fs3.readFileSync(filename, "utf8");
203
+ const result = applyPlugin(source, filename, runtime);
204
+ return {
205
+ format: toNodeLoaderFormat(result.format || expectedFormat),
206
+ source: result.code,
207
+ shortCircuit: true
208
+ };
209
+ }
210
+ }
211
+ if (!next) {
212
+ throw new Error("No default loader available for " + url);
213
+ }
214
+ const forwarded = await next(url, context);
215
+ if (forwarded) return forwarded;
216
+ throw new Error("Loader did not return a result for " + url);
217
+ }
218
+
219
+ export {
220
+ loadHirariConfig,
221
+ IMPORT_META_URL_VARIABLE,
222
+ resolvePlugins,
223
+ createRuntime,
224
+ registerRequireHooks,
225
+ loaderResolve,
226
+ loaderLoad
227
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ createRuntime,
3
+ registerRequireHooks
4
+ } from "./chunk-YN5O4JJJ.js";
5
+
6
+ // src/register.ts
7
+ function register(cwd = process.cwd()) {
8
+ const runtime = createRuntime(cwd);
9
+ const unregister = registerRequireHooks(runtime);
10
+ return { unregister };
11
+ }
12
+
13
+ export {
14
+ register
15
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ createRuntime,
3
+ registerRequireHooks
4
+ } from "./chunk-CSHOBCMM.js";
5
+
6
+ // src/register.ts
7
+ function register(cwd = process.cwd()) {
8
+ const runtime = createRuntime(cwd);
9
+ const unregister = registerRequireHooks(runtime);
10
+ return { unregister };
11
+ }
12
+
13
+ export {
14
+ register
15
+ };
@@ -0,0 +1,346 @@
1
+ // src/config.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ var DEFAULT_CONFIG = {
5
+ format: "cjs",
6
+ plugins: ["@hirarijs/loader-ts", "@hirarijs/loader-tsx", "@hirarijs/loader-vue"]
7
+ };
8
+ function loadHirariConfig(cwd = process.cwd()) {
9
+ const configPath = path.join(cwd, "hirari.json");
10
+ if (!fs.existsSync(configPath)) {
11
+ return { ...DEFAULT_CONFIG };
12
+ }
13
+ const raw = fs.readFileSync(configPath, "utf8");
14
+ let parsed;
15
+ try {
16
+ parsed = JSON.parse(raw);
17
+ } catch (error) {
18
+ throw new Error(`Failed to parse hirari.json: ${error.message}`);
19
+ }
20
+ const loaderConfig = parsed.loader || {};
21
+ return {
22
+ ...DEFAULT_CONFIG,
23
+ ...loaderConfig,
24
+ plugins: loaderConfig.plugins?.length ? loaderConfig.plugins : DEFAULT_CONFIG.plugins
25
+ };
26
+ }
27
+ function getFormat(config) {
28
+ return config.format === "esm" ? "esm" : "cjs";
29
+ }
30
+
31
+ // src/constants.ts
32
+ var IMPORT_META_URL_VARIABLE = "__hirari_loader_import_meta_url__";
33
+
34
+ // src/plugin-manager.ts
35
+ import { spawnSync } from "child_process";
36
+ import fs2 from "fs";
37
+ import path2 from "path";
38
+ import { createRequire } from "module";
39
+ var PACKAGE_MANAGERS = [
40
+ { lock: "pnpm-lock.yaml", command: "pnpm", args: ["add"] },
41
+ { lock: "yarn.lock", command: "yarn", args: ["add"] },
42
+ { lock: "package-lock.json", command: "npm", args: ["install"] },
43
+ { lock: "npm-shrinkwrap.json", command: "npm", args: ["install"] }
44
+ ];
45
+ function detectPackageManager(cwd) {
46
+ for (const pm of PACKAGE_MANAGERS) {
47
+ if (fs2.existsSync(path2.join(cwd, pm.lock))) return pm;
48
+ }
49
+ return { command: "npm", args: ["install"] };
50
+ }
51
+ function tryRequire(moduleId, cwd) {
52
+ const req = createRequire(path2.join(cwd, "noop.js"));
53
+ const loaded = req(moduleId);
54
+ return loaded && (loaded.default || loaded);
55
+ }
56
+ function install(pkg, cwd) {
57
+ const pm = detectPackageManager(cwd);
58
+ const result = spawnSync(pm.command, [...pm.args, pkg], {
59
+ cwd,
60
+ stdio: "inherit",
61
+ env: process.env
62
+ });
63
+ if (result.error) {
64
+ throw result.error;
65
+ }
66
+ if (result.status !== 0) {
67
+ throw new Error(`${pm.command} ${pm.args.join(" ")} ${pkg} failed`);
68
+ }
69
+ }
70
+ function resolvePlugins(config, cwd) {
71
+ const plugins = [];
72
+ for (const pluginName of config.plugins || []) {
73
+ let loaded = null;
74
+ try {
75
+ loaded = tryRequire(pluginName, cwd);
76
+ } catch (error) {
77
+ if (config.autoInstall) {
78
+ console.log(`[hirari-loader] installing missing plugin ${pluginName}`);
79
+ install(pluginName, cwd);
80
+ loaded = tryRequire(pluginName, cwd);
81
+ } else {
82
+ throw new Error(
83
+ `Plugin "${pluginName}" not found. Enable autoInstall or install manually.`
84
+ );
85
+ }
86
+ }
87
+ if (!loaded) continue;
88
+ plugins.push({
89
+ plugin: loaded,
90
+ options: config.pluginOptions?.[pluginName]
91
+ });
92
+ if (config.debug) {
93
+ console.log(`[hirari-loader] loaded plugin ${pluginName}`);
94
+ }
95
+ }
96
+ return plugins;
97
+ }
98
+
99
+ // src/runtime.ts
100
+ import fs4 from "fs";
101
+ import module from "module";
102
+ import { fileURLToPath, pathToFileURL } from "url";
103
+ import { addHook } from "pirates";
104
+ import * as sourceMapSupport from "source-map-support";
105
+
106
+ // src/tsconfig-paths.ts
107
+ import fs3 from "fs";
108
+ import path3 from "path";
109
+ var EXTENSIONS = [
110
+ ".ts",
111
+ ".tsx",
112
+ ".mts",
113
+ ".cts",
114
+ ".js",
115
+ ".jsx",
116
+ ".mjs",
117
+ ".cjs"
118
+ ];
119
+ function readTsConfig(cwd) {
120
+ const tsconfigPath = path3.join(cwd, "tsconfig.json");
121
+ if (!fs3.existsSync(tsconfigPath)) return null;
122
+ try {
123
+ const raw = JSON.parse(fs3.readFileSync(tsconfigPath, "utf8"));
124
+ const compilerOptions = raw.compilerOptions || {};
125
+ const baseUrl = compilerOptions.baseUrl ? path3.resolve(cwd, compilerOptions.baseUrl) : cwd;
126
+ const paths = compilerOptions.paths || {};
127
+ return { baseUrl, paths };
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+ function expandPattern(pattern, target) {
133
+ if (!pattern.includes("*")) {
134
+ return pattern === target ? target : null;
135
+ }
136
+ const [prefix, suffix] = pattern.split("*");
137
+ if (!target.startsWith(prefix) || !target.endsWith(suffix)) return null;
138
+ const wildcard = target.slice(prefix.length, target.length - suffix.length);
139
+ return wildcard;
140
+ }
141
+ function tryFile(resolved) {
142
+ if (fs3.existsSync(resolved) && fs3.statSync(resolved).isFile()) {
143
+ return resolved;
144
+ }
145
+ for (const ext of EXTENSIONS) {
146
+ const candidate = resolved + ext;
147
+ if (fs3.existsSync(candidate) && fs3.statSync(candidate).isFile()) {
148
+ return candidate;
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+ function createPathMatcher(cwd, debug) {
154
+ const cfg = readTsConfig(cwd);
155
+ if (!cfg || !cfg.paths || Object.keys(cfg.paths).length === 0) return null;
156
+ if (debug) {
157
+ console.log("[hirari-loader] tsconfig paths enabled", {
158
+ baseUrl: cfg.baseUrl,
159
+ paths: cfg.paths
160
+ });
161
+ }
162
+ return {
163
+ match(specifier) {
164
+ for (const [pattern, replacements] of Object.entries(cfg.paths)) {
165
+ const wildcard = expandPattern(pattern, specifier);
166
+ if (wildcard === null) continue;
167
+ for (const repl of replacements) {
168
+ const replaced = repl.replace("*", wildcard);
169
+ const candidate = path3.resolve(cfg.baseUrl, replaced);
170
+ const file = tryFile(candidate);
171
+ if (file) {
172
+ if (debug) {
173
+ console.log(
174
+ `[hirari-loader] resolved "${specifier}" -> "${file}" via tsconfig paths`
175
+ );
176
+ }
177
+ return file;
178
+ }
179
+ }
180
+ }
181
+ return null;
182
+ }
183
+ };
184
+ }
185
+
186
+ // src/runtime.ts
187
+ var map = {};
188
+ function installSourceMaps() {
189
+ sourceMapSupport.install({
190
+ handleUncaughtExceptions: false,
191
+ environment: "node",
192
+ retrieveSourceMap(file) {
193
+ if (map[file]) {
194
+ return { url: file, map: map[file] };
195
+ }
196
+ return null;
197
+ }
198
+ });
199
+ }
200
+ var toNodeLoaderFormat = (format) => format === "esm" ? "module" : "commonjs";
201
+ function createRuntime(cwd = process.cwd()) {
202
+ const loaderConfig = loadHirariConfig(cwd);
203
+ const resolvedPlugins = resolvePlugins(loaderConfig, cwd);
204
+ installSourceMaps();
205
+ const pathMatcher = createPathMatcher(cwd, loaderConfig.debug);
206
+ if (loaderConfig.debug) {
207
+ console.log("[hirari-loader] config", loaderConfig);
208
+ }
209
+ return {
210
+ cwd,
211
+ loaderConfig,
212
+ resolvedPlugins,
213
+ format: getFormat(loaderConfig),
214
+ pathMatcher
215
+ };
216
+ }
217
+ function pickPlugin(filename, plugins) {
218
+ return plugins.find(({ plugin }) => plugin.match(filename));
219
+ }
220
+ function applyPlugin(code, filename, runtime) {
221
+ const match = pickPlugin(filename, runtime.resolvedPlugins);
222
+ if (!match) return { code };
223
+ const ctx = {
224
+ format: runtime.format,
225
+ loaderConfig: runtime.loaderConfig,
226
+ pluginOptions: match.options
227
+ };
228
+ const result = match.plugin.transform(code, filename, ctx);
229
+ if (runtime.loaderConfig.debug) {
230
+ console.log(`[hirari-loader][${match.plugin.name}] compiled ${filename}`);
231
+ console.log(result.code);
232
+ }
233
+ if (result.map) {
234
+ map[filename] = result.map;
235
+ }
236
+ return result;
237
+ }
238
+ function collectExtensions(plugins) {
239
+ const set = /* @__PURE__ */ new Set();
240
+ for (const { plugin } of plugins) {
241
+ plugin.extensions.forEach((ext) => set.add(ext));
242
+ }
243
+ return Array.from(set);
244
+ }
245
+ function registerRequireHooks(runtime) {
246
+ const extensions = collectExtensions(runtime.resolvedPlugins);
247
+ const compile = (code, filename) => {
248
+ const result = applyPlugin(code, filename, runtime);
249
+ const banner = `const ${IMPORT_META_URL_VARIABLE} = require('url').pathToFileURL(__filename).href;`;
250
+ if (!result.code.includes(IMPORT_META_URL_VARIABLE)) {
251
+ return `${banner}${result.code}`;
252
+ }
253
+ return result.code;
254
+ };
255
+ const revert = addHook(compile, {
256
+ exts: extensions,
257
+ ignoreNodeModules: runtime.loaderConfig.hookIgnoreNodeModules ?? true
258
+ });
259
+ const extensionsObj = module.Module._extensions;
260
+ const jsHandler = extensionsObj[".js"];
261
+ const resolveFilename = module.Module._resolveFilename;
262
+ if (runtime.pathMatcher) {
263
+ ;
264
+ module.Module._resolveFilename = function(request, parent, isMain, options) {
265
+ const matched = runtime.pathMatcher?.match(request);
266
+ if (matched) {
267
+ request = matched;
268
+ }
269
+ return resolveFilename.call(this, request, parent, isMain, options);
270
+ };
271
+ }
272
+ extensionsObj[".js"] = function(mod, filename) {
273
+ try {
274
+ return jsHandler.call(this, mod, filename);
275
+ } catch (error) {
276
+ if (error && error.code === "ERR_REQUIRE_ESM") {
277
+ const src = fs4.readFileSync(filename, "utf8");
278
+ const result = applyPlugin(src, filename, runtime);
279
+ mod._compile(result.code, filename);
280
+ return;
281
+ }
282
+ throw error;
283
+ }
284
+ };
285
+ return () => {
286
+ revert();
287
+ extensionsObj[".js"] = jsHandler;
288
+ if (runtime.pathMatcher) {
289
+ ;
290
+ module.Module._resolveFilename = resolveFilename;
291
+ }
292
+ };
293
+ }
294
+ async function loaderResolve(specifier, context, next, runtime) {
295
+ if (runtime.pathMatcher && !specifier.startsWith("node:") && !specifier.startsWith("file:") && !specifier.startsWith("data:") && !specifier.startsWith("http") && !specifier.startsWith("https") && !specifier.startsWith("/") && !specifier.startsWith("./") && !specifier.startsWith("../")) {
296
+ const matched = runtime.pathMatcher.match(specifier);
297
+ if (matched) {
298
+ if (runtime.loaderConfig.debug) {
299
+ console.log(
300
+ `[hirari-loader] resolve (paths) "${specifier}" -> "${matched}"`
301
+ );
302
+ }
303
+ return { url: pathToFileURL(matched).href };
304
+ }
305
+ }
306
+ if (next) return next(specifier, context);
307
+ return { url: specifier };
308
+ }
309
+ async function loaderLoad(url, context, next, runtime) {
310
+ const { format: expectedFormat } = runtime;
311
+ if (url.startsWith("file://")) {
312
+ const filename = fileURLToPath(url);
313
+ const match = pickPlugin(filename, runtime.resolvedPlugins);
314
+ if (match) {
315
+ const source = fs4.readFileSync(filename, "utf8");
316
+ const result = applyPlugin(source, filename, runtime);
317
+ return {
318
+ format: toNodeLoaderFormat(result.format || expectedFormat),
319
+ source: result.code,
320
+ shortCircuit: true
321
+ };
322
+ }
323
+ }
324
+ if (!next) {
325
+ throw new Error("No default loader available for " + url);
326
+ }
327
+ if (runtime.pathMatcher && !url.startsWith("node:") && !url.startsWith("file:") && !url.startsWith("data:") && !url.startsWith("http") && !url.startsWith("https") && !url.startsWith("/") && !url.startsWith("./") && !url.startsWith("../")) {
328
+ const matched = runtime.pathMatcher.match(url);
329
+ if (matched) {
330
+ return next(pathToFileURL(matched).href, context);
331
+ }
332
+ }
333
+ const forwarded = await next(url, context);
334
+ if (forwarded) return forwarded;
335
+ throw new Error("Loader did not return a result for " + url);
336
+ }
337
+
338
+ export {
339
+ loadHirariConfig,
340
+ IMPORT_META_URL_VARIABLE,
341
+ resolvePlugins,
342
+ createRuntime,
343
+ registerRequireHooks,
344
+ loaderResolve,
345
+ loaderLoad
346
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ createRuntime,
3
+ registerRequireHooks
4
+ } from "./chunk-VVQLDIKO.js";
5
+
6
+ // src/register.ts
7
+ function register(cwd = process.cwd()) {
8
+ const runtime = createRuntime(cwd);
9
+ const unregister = registerRequireHooks(runtime);
10
+ return { unregister };
11
+ }
12
+
13
+ export {
14
+ register
15
+ };