olum-compiler 1.9.0 → 1.9.2

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.
package/bin/copySrc.js CHANGED
@@ -1,12 +1,14 @@
1
1
  const path = require("path");
2
2
  const fs = require("fs");
3
- const { copy, compileRoutes } = require("../lib/helpers");
3
+ const { copy, compileRoutes, ls, isFile } = require("../lib/helpers");
4
4
  const importMap = require("../lib/importMap");
5
5
  const usage = require("../lib/usage");
6
+ const splitJsBarrels = require("../lib/jsBarrels");
6
7
 
7
8
  const cwd = process.cwd();
8
- const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src");
9
- const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public");
9
+ const projectRoot = cwd.replace(/\/module$/, "");
10
+ const entryPoint = path.resolve(projectRoot, "src");
11
+ const entryPoint2 = path.resolve(projectRoot, "public");
10
12
 
11
13
  const devtoolSrc = path.resolve(
12
14
  cwd.replace(/\/module$/, ""),
@@ -36,6 +38,13 @@ function injectIndexHtml(indexHtmlPath) {
36
38
  fs.writeFileSync(indexHtmlPath, indexHtmlContent);
37
39
  }
38
40
 
41
+ function splitCopiedJs() {
42
+ ls(srcDest, { absolute: true }).forEach((file) => {
43
+ if (isFile(file) && file.endsWith(".js"))
44
+ splitJsBarrels.file(file, projectRoot);
45
+ });
46
+ }
47
+
39
48
  function handleMainJs() {
40
49
  if (fs.existsSync(mainJsPathDest)) return;
41
50
  const mainJsContent = compileRoutes(entryPoint);
@@ -61,6 +70,7 @@ function syncFile(event, file) {
61
70
  } else {
62
71
  fs.mkdirSync(path.dirname(dest), { recursive: true });
63
72
  fs.copyFileSync(file, dest);
73
+ if (inSrc && dest.endsWith(".js")) splitJsBarrels.file(dest, projectRoot);
64
74
  if (dest === indexHtmlDest) injectIndexHtml(dest);
65
75
  }
66
76
 
@@ -86,7 +96,10 @@ module.exports = function copySrc(event, file) {
86
96
  fs.rmSync(publicDest, { recursive: true, force: true });
87
97
  fs.rmSync(srcDest, { recursive: true, force: true });
88
98
 
89
- copy(entryPoint, srcDest, () => handleMainJs());
99
+ copy(entryPoint, srcDest, () => {
100
+ splitCopiedJs();
101
+ handleMainJs();
102
+ });
90
103
  copy(entryPoint2, publicDest, () => injectIndexHtml(indexHtmlDest));
91
104
 
92
105
  if (devtoolEnabled) {
@@ -24,64 +24,116 @@ function pickEntry(exp) {
24
24
  return null;
25
25
  }
26
26
 
27
- // A package with an `exports` map is only reachable through the subpaths it
28
- // lists -- a file that exists on disk but isn't exported can't be imported by
29
- // name, and bundlers hard-fail on the attempt. Deep-importing a barrel member
30
- // is only safe once the target survives this check. Mirrors the pattern
31
- // matching in Node's PACKAGE_EXPORTS_RESOLVE, minus the condition ordering
32
- // (pickEntry already picks a browser/ESM branch).
33
- function exposes(exp, subpath, dir) {
34
- // Matching a pattern isn't enough -- the wildcard has to be substituted back
35
- // into the target and the result has to exist. "./*.js": "./dist/*.js" does
36
- // match "./dist/OlumLogo.js", but resolves it to "./dist/dist/OlumLogo.js",
37
- // which is nothing. Approving that would emit a specifier no bundler
38
- // resolves, which is the failure this whole check exists to prevent.
39
- const lands = (target) =>
40
- typeof target === "string" &&
41
- fs.existsSync(path.resolve(dir, target.replace(/^\.?\//, "")));
42
-
43
- // No exports field at all: legacy resolution, every file is addressable.
44
- if (exp == null) return true;
45
-
46
- // A string, an array or a bare conditions object describes the root export
47
- // and nothing else, so no deep path is reachable.
48
- const isSubpathMap =
49
- typeof exp === "object" &&
50
- !Array.isArray(exp) &&
51
- Object.keys(exp).some((key) => key.startsWith("."));
52
- if (!isSubpathMap) return false;
53
-
54
- if (Object.hasOwn(exp, subpath)) return lands(pickEntry(exp[subpath]));
55
-
56
- // Longest matching prefix wins, as in Node's resolver.
27
+ const isSubpathMap = (exp) =>
28
+ exp != null &&
29
+ typeof exp === "object" &&
30
+ !Array.isArray(exp) &&
31
+ Object.keys(exp).some((key) => key.startsWith("."));
32
+
33
+ const toPath = (dir, target) => path.resolve(dir, target.replace(/^\.?\//, ""));
34
+
35
+ const splitStar = (str) => {
36
+ const star = str.indexOf("*");
37
+ return star === -1 ? null : [str.slice(0, star), str.slice(star + 1)];
38
+ };
39
+
40
+ function resolveTarget(exp, subpath) {
41
+ if (!isSubpathMap(exp)) return null;
42
+ if (Object.hasOwn(exp, subpath)) return pickEntry(exp[subpath]);
43
+
57
44
  let best = null;
58
45
  for (const key of Object.keys(exp)) {
59
- const star = key.indexOf("*");
60
- if (star === -1) continue;
61
- const prefix = key.slice(0, star);
62
- const suffix = key.slice(star + 1);
63
- if (subpath.length < prefix.length + suffix.length) continue;
46
+ const parts = splitStar(key);
47
+ if (!parts) continue;
48
+ const [prefix, suffix] = parts;
49
+ if (subpath.length <= prefix.length + suffix.length) continue;
64
50
  if (!subpath.startsWith(prefix)) continue;
65
51
  if (suffix && !subpath.endsWith(suffix)) continue;
66
52
  if (!best || prefix.length > best.prefix.length)
67
53
  best = { prefix, suffix, value: exp[key] };
68
54
  }
69
- if (!best) return false;
55
+ if (!best) return null;
70
56
 
71
57
  const target = pickEntry(best.value);
72
- if (typeof target !== "string" || !target.includes("*")) return lands(target);
73
-
58
+ if (typeof target !== "string" || !target.includes("*")) return target;
74
59
  const captured = subpath.slice(
75
60
  best.prefix.length,
76
61
  best.suffix ? subpath.length - best.suffix.length : undefined,
77
62
  );
78
- return lands(target.replace("*", captured));
63
+ return target.replace("*", captured);
64
+ }
65
+
66
+ function subpathOf(exp, rel, dir) {
67
+ if (rel.startsWith("../")) return null;
68
+ const file = "./" + rel;
69
+ if (exp == null) return file;
70
+ if (!isSubpathMap(exp)) return null;
71
+
72
+ const hits = (subpath) => {
73
+ const target = resolveTarget(exp, subpath);
74
+ return (
75
+ typeof target === "string" && toPath(dir, target) === toPath(dir, file)
76
+ );
77
+ };
78
+
79
+ for (const key of Object.keys(exp)) {
80
+ if (key === "." || key.includes("*")) continue;
81
+ if (hits(key)) return key;
82
+ }
83
+
84
+ let best = null;
85
+ for (const key of Object.keys(exp)) {
86
+ const keyParts = splitStar(key);
87
+ if (!keyParts) continue;
88
+ const target = pickEntry(exp[key]);
89
+ if (typeof target !== "string") continue;
90
+ const targetParts = splitStar(target);
91
+ if (!targetParts) continue;
92
+ const [keyPrefix, keySuffix] = keyParts;
93
+ const [targetPrefix, targetSuffix] = targetParts;
94
+
95
+ if (keySuffix !== targetSuffix) continue;
96
+ if (file.length <= targetPrefix.length + targetSuffix.length) continue;
97
+ if (!file.startsWith(targetPrefix) || !file.endsWith(targetSuffix))
98
+ continue;
99
+ const captured = file.slice(
100
+ targetPrefix.length,
101
+ targetSuffix ? file.length - targetSuffix.length : undefined,
102
+ );
103
+ const subpath = keyPrefix + captured + keySuffix;
104
+ if (!hits(subpath)) continue;
105
+ if (!best || targetPrefix.length > best.prefix.length)
106
+ best = { prefix: targetPrefix, subpath };
107
+ }
108
+ return best ? best.subpath : null;
109
+ }
110
+
111
+ function entryFor(dir, pkg, subpath) {
112
+ const exp = pkg.exports;
113
+ let entry;
114
+ if (isSubpathMap(exp)) {
115
+ entry = resolveTarget(exp, subpath);
116
+ if (typeof entry !== "string" && subpath === ".")
117
+ entry = pkg.module || pkg.main;
118
+ } else if (subpath === ".") {
119
+ entry = pickEntry(exp) || pkg.module || pkg.main || "index.js";
120
+ } else {
121
+ entry = subpath;
122
+ }
123
+ if (typeof entry !== "string") return null;
124
+
125
+ let entryPath = toPath(dir, entry);
126
+ if (!fs.existsSync(entryPath) && fs.existsSync(entryPath + ".js"))
127
+ entryPath += ".js";
128
+ if (fs.existsSync(entryPath) && fs.statSync(entryPath).isDirectory())
129
+ entryPath = path.join(entryPath, "index.js");
130
+ return fs.existsSync(entryPath) ? entryPath : null;
79
131
  }
80
132
 
81
133
  const nameOf = (node) => (node.type === "Identifier" ? node.name : node.value);
82
134
 
83
- function barrelMap(rootDir, pkgName) {
84
- const key = rootDir + "\0" + pkgName;
135
+ function barrelMap(rootDir, pkgName, subpath) {
136
+ const key = rootDir + "\0" + pkgName + "\0" + subpath;
85
137
  if (cache.has(key)) return cache.get(key);
86
138
 
87
139
  let map = null;
@@ -91,16 +143,7 @@ function barrelMap(rootDir, pkgName) {
91
143
  fs.readFileSync(path.join(dir, "package.json"), "utf8"),
92
144
  );
93
145
 
94
- let exp = pkg.exports;
95
- if (exp && typeof exp === "object" && !Array.isArray(exp)) {
96
- const keys = Object.keys(exp);
97
- if (keys.some((k) => k.startsWith("."))) exp = exp["."];
98
- }
99
- let entry = pickEntry(exp) || pkg.module || pkg.main || "index.js";
100
- let entryPath = path.resolve(dir, entry.replace(/^\.?\//, ""));
101
- if (fs.existsSync(entryPath) && fs.statSync(entryPath).isDirectory())
102
- entryPath = path.join(entryPath, "index.js");
103
-
146
+ const entryPath = entryFor(dir, pkg, subpath);
104
147
  const body = acorn.parse(fs.readFileSync(entryPath, "utf8"), {
105
148
  ecmaVersion: "latest",
106
149
  sourceType: "module",
@@ -116,10 +159,12 @@ function barrelMap(rootDir, pkgName) {
116
159
  map = new Map();
117
160
  body.forEach((node) => {
118
161
  const target = path.resolve(path.dirname(entryPath), node.source.value);
162
+ if (!fs.existsSync(target)) return;
119
163
  const rel = path.relative(dir, target).split(path.sep).join("/");
120
- // Also drops re-exports that resolve outside the package ("../").
121
- if (!exposes(pkg.exports, "./" + rel, dir)) return;
122
- const spec = pkgName + "/" + rel;
164
+
165
+ const member = subpathOf(pkg.exports, rel, dir);
166
+ if (!member) return;
167
+ const spec = pkgName + member.slice(1);
123
168
  node.specifiers.forEach((item) =>
124
169
  map.set(nameOf(item.exported), {
125
170
  spec,
@@ -159,18 +204,20 @@ function splitBarrels(statement, rootDir) {
159
204
  const pkgName = source.startsWith("@")
160
205
  ? segments.slice(0, 2).join("/")
161
206
  : segments[0];
162
- if (pkgName !== source) return statement;
207
+
208
+ const rest = source.slice(pkgName.length);
209
+ const subpath = rest ? "." + rest : ".";
163
210
  if (!node.specifiers.length) return statement;
164
211
  if (!node.specifiers.every((item) => item.type === "ImportSpecifier"))
165
212
  return statement;
166
213
 
167
- const map = barrelMap(root, pkgName);
214
+ const map = barrelMap(root, pkgName, subpath);
168
215
  if (!map) return statement;
169
216
 
170
217
  const lines = [];
171
218
  for (const item of node.specifiers) {
172
219
  const hit = map.get(nameOf(item.imported));
173
- if (!hit) return statement;
220
+ if (!hit || hit.spec === source) return statement;
174
221
  const local = item.local.name;
175
222
  lines.push(
176
223
  hit.imported === "default"
package/lib/importMap.js CHANGED
@@ -25,11 +25,6 @@ function pickEntry(exp) {
25
25
  return null;
26
26
  }
27
27
 
28
- // A `pkgName + "/"` prefix entry resolves every subpath straight to disk, which
29
- // is only how Node behaves for a package with no `exports` map. Where a map
30
- // exists its keys are aliases -- "olum-icons/lucide" names dist/lucide/index.js,
31
- // it isn't a path -- so each one needs an entry of its own, and the blanket
32
- // prefix has to go: it would let dev resolve specifiers the bundler rejects.
33
28
  function subpathImports(pkg, pkgName) {
34
29
  const base = "/node_modules/" + pkgName + "/";
35
30
  const exp = pkg.exports;
@@ -49,10 +44,7 @@ function subpathImports(pkg, pkgName) {
49
44
  imports[pkgName + key.slice(1)] = base + target.replace(/^\.?\//, "");
50
45
  return;
51
46
  }
52
- // An import map only substitutes prefixes, so a pattern is expressible
53
- // when both sides carry the same text after the wildcard -- that text is
54
- // then part of the specifier the browser writes and needs no rewriting.
55
- // "./*.js": "./dist/*.js" becomes "pkg/" -> "/node_modules/pkg/dist/".
47
+
56
48
  const [keyPrefix, keySuffix] = key.split("*");
57
49
  const [targetPrefix, targetSuffix] = target.split("*");
58
50
  if (keySuffix !== targetSuffix) return;
@@ -192,6 +184,5 @@ function importMap(srcDir) {
192
184
  }
193
185
 
194
186
  module.exports = importMap;
195
- // Exposed for the test suite -- the interesting logic is the exports-map
196
- // translation, which shouldn't need a whole node_modules tree to exercise.
187
+
197
188
  module.exports.subpathImports = subpathImports;
@@ -0,0 +1,39 @@
1
+ const fs = require("fs");
2
+ const acorn = require("acorn");
3
+ const splitBarrels = require("./barrelSplit");
4
+
5
+ const hasBareImport = (code) => /from\s*["'][^./"']/.test(code);
6
+
7
+ function splitJsBarrels(code, rootDir) {
8
+ if (!hasBareImport(code)) return code;
9
+
10
+ let body;
11
+ try {
12
+ body = acorn.parse(code, {
13
+ ecmaVersion: "latest",
14
+ sourceType: "module",
15
+ }).body;
16
+ } catch (e) {
17
+ return code;
18
+ }
19
+
20
+ const nodes = body.filter((node) => node.type === "ImportDeclaration");
21
+
22
+ for (let i = nodes.length - 1; i >= 0; i--) {
23
+ const { start, end } = nodes[i];
24
+ const statement = code.slice(start, end);
25
+ const split = splitBarrels(statement, rootDir);
26
+ if (split !== statement)
27
+ code = code.slice(0, start) + split + code.slice(end);
28
+ }
29
+ return code;
30
+ }
31
+
32
+ function splitFile(file, rootDir) {
33
+ const code = fs.readFileSync(file, "utf8");
34
+ const split = splitJsBarrels(code, rootDir);
35
+ if (split !== code) fs.writeFileSync(file, split);
36
+ }
37
+
38
+ module.exports = splitJsBarrels;
39
+ module.exports.file = splitFile;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.9.0",
3
+ "version": "1.9.2",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -1019,8 +1019,6 @@ section("§24 Barrel splitting");
1019
1019
 
1020
1020
  const splitBarrels = require("../lib/barrelSplit");
1021
1021
 
1022
- // splitBarrels reads the dependency off disk, so these run against throwaway
1023
- // packages instead of a compiled template.
1024
1022
  const fixtureRoot = fs.mkdtempSync(nodePath.join(os.tmpdir(), "olum-barrel-"));
1025
1023
 
1026
1024
  function pkg(name, files) {
@@ -1131,9 +1129,9 @@ pkg("shifted-barrel", {
1131
1129
  });
1132
1130
 
1133
1131
  split(
1134
- "leaves the barrel alone when the pattern matches but resolves nowhere",
1132
+ "names the target through the pattern, not by its path on disk",
1135
1133
  `import { A } from "shifted-barrel";`,
1136
- untouched(`import { A } from "shifted-barrel";`),
1134
+ (out) => /^import \{ A as A \} from "shifted-barrel\/A\.js";$/.test(out),
1137
1135
  );
1138
1136
 
1139
1137
  pkg("flat-barrel", {
@@ -1153,11 +1151,64 @@ split(
1153
1151
  );
1154
1152
 
1155
1153
  split(
1156
- "leaves a subpath import alone",
1154
+ "leaves a subpath import alone when it isn't a barrel",
1157
1155
  `import { A } from "wildcard-barrel/dist/A.js";`,
1158
1156
  untouched(`import { A } from "wildcard-barrel/dist/A.js";`),
1159
1157
  );
1160
1158
 
1159
+ pkg("nested-barrel", {
1160
+ "package.json": {
1161
+ name: "nested-barrel",
1162
+ exports: {
1163
+ ".": "./dist/index.js",
1164
+ "./sub": "./dist/sub/index.js",
1165
+ "./*.js": "./dist/*.js",
1166
+ },
1167
+ },
1168
+ "dist/index.js": BARREL,
1169
+ "dist/A.js": "export const A = 1;",
1170
+ "dist/B.js": "export const B = 2;",
1171
+ "dist/sub/index.js": `export { C } from "./C.js";\n`,
1172
+ "dist/sub/C.js": "export const C = 3;",
1173
+ });
1174
+
1175
+ split(
1176
+ "splits a barrel reached through a subpath",
1177
+ `import { C } from "nested-barrel/sub";`,
1178
+ (out) => /^import \{ C as C \} from "nested-barrel\/sub\/C\.js";$/.test(out),
1179
+ );
1180
+
1181
+ pkg("legacy-nested-barrel", {
1182
+ "package.json": { name: "legacy-nested-barrel", main: "./index.js" },
1183
+ "index.js": BARREL,
1184
+ "A.js": "export const A = 1;",
1185
+ "B.js": "export const B = 2;",
1186
+ "sub/index.js": `export { C } from "./C.js";\n`,
1187
+ "sub/C.js": "export const C = 3;",
1188
+ });
1189
+
1190
+ split(
1191
+ "splits a subpath barrel in a package with no exports field",
1192
+ `import { C } from "legacy-nested-barrel/sub";`,
1193
+ (out) =>
1194
+ /^import \{ C as C \} from "legacy-nested-barrel\/sub\/C\.js";$/.test(out),
1195
+ );
1196
+
1197
+ pkg("opaque-barrel", {
1198
+ "package.json": {
1199
+ name: "opaque-barrel",
1200
+ exports: { ".": "./index.js", "./icons/*": "./dist/icons/*.js" },
1201
+ },
1202
+ "index.js": `export { A } from "./dist/icons/A.js";\n`,
1203
+ "dist/icons/A.js": "export const A = 1;",
1204
+ });
1205
+
1206
+ split(
1207
+ "leaves the barrel alone when the import map can't express the pattern",
1208
+ `import { A } from "opaque-barrel";`,
1209
+ untouched(`import { A } from "opaque-barrel";`),
1210
+ );
1211
+
1161
1212
  fs.rmSync(fixtureRoot, { recursive: true, force: true });
1162
1213
 
1163
1214
  section("§25 Import map subpaths");
@@ -1228,7 +1279,7 @@ if (failed) {
1228
1279
  console.log("");
1229
1280
  }
1230
1281
 
1231
- const EXPECTED_CHECKS = 105;
1282
+ const EXPECTED_CHECKS = 108;
1232
1283
  const total = passed + failed;
1233
1284
  if (total !== EXPECTED_CHECKS) {
1234
1285
  console.log(