@granite-js/mpack 0.1.10 → 0.1.12

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.
Files changed (32) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundler/Bundler.js +3 -3
  3. package/dist/bundler/plugins/buildStatusPlugin/buildStatusPlugin.js +21 -17
  4. package/dist/bundler/plugins/index.d.ts +1 -1
  5. package/dist/bundler/plugins/index.js +2 -2
  6. package/dist/bundler/plugins/resolveHelpers.d.ts +3 -0
  7. package/dist/bundler/plugins/resolveHelpers.js +45 -0
  8. package/dist/bundler/plugins/resolvePlugin/alias/setupAliasResolver.d.ts +3 -0
  9. package/dist/bundler/plugins/resolvePlugin/alias/setupAliasResolver.js +115 -0
  10. package/dist/bundler/plugins/resolvePlugin/index.d.ts +1 -0
  11. package/dist/bundler/plugins/{dependencyAliasPlugin → resolvePlugin}/index.js +6 -6
  12. package/dist/bundler/plugins/{dependencyAliasPlugin/protocolResolver.js → resolvePlugin/protocol/setupProtocolResolver.js} +4 -4
  13. package/dist/bundler/plugins/resolvePlugin/resolvePlugin.d.ts +3 -0
  14. package/dist/bundler/plugins/{dependencyAliasPlugin/dependencyAliasPlugin.js → resolvePlugin/resolvePlugin.js} +12 -13
  15. package/dist/bundler/plugins/transformPlugin/helpers/preludeScript.d.ts +11 -3
  16. package/dist/bundler/plugins/transformPlugin/helpers/preludeScript.js +12 -13
  17. package/dist/operations/build.d.ts +3 -3
  18. package/dist/operations/build.js +19 -10
  19. package/dist/plugins/statusPlugin.js +7 -6
  20. package/dist/server/DevServer.js +16 -12
  21. package/dist/utils/buildResult.d.ts +2 -0
  22. package/dist/utils/buildResult.js +30 -0
  23. package/dist/utils/printSummary.d.ts +2 -7
  24. package/dist/utils/printSummary.js +19 -14
  25. package/dist/utils/{promiseHandler.d.ts → promise.d.ts} +2 -0
  26. package/dist/utils/{promiseHandler.js → promise.js} +15 -5
  27. package/package.json +4 -4
  28. package/dist/bundler/plugins/dependencyAliasPlugin/aliasResolver.d.ts +0 -3
  29. package/dist/bundler/plugins/dependencyAliasPlugin/aliasResolver.js +0 -89
  30. package/dist/bundler/plugins/dependencyAliasPlugin/dependencyAliasPlugin.d.ts +0 -3
  31. package/dist/bundler/plugins/dependencyAliasPlugin/index.d.ts +0 -1
  32. /package/dist/bundler/plugins/{dependencyAliasPlugin/protocolResolver.d.ts → resolvePlugin/protocol/setupProtocolResolver.d.ts} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @granite-js/mpack
2
2
 
3
+ ## 0.1.12
4
+
5
+ ### Patch Changes
6
+
7
+ - d1e6585: fix module resolutions
8
+ - Updated dependencies [d1e6585]
9
+ - Updated dependencies [1e99fe1]
10
+ - @granite-js/devtools-frontend@0.1.12
11
+ - @granite-js/plugin-core@0.1.12
12
+ - @granite-js/utils@0.1.12
13
+
14
+ ## 0.1.11
15
+
16
+ ### Patch Changes
17
+
18
+ - 12f568f: improve error handler
19
+ - d3a2b58: improve resolver plugin
20
+ - Updated dependencies [d3a2b58]
21
+ - @granite-js/plugin-core@0.1.11
22
+ - @granite-js/devtools-frontend@0.1.11
23
+ - @granite-js/utils@0.1.11
24
+
3
25
  ## 0.1.10
4
26
 
5
27
  ### Patch Changes
@@ -39,7 +39,7 @@ var import_plugins = require("./plugins");
39
39
  var import_constants = require("../constants");
40
40
  var import_logger = require("../logger");
41
41
  var import_getId = require("../utils/getId");
42
- var import_promiseHandler = require("../utils/promiseHandler");
42
+ var import_promise = require("../utils/promise");
43
43
  var import_presets = require("./internal/presets");
44
44
  class Bundler {
45
45
  constructor(config) {
@@ -69,7 +69,7 @@ class Bundler {
69
69
  if (this.status === "prepared" || this.status === "building") {
70
70
  this.bundleTask?.abort();
71
71
  }
72
- this.bundleTask = new import_promiseHandler.PromiseHandler(this.revisionId++);
72
+ this.bundleTask = new import_promise.PromiseHandler(this.revisionId++);
73
73
  this.esbuildContext.rebuild();
74
74
  this.status = "prepared";
75
75
  const result = await this.bundleTask.wait();
@@ -141,7 +141,7 @@ class Bundler {
141
141
  onLoad: (moduleCount) => this.handleLoad(moduleCount),
142
142
  onEnd: (buildResult) => this.handleEnd(buildResult)
143
143
  }),
144
- (0, import_plugins.dependencyAliasPlugin)({ context: pluginContext }),
144
+ (0, import_plugins.resolvePlugin)({ context: pluginContext }),
145
145
  (0, import_plugins.requireContextPlugin)(),
146
146
  (0, import_plugins.transformPlugin)({
147
147
  context: pluginContext,
@@ -44,30 +44,34 @@ function buildStatusPlugin({ context, ...hooks }) {
44
44
  });
45
45
  build.onEnd(async (result) => {
46
46
  const endAt = performance.now();
47
+ const duration = endAt - buildStartedAt;
47
48
  const { buildConfig } = context.config;
48
49
  const { outfile, sourcemapOutfile, platform, extra } = buildConfig;
49
50
  const { source, sourcemap } = (0, import_getBundleOutputs.getBundleOutputs)(outfile, result);
50
- const duration = endAt - buildStartedAt;
51
- if (source && sourcemap) {
52
- Object.defineProperties(result, {
53
- bundle: { value: { source, sourcemap }, enumerable: true },
54
- outfile: { value: outfile, enumerable: true },
55
- sourcemapOutfile: { value: sourcemapOutfile ?? (0, import_getSourcemapName.getSourcemapName)(outfile), enumerable: true },
56
- platform: { value: platform, enumerable: true },
57
- extra: { value: extra, enumerable: true },
58
- totalModuleCount: { value: moduleCount, enumerable: true },
59
- duration: { value: duration, enumerable: true },
60
- size: { value: source.contents.byteLength, enumerable: true }
61
- });
62
- import_logger.logger.debug("Build completed", { id: context.id });
63
- await hooks.onEnd(result);
64
- } else {
65
- throw new Error("invalid bundle result");
66
- }
51
+ const buildResult = extendBuildResult(
52
+ result,
53
+ source && sourcemap ? {
54
+ bundle: { source, sourcemap },
55
+ outfile,
56
+ sourcemapOutfile: sourcemapOutfile ?? (0, import_getSourcemapName.getSourcemapName)(outfile),
57
+ platform,
58
+ extra,
59
+ duration,
60
+ size: source.contents.byteLength,
61
+ totalModuleCount: moduleCount
62
+ } : { platform, extra, duration }
63
+ );
64
+ await hooks.onEnd(buildResult);
67
65
  });
68
66
  }
69
67
  };
70
68
  }
69
+ function extendBuildResult(result, properties) {
70
+ return Object.defineProperties(
71
+ result,
72
+ Object.fromEntries(Object.entries(properties).map(([property, value]) => [property, { value, enumerable: true }]))
73
+ );
74
+ }
71
75
  // Annotate the CommonJS export names for ESM import in node:
72
76
  0 && (module.exports = {
73
77
  buildStatusPlugin
@@ -1,4 +1,4 @@
1
1
  export * from './buildStatusPlugin';
2
- export * from './dependencyAliasPlugin';
2
+ export * from './resolvePlugin';
3
3
  export * from './requireContextPlugin';
4
4
  export * from './transformPlugin';
@@ -16,13 +16,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
16
16
  var plugins_exports = {};
17
17
  module.exports = __toCommonJS(plugins_exports);
18
18
  __reExport(plugins_exports, require("./buildStatusPlugin"), module.exports);
19
- __reExport(plugins_exports, require("./dependencyAliasPlugin"), module.exports);
19
+ __reExport(plugins_exports, require("./resolvePlugin"), module.exports);
20
20
  __reExport(plugins_exports, require("./requireContextPlugin"), module.exports);
21
21
  __reExport(plugins_exports, require("./transformPlugin"), module.exports);
22
22
  // Annotate the CommonJS export names for ESM import in node:
23
23
  0 && (module.exports = {
24
24
  ...require("./buildStatusPlugin"),
25
- ...require("./dependencyAliasPlugin"),
25
+ ...require("./resolvePlugin"),
26
26
  ...require("./requireContextPlugin"),
27
27
  ...require("./transformPlugin")
28
28
  });
@@ -0,0 +1,3 @@
1
+ import type { OnResolveArgs, PluginBuild, ResolveOptions } from 'esbuild';
2
+ export declare function createNonRecursiveResolver(build: PluginBuild): (args: OnResolveArgs, options: ResolveOptions) => Promise<import("esbuild").ResolveResult> | null;
3
+ export declare function isResolved(args: OnResolveArgs): any;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var resolveHelpers_exports = {};
20
+ __export(resolveHelpers_exports, {
21
+ createNonRecursiveResolver: () => createNonRecursiveResolver,
22
+ isResolved: () => isResolved
23
+ });
24
+ module.exports = __toCommonJS(resolveHelpers_exports);
25
+ const RESOLVED_FLAG_KEY = Symbol.for("mpack:REAOLVED_FLAG");
26
+ function createNonRecursiveResolver(build) {
27
+ return (args, options) => {
28
+ if (args.pluginData?.[RESOLVED_FLAG_KEY]) {
29
+ return null;
30
+ }
31
+ const pluginDataWithResolvedFlag = {
32
+ ...options?.pluginData,
33
+ [RESOLVED_FLAG_KEY]: true
34
+ };
35
+ return build.resolve(args.path, { ...options, pluginData: pluginDataWithResolvedFlag });
36
+ };
37
+ }
38
+ function isResolved(args) {
39
+ return args.pluginData?.[RESOLVED_FLAG_KEY];
40
+ }
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ createNonRecursiveResolver,
44
+ isResolved
45
+ });
@@ -0,0 +1,3 @@
1
+ import type { AliasConfig } from '@granite-js/plugin-core';
2
+ import type { PluginBuild } from 'esbuild';
3
+ export declare function setupAliasResolver(build: PluginBuild, aliasConfig: AliasConfig[]): void;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var setupAliasResolver_exports = {};
30
+ __export(setupAliasResolver_exports, {
31
+ setupAliasResolver: () => setupAliasResolver
32
+ });
33
+ module.exports = __toCommonJS(setupAliasResolver_exports);
34
+ var import_path = __toESM(require("path"));
35
+ var import_es_toolkit = require("es-toolkit");
36
+ var import_performance = require("../../../../performance");
37
+ var import_esbuildUtils = require("../../../../utils/esbuildUtils");
38
+ var import_replaceModulePath = require("../../../../utils/replaceModulePath");
39
+ var import_resolveHelpers = require("../../resolveHelpers");
40
+ var import_swc = require("../../shared/swc");
41
+ function setupAliasResolver(build, aliasConfig) {
42
+ const resolver = (0, import_resolveHelpers.createNonRecursiveResolver)(build);
43
+ [import_swc.swcHelperOptimizationRules.getAliasConfig(), ...aliasConfig].forEach((aliasConfig2) => {
44
+ const resolveResultCache = /* @__PURE__ */ new Map();
45
+ const { filter, resolveAlias } = resolveAliasConfig(build, aliasConfig2);
46
+ build.onResolve({ filter }, async (args) => {
47
+ if ((0, import_resolveHelpers.isResolved)(args)) {
48
+ return null;
49
+ }
50
+ const trace = import_performance.Performance.trace("alias-resolver", {
51
+ detail: { pattern: filter, path: args.path }
52
+ });
53
+ const defaultResolveOptions = {
54
+ resolveDir: args.resolveDir,
55
+ importer: args.importer,
56
+ kind: args.kind,
57
+ with: args.with
58
+ };
59
+ const resolveResult = await resolveAlias(args);
60
+ const resolvePath = resolveResult.path;
61
+ const resolveOptions = { ...defaultResolveOptions, ...resolveResult.options ?? {} };
62
+ const cacheKey = `${resolveOptions.kind}:${resolveOptions.resolveDir}:${resolvePath}`;
63
+ if (resolveResultCache.has(cacheKey)) {
64
+ trace.stop({ detail: { cacheHit: true } });
65
+ return resolveResultCache.get(cacheKey);
66
+ }
67
+ if (import_path.default.isAbsolute(resolvePath)) {
68
+ trace.stop({ detail: { isAbsolute: true } });
69
+ const result2 = { path: resolvePath };
70
+ resolveResultCache.set(cacheKey, result2);
71
+ return result2;
72
+ }
73
+ const pathOverriddenArgs = { ...args, path: resolvePath };
74
+ const result = await resolver(pathOverriddenArgs, resolveOptions);
75
+ if (result) {
76
+ trace.stop({ detail: { cacheHit: false, isAbsolute: false } });
77
+ resolveResultCache.set(cacheKey, result);
78
+ return result;
79
+ }
80
+ return null;
81
+ });
82
+ });
83
+ }
84
+ function resolveAliasConfig(build, aliasConfig) {
85
+ const { from, to, exact } = aliasConfig;
86
+ const filter = new RegExp(exact ? `^${from}$` : `^${from}(?:$|/)`);
87
+ const resolver = (0, import_resolveHelpers.createNonRecursiveResolver)(build);
88
+ const aliasResolver = (boundArgs, path2, options) => {
89
+ const result = resolver({ ...boundArgs, path: path2 }, options);
90
+ (0, import_es_toolkit.assert)(result, "resolver should return result");
91
+ return result;
92
+ };
93
+ const resolveAlias = async (args) => {
94
+ if (typeof to === "string") {
95
+ return normalizeResolveResult((0, import_replaceModulePath.replaceModulePath)(args.path, from, to));
96
+ }
97
+ if (typeof to === "function") {
98
+ const result = await to({ resolve: aliasResolver.bind(null, args), args });
99
+ return normalizeResolveResult(result);
100
+ }
101
+ return normalizeResolveResult(to);
102
+ };
103
+ return { filter, resolveAlias };
104
+ }
105
+ function normalizeResolveResult(result) {
106
+ if (typeof result === "string") {
107
+ return { path: (0, import_esbuildUtils.normalizePath)(result), options: void 0 };
108
+ }
109
+ const { path: path2, ...options } = result;
110
+ return { path: path2, options };
111
+ }
112
+ // Annotate the CommonJS export names for ESM import in node:
113
+ 0 && (module.exports = {
114
+ setupAliasResolver
115
+ });
@@ -0,0 +1 @@
1
+ export { resolvePlugin } from './resolvePlugin';
@@ -16,13 +16,13 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var dependencyAliasPlugin_exports = {};
20
- __export(dependencyAliasPlugin_exports, {
21
- dependencyAliasPlugin: () => import_dependencyAliasPlugin.dependencyAliasPlugin
19
+ var resolvePlugin_exports = {};
20
+ __export(resolvePlugin_exports, {
21
+ resolvePlugin: () => import_resolvePlugin.resolvePlugin
22
22
  });
23
- module.exports = __toCommonJS(dependencyAliasPlugin_exports);
24
- var import_dependencyAliasPlugin = require("./dependencyAliasPlugin");
23
+ module.exports = __toCommonJS(resolvePlugin_exports);
24
+ var import_resolvePlugin = require("./resolvePlugin");
25
25
  // Annotate the CommonJS export names for ESM import in node:
26
26
  0 && (module.exports = {
27
- dependencyAliasPlugin
27
+ resolvePlugin
28
28
  });
@@ -16,12 +16,12 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var protocolResolver_exports = {};
20
- __export(protocolResolver_exports, {
19
+ var setupProtocolResolver_exports = {};
20
+ __export(setupProtocolResolver_exports, {
21
21
  setupProtocolResolver: () => setupProtocolResolver
22
22
  });
23
- module.exports = __toCommonJS(protocolResolver_exports);
24
- var import_performance = require("../../../performance");
23
+ module.exports = __toCommonJS(setupProtocolResolver_exports);
24
+ var import_performance = require("../../../../performance");
25
25
  function setupProtocolResolver(build, protocolConfig) {
26
26
  const protocols = Object.entries(protocolConfig);
27
27
  protocols.forEach(([protocol, { resolve, load }]) => {
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'esbuild';
2
+ import type { PluginOptions } from '../types';
3
+ export declare function resolvePlugin({ context }: PluginOptions): Plugin;
@@ -16,28 +16,27 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var dependencyAliasPlugin_exports = {};
20
- __export(dependencyAliasPlugin_exports, {
21
- dependencyAliasPlugin: () => dependencyAliasPlugin
19
+ var resolvePlugin_exports = {};
20
+ __export(resolvePlugin_exports, {
21
+ resolvePlugin: () => resolvePlugin
22
22
  });
23
- module.exports = __toCommonJS(dependencyAliasPlugin_exports);
24
- var import_aliasResolver = require("./aliasResolver");
25
- var import_protocolResolver = require("./protocolResolver");
26
- function dependencyAliasPlugin({ context }) {
27
- const pluginName = "dependency-alias-plugin";
23
+ module.exports = __toCommonJS(resolvePlugin_exports);
24
+ var import_setupAliasResolver = require("./alias/setupAliasResolver");
25
+ var import_setupProtocolResolver = require("./protocol/setupProtocolResolver");
26
+ function resolvePlugin({ context }) {
28
27
  return {
29
- name: pluginName,
28
+ name: "resolve-plugin",
30
29
  setup(build) {
31
- const { rootDir, buildConfig } = context.config;
30
+ const { buildConfig } = context.config;
32
31
  const { resolver } = buildConfig;
33
32
  const alias = resolver?.alias ?? [];
34
33
  const protocols = resolver?.protocols ?? {};
35
- (0, import_aliasResolver.setupAliasResolver)(build, rootDir, alias);
36
- (0, import_protocolResolver.setupProtocolResolver)(build, protocols);
34
+ (0, import_setupAliasResolver.setupAliasResolver)(build, alias);
35
+ (0, import_setupProtocolResolver.setupProtocolResolver)(build, protocols);
37
36
  }
38
37
  };
39
38
  }
40
39
  // Annotate the CommonJS export names for ESM import in node:
41
40
  0 && (module.exports = {
42
- dependencyAliasPlugin
41
+ resolvePlugin
43
42
  });
@@ -1,15 +1,23 @@
1
1
  import { OnLoadArgs, PluginBuild } from 'esbuild';
2
2
  /**
3
- * Entry Point 모듈을 찾아 마킹하기 위한 `onResolve` 콜백 등록
3
+ * Register `onResolve` callback to mark the module as entry point module
4
4
  */
5
5
  export declare function registerEntryPointMarker(build: PluginBuild): void;
6
6
  /**
7
- * 가상의 Prelude script 경로를 Tree Shaking 없이 직접 resolve 하기 위한 `onResolve` 콜백 등록
7
+ * Register `onResolve` callback to resolve the virtual prelude script path
8
+ *
9
+ * This callback is used to resolve the virtual prelude script path without tree shaking.
10
+ *
11
+ * ```ts
12
+ * import 'prelude:foo';
13
+ * import 'prelude:bar';
14
+ * import 'prelude:baz';
15
+ * ```
8
16
  */
9
17
  export declare function registerPreludeScriptResolver(build: PluginBuild): void;
10
18
  export declare function isEntryPoint(args: OnLoadArgs): boolean;
11
19
  /**
12
- * 코드 최상단에 prelude 스크립트 추가
20
+ * Returns string that inject prelude script at the top of the code
13
21
  *
14
22
  * ```ts
15
23
  * import 'prelude:foo';
@@ -38,21 +38,20 @@ var path = __toESM(require("path"));
38
38
  var import_es_toolkit = require("es-toolkit");
39
39
  var import_constants = require("../../../../constants");
40
40
  var import_esbuildUtils = require("../../../../utils/esbuildUtils");
41
- const skipResolve = Symbol.for("skipResolve");
42
- const isEntry = Symbol.for("isEntry");
41
+ var import_resolveHelpers = require("../../resolveHelpers");
42
+ const IS_ENTRY_FLAG = Symbol.for("mpack:IS_ENTRY_FLAG");
43
43
  function registerEntryPointMarker(build) {
44
+ const resolver = (0, import_resolveHelpers.createNonRecursiveResolver)(build);
44
45
  build.onResolve({ filter: /\.([mc]js|[tj]sx?)$/ }, async (args) => {
45
- if (args.pluginData !== skipResolve && args.kind === "entry-point") {
46
- const { path: path2, errors } = await build.resolve(args.path, {
47
- importer: args.importer,
48
- kind: args.kind,
49
- resolveDir: args.resolveDir,
50
- // 한 번만 resolve 하기 위한 플래그 값
51
- pluginData: skipResolve
52
- });
53
- return errors.length === 0 ? { path: path2, pluginData: isEntry } : { errors };
46
+ if (args.kind !== "entry-point") {
47
+ return null;
54
48
  }
55
- return null;
49
+ const result = await resolver(args, {
50
+ importer: args.importer,
51
+ kind: args.kind,
52
+ resolveDir: args.resolveDir
53
+ });
54
+ return result ? { ...result, pluginData: IS_ENTRY_FLAG } : null;
56
55
  });
57
56
  }
58
57
  function registerPreludeScriptResolver(build) {
@@ -63,7 +62,7 @@ function registerPreludeScriptResolver(build) {
63
62
  });
64
63
  }
65
64
  function isEntryPoint(args) {
66
- return args.pluginData === isEntry;
65
+ return args.pluginData === IS_ENTRY_FLAG;
67
66
  }
68
67
  function injectPreludeScript(code, {
69
68
  preludeScriptPaths
@@ -1,4 +1,4 @@
1
- import { type BuildConfig, type BuildResult, type CompleteGraniteConfig } from '@granite-js/plugin-core';
1
+ import { type BuildConfig, type CompleteGraniteConfig } from '@granite-js/plugin-core';
2
2
  import type { BundlerConfig, PluginFactory } from '../types';
3
3
  type CommonBuildOptions = Omit<BundlerConfig, 'rootDir' | 'buildConfig'> & Pick<BuildConfig, 'platform' | 'outfile'>;
4
4
  export interface BuildOptions extends CommonBuildOptions {
@@ -10,6 +10,6 @@ export interface BuildAllOptions {
10
10
  concurrency?: number;
11
11
  plugins?: PluginFactory[];
12
12
  }
13
- export declare function build({ config, plugins, ...options }: BuildOptions): Promise<BuildResult>;
14
- export declare function buildAll(optionsList: CommonBuildOptions[], { config, plugins, concurrency }: BuildAllOptions): Promise<BuildResult[]>;
13
+ export declare function build({ config, plugins, ...options }: BuildOptions): Promise<import("@granite-js/plugin-core").BuildSuccessResult>;
14
+ export declare function buildAll(optionsList: CommonBuildOptions[], { config, plugins, concurrency }: BuildAllOptions): Promise<import("@granite-js/plugin-core").BuildSuccessResult[]>;
15
15
  export {};
@@ -38,7 +38,9 @@ var import_plugin_core = require("@granite-js/plugin-core");
38
38
  var import_es_toolkit = require("es-toolkit");
39
39
  var import_bundler = require("../bundler");
40
40
  var import_performance = require("../performance");
41
+ var import_buildResult = require("../utils/buildResult");
41
42
  var import_getDefaultOutfileName = require("../utils/getDefaultOutfileName");
43
+ var import_promise = require("../utils/promise");
42
44
  var import_writeBundle = require("../utils/writeBundle");
43
45
  async function build({ config, plugins = [], ...options }) {
44
46
  const driver = (0, import_plugin_core.createPluginHooksDriver)(config);
@@ -48,21 +50,24 @@ async function build({ config, plugins = [], ...options }) {
48
50
  return buildResult;
49
51
  }
50
52
  async function buildAll(optionsList, { config, plugins = [], concurrency = 2 }) {
51
- const buildResults = [];
52
53
  const semaphore = new import_es_toolkit.Semaphore(Math.min(concurrency, optionsList.length));
53
54
  const driver = (0, import_plugin_core.createPluginHooksDriver)(config);
54
55
  await driver.build.pre();
55
- await Promise.all(
56
+ const taskResults = await Promise.allSettled(
56
57
  optionsList.map(async (options) => {
57
58
  await semaphore.acquire();
58
59
  try {
59
60
  const buildResult = await buildImpl(config, plugins, options);
60
- buildResults.push(buildResult);
61
- } catch {
61
+ return buildResult;
62
+ } finally {
62
63
  semaphore.release();
63
64
  }
64
65
  })
65
66
  );
67
+ if (taskResults.some(import_promise.isRejected)) {
68
+ throw new Error("Build failed");
69
+ }
70
+ const buildResults = taskResults.filter(import_promise.isFulfilled).map((result) => result.value);
66
71
  await driver.build.post({ buildResults });
67
72
  return buildResults;
68
73
  }
@@ -85,13 +90,17 @@ async function buildImpl(config, plugins, { platform, outfile, cache = true, dev
85
90
  bundler.addPlugin(plugin());
86
91
  }
87
92
  const buildResult = await bundler.build();
88
- await (0, import_writeBundle.writeBundle)(buildResult.outfile, buildResult.bundle);
89
- const performanceSummary = import_performance.Performance.getSummary();
90
- if (performanceSummary != null) {
91
- (0, import_performance.printSummary)(performanceSummary);
92
- await fs.writeFile(path.join(config.cwd, "perf.json"), JSON.stringify(performanceSummary, null, 2), "utf-8");
93
+ if ((0, import_buildResult.isBuildSuccess)(buildResult)) {
94
+ await (0, import_writeBundle.writeBundle)(buildResult.outfile, buildResult.bundle);
95
+ const performanceSummary = import_performance.Performance.getSummary();
96
+ if (performanceSummary != null) {
97
+ (0, import_performance.printSummary)(performanceSummary);
98
+ await fs.writeFile(path.join(config.cwd, "perf.json"), JSON.stringify(performanceSummary, null, 2), "utf-8");
99
+ }
100
+ return buildResult;
101
+ } else {
102
+ throw new Error("Build failed");
93
103
  }
94
- return buildResult;
95
104
  }
96
105
  // Annotate the CommonJS export names for ESM import in node:
97
106
  0 && (module.exports = {
@@ -42,16 +42,17 @@ function statusPlugin(handlers) {
42
42
  handlers?.onStart?.();
43
43
  },
44
44
  buildEnd(result) {
45
- progressBar.update(result.totalModuleCount);
46
- progressBar.hide();
47
- progressBar.remove();
48
- if (result.errors.length === 0) {
45
+ if ("bundle" in result) {
49
46
  totalModuleCount = result.totalModuleCount;
50
47
  import_PersistentStorage.persistentStorage.setData({ [this.id]: { totalModuleCount: result.totalModuleCount } });
51
48
  import_PersistentStorage.persistentStorage.saveData();
52
- handlers?.onEnd?.();
49
+ } else {
50
+ totalModuleCount = void 0;
53
51
  }
54
- (0, import_es_toolkit.delay)(100).then(() => (0, import_printSummary.printSummary)(result));
52
+ progressBar.hide();
53
+ progressBar.remove();
54
+ handlers?.onEnd?.();
55
+ (0, import_es_toolkit.delay)(100).then(() => (0, import_printSummary.printSummary)(result)).catch(import_es_toolkit.noop);
55
56
  },
56
57
  load: (moduleCount) => {
57
58
  progressBar.update(moduleCount, totalModuleCount);
@@ -192,21 +192,25 @@ class DevServer {
192
192
  }
193
193
  async getBundle(platform) {
194
194
  const { bundler } = this.getContext()[platform];
195
- const { bundle } = await bundler.build({ withDispose: false });
195
+ const buildResult = await bundler.build({ withDispose: false });
196
196
  let targetBundle;
197
- if (globalThis.remoteBundles != null) {
198
- const hostBundleContent = bundle.source.text;
199
- const remoteBundleContent = globalThis.remoteBundles[platform];
200
- const mergedBundle = await (0, import_mergeBundles.mergeBundles)({
201
- platform,
202
- hostBundleContent,
203
- remoteBundleContent
204
- });
205
- targetBundle = mergedBundle;
197
+ if ("bundle" in buildResult) {
198
+ if (globalThis.remoteBundles != null) {
199
+ const hostBundleContent = buildResult.bundle.source.text;
200
+ const remoteBundleContent = globalThis.remoteBundles[platform];
201
+ const mergedBundle = await (0, import_mergeBundles.mergeBundles)({
202
+ platform,
203
+ hostBundleContent,
204
+ remoteBundleContent
205
+ });
206
+ targetBundle = mergedBundle;
207
+ } else {
208
+ targetBundle = buildResult.bundle;
209
+ }
210
+ return targetBundle;
206
211
  } else {
207
- targetBundle = bundle;
212
+ throw new Error("Build failed");
208
213
  }
209
- return targetBundle;
210
214
  }
211
215
  }
212
216
  // Annotate the CommonJS export names for ESM import in node:
@@ -0,0 +1,2 @@
1
+ import type { BuildResult, BuildSuccessResult } from '@granite-js/plugin-core';
2
+ export declare function isBuildSuccess(result: BuildResult): result is BuildSuccessResult;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var buildResult_exports = {};
20
+ __export(buildResult_exports, {
21
+ isBuildSuccess: () => isBuildSuccess
22
+ });
23
+ module.exports = __toCommonJS(buildResult_exports);
24
+ function isBuildSuccess(result) {
25
+ return "bundle" in result;
26
+ }
27
+ // Annotate the CommonJS export names for ESM import in node:
28
+ 0 && (module.exports = {
29
+ isBuildSuccess
30
+ });
@@ -1,7 +1,2 @@
1
- import { Message } from 'esbuild';
2
- export declare function printSummary<Result extends {
3
- warnings: Message[];
4
- errors: Message[];
5
- totalModuleCount: number;
6
- duration: number;
7
- }>({ warnings, errors, totalModuleCount, duration }: Result): Promise<void>;
1
+ import type { BuildResult } from '@granite-js/plugin-core';
2
+ export declare function printSummary(buildResult: BuildResult): Promise<void>;
@@ -32,22 +32,27 @@ __export(printSummary_exports, {
32
32
  });
33
33
  module.exports = __toCommonJS(printSummary_exports);
34
34
  var import_chalk = __toESM(require("chalk"));
35
+ var import_es_toolkit = require("es-toolkit");
35
36
  var import_esbuild = require("esbuild");
36
37
  var import_logger = require("../logger");
37
- function printSummary({ warnings, errors, totalModuleCount, duration }) {
38
- return Promise.all([(0, import_esbuild.formatMessages)(warnings, { kind: "warning" }), (0, import_esbuild.formatMessages)(errors, { kind: "error" })]).then(
39
- ([warnings2, errors2]) => {
40
- warnings2.forEach((message) => import_logger.logger.warn("\n\n", message));
41
- errors2.forEach((message) => import_logger.logger.error("\n\n", message));
42
- const durations = import_chalk.default.underline(`${totalModuleCount} Modules (${(duration / 1e3).toFixed(2)}s)`);
43
- const summary = [
44
- durations,
45
- `${import_chalk.default.red(errors2.length)} errors`,
46
- `${import_chalk.default.yellow(warnings2.length)} warnings`
47
- ].join(import_chalk.default.white(" | "));
48
- import_logger.logger.info(import_chalk.default.gray(summary));
49
- }
50
- );
38
+ var import_buildResult = require("./buildResult");
39
+ function printSummary(buildResult) {
40
+ return Promise.all([
41
+ (0, import_esbuild.formatMessages)(buildResult.warnings, { kind: "warning", color: true }),
42
+ (0, import_esbuild.formatMessages)(buildResult.errors, { kind: "error", color: true })
43
+ ]).then(([warnings, errors]) => {
44
+ warnings.forEach((message) => console.warn("\n\n", message));
45
+ errors.forEach((message) => console.error("\n\n", message));
46
+ const platform = `[${buildResult.platform}]`;
47
+ const moduleCountAndDuration = (0, import_buildResult.isBuildSuccess)(buildResult) ? import_chalk.default.underline(`${buildResult.totalModuleCount} Modules (${(buildResult.duration / 1e3).toFixed(2)}s)`) : null;
48
+ const summary = [
49
+ platform,
50
+ moduleCountAndDuration,
51
+ `${import_chalk.default.red(errors.length)} errors`,
52
+ `${import_chalk.default.yellow(warnings.length)} warnings`
53
+ ].filter(import_es_toolkit.isNotNil).join(import_chalk.default.white(" | "));
54
+ import_logger.logger.info(import_chalk.default.gray(summary));
55
+ });
51
56
  }
52
57
  // Annotate the CommonJS export names for ESM import in node:
53
58
  0 && (module.exports = {
@@ -10,3 +10,5 @@ export declare class PromiseHandler<T> {
10
10
  done(result: T): void;
11
11
  abort(reason?: Error): void;
12
12
  }
13
+ export declare function isFulfilled<T>(task: PromiseSettledResult<T>): task is PromiseFulfilledResult<T>;
14
+ export declare function isRejected<T>(task: PromiseSettledResult<T>): task is PromiseRejectedResult;
@@ -16,11 +16,13 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var promiseHandler_exports = {};
20
- __export(promiseHandler_exports, {
21
- PromiseHandler: () => PromiseHandler
19
+ var promise_exports = {};
20
+ __export(promise_exports, {
21
+ PromiseHandler: () => PromiseHandler,
22
+ isFulfilled: () => isFulfilled,
23
+ isRejected: () => isRejected
22
24
  });
23
- module.exports = __toCommonJS(promiseHandler_exports);
25
+ module.exports = __toCommonJS(promise_exports);
24
26
  var import_es_toolkit = require("es-toolkit");
25
27
  class PromiseHandler {
26
28
  constructor(revisionId) {
@@ -48,7 +50,15 @@ class PromiseHandler {
48
50
  this.rejector(reason);
49
51
  }
50
52
  }
53
+ function isFulfilled(task) {
54
+ return task.status === "fulfilled";
55
+ }
56
+ function isRejected(task) {
57
+ return task.status === "rejected";
58
+ }
51
59
  // Annotate the CommonJS export names for ESM import in node:
52
60
  0 && (module.exports = {
53
- PromiseHandler
61
+ PromiseHandler,
62
+ isFulfilled,
63
+ isRejected
54
64
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@granite-js/mpack",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "A bundler for Granite apps",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -83,9 +83,9 @@
83
83
  "@babel/traverse": "^7.14.0",
84
84
  "@babel/types": "^7.0.0",
85
85
  "@fastify/static": "7.0.1",
86
- "@granite-js/devtools-frontend": "0.1.10",
87
- "@granite-js/plugin-core": "0.1.10",
88
- "@granite-js/utils": "0.1.10",
86
+ "@granite-js/devtools-frontend": "0.1.12",
87
+ "@granite-js/plugin-core": "0.1.12",
88
+ "@granite-js/utils": "0.1.12",
89
89
  "@inquirer/prompts": "^7.2.3",
90
90
  "@react-native-community/cli-plugin-metro": "11.3.7",
91
91
  "@react-native-community/cli-server-api": "11.3.7",
@@ -1,3 +0,0 @@
1
- import type { AliasConfig } from '@granite-js/plugin-core';
2
- import type { PluginBuild } from 'esbuild';
3
- export declare function setupAliasResolver(build: PluginBuild, rootDir: string, aliasConfig: AliasConfig[]): void;
@@ -1,89 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var aliasResolver_exports = {};
30
- __export(aliasResolver_exports, {
31
- setupAliasResolver: () => setupAliasResolver
32
- });
33
- module.exports = __toCommonJS(aliasResolver_exports);
34
- var import_path = __toESM(require("path"));
35
- var import_performance = require("../../../performance");
36
- var import_esbuildUtils = require("../../../utils/esbuildUtils");
37
- var import_replaceModulePath = require("../../../utils/replaceModulePath");
38
- var import_swc = require("../shared/swc");
39
- const resolved = Symbol();
40
- function setupAliasResolver(build, rootDir, aliasConfig) {
41
- function aliasResolver(path2, options) {
42
- return build.resolve(path2, {
43
- ...options,
44
- pluginData: {
45
- ...options?.pluginData,
46
- [resolved]: true
47
- }
48
- });
49
- }
50
- [import_swc.swcHelperOptimizationRules.getAliasConfig(), ...aliasConfig].forEach(({ from, to, exact }) => {
51
- const resolveResultCache = /* @__PURE__ */ new Map();
52
- const filter = new RegExp(exact ? `^${from}$` : `^${from}(?:$|/)`);
53
- build.onResolve({ filter }, async (args) => {
54
- if (args.pluginData?.[resolved]) {
55
- return;
56
- }
57
- const trace = import_performance.Performance.trace("alias-resolver", {
58
- detail: { pattern: filter, path: args.path }
59
- });
60
- const resolvedPath = typeof to === "string" ? (0, import_replaceModulePath.replaceModulePath)(args.path, from, to) : await to({ resolve: aliasResolver, args });
61
- const normalizedPath = (0, import_esbuildUtils.normalizePath)(resolvedPath);
62
- const cacheKey = `${args.kind}:${normalizedPath}`;
63
- if (resolveResultCache.has(cacheKey)) {
64
- trace.stop({ detail: { cacheHit: true } });
65
- return resolveResultCache.get(cacheKey);
66
- }
67
- if (import_path.default.isAbsolute(normalizedPath)) {
68
- trace.stop({ detail: { isAbsolute: true } });
69
- const result2 = { path: normalizedPath };
70
- resolveResultCache.set(cacheKey, result2);
71
- return result2;
72
- }
73
- const result = await build.resolve(normalizedPath, {
74
- resolveDir: rootDir,
75
- kind: args.kind,
76
- pluginData: {
77
- [resolved]: true
78
- }
79
- });
80
- trace.stop({ detail: { cacheHit: false, isAbsolute: false } });
81
- resolveResultCache.set(cacheKey, result);
82
- return result;
83
- });
84
- });
85
- }
86
- // Annotate the CommonJS export names for ESM import in node:
87
- 0 && (module.exports = {
88
- setupAliasResolver
89
- });
@@ -1,3 +0,0 @@
1
- import type { Plugin } from 'esbuild';
2
- import { PluginOptions } from '../types';
3
- export declare function dependencyAliasPlugin({ context }: PluginOptions): Plugin;
@@ -1 +0,0 @@
1
- export { dependencyAliasPlugin } from './dependencyAliasPlugin';