unpeek 2.0.0 → 4.0.0

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 (120) hide show
  1. package/README.md +57 -21
  2. package/README.tr.md +65 -29
  3. package/dist/adapters/esbuild.cjs +13 -0
  4. package/dist/adapters/esbuild.d.cts +13 -0
  5. package/dist/adapters/esbuild.d.ts +11 -0
  6. package/dist/adapters/esbuild.js +13 -0
  7. package/dist/adapters/next/adapter.cjs +43 -0
  8. package/dist/{next → adapters/next}/adapter.d.cts +4 -4
  9. package/dist/{next → adapters/next}/adapter.d.ts +4 -4
  10. package/dist/adapters/next/adapter.js +43 -0
  11. package/dist/adapters/next/index.cjs +16 -0
  12. package/dist/adapters/next/index.d.cts +53 -0
  13. package/dist/adapters/next/index.d.ts +53 -0
  14. package/dist/adapters/next/index.js +16 -0
  15. package/dist/adapters/rollup.cjs +13 -0
  16. package/dist/adapters/rollup.d.cts +13 -0
  17. package/dist/adapters/rollup.d.ts +11 -0
  18. package/dist/adapters/rollup.js +13 -0
  19. package/dist/adapters/rspack.cjs +13 -0
  20. package/dist/adapters/rspack.d.cts +13 -0
  21. package/dist/adapters/rspack.d.ts +11 -0
  22. package/dist/adapters/rspack.js +13 -0
  23. package/dist/adapters/vite.cjs +13 -0
  24. package/dist/adapters/vite.d.cts +13 -0
  25. package/dist/adapters/vite.d.ts +11 -0
  26. package/dist/adapters/vite.js +13 -0
  27. package/dist/adapters/webpack.cjs +13 -0
  28. package/dist/adapters/webpack.d.cts +13 -0
  29. package/dist/adapters/webpack.d.ts +11 -0
  30. package/dist/adapters/webpack.js +13 -0
  31. package/dist/browser.cjs +8 -5
  32. package/dist/browser.d.cts +44 -3
  33. package/dist/browser.d.ts +44 -3
  34. package/dist/browser.js +10 -7
  35. package/dist/{chunk-5QD6FZPB.js → chunk-2JU3V7HW.js} +75 -43
  36. package/dist/chunk-3LWXEJU6.cjs +1054 -0
  37. package/dist/chunk-4FNZNIBW.js +7391 -0
  38. package/dist/chunk-7HXLHLLQ.cjs +503 -0
  39. package/dist/chunk-ADKRENAP.js +1054 -0
  40. package/dist/chunk-EN6QVR6P.js +89 -0
  41. package/dist/chunk-HHC7BUCK.js +503 -0
  42. package/dist/chunk-KLYFNMKS.cjs +7391 -0
  43. package/dist/chunk-L6BOM5VS.cjs +40 -0
  44. package/dist/{chunk-OOXSZTRV.js → chunk-LA6J3BT3.js} +26 -1
  45. package/dist/chunk-URPPSTHZ.cjs +89 -0
  46. package/dist/chunk-VG4Y26ZN.cjs +429 -0
  47. package/dist/{chunk-GZB7PFLY.js → chunk-W77DAC3H.js} +46 -64
  48. package/dist/chunk-X6EETCO6.cjs +352 -0
  49. package/dist/chunk-YCRMTXOE.js +429 -0
  50. package/dist/{chunk-GAVI2C44.cjs → chunk-ZG7BIAUI.cjs} +80 -48
  51. package/dist/cli/index.js +9861 -32
  52. package/dist/{types-BBSRUEab.d.cts → config-Y6JwVGwX.d.cts} +58 -86
  53. package/dist/{types-BBSRUEab.d.ts → config-Y6JwVGwX.d.ts} +58 -86
  54. package/dist/config.cjs +4 -16
  55. package/dist/config.d.cts +1 -12
  56. package/dist/config.d.ts +1 -12
  57. package/dist/config.js +5 -17
  58. package/dist/index-0O1WSfVP.d.ts +52 -0
  59. package/dist/index-COVHErnx.d.cts +52 -0
  60. package/dist/index.cjs +437 -9
  61. package/dist/index.d.cts +9 -17
  62. package/dist/index.d.ts +9 -17
  63. package/dist/index.js +438 -10
  64. package/dist/plugins/unplugin.cjs +21 -0
  65. package/dist/plugins/unplugin.d.cts +17 -0
  66. package/dist/plugins/unplugin.d.ts +15 -0
  67. package/dist/{bundler → plugins}/unplugin.js +6 -5
  68. package/dist/types-CMtZnV8C.d.ts +112 -0
  69. package/dist/types-D93PuOOl.d.cts +112 -0
  70. package/package.json +48 -52
  71. package/dist/ast/index.cjs +0 -17
  72. package/dist/ast/index.d.cts +0 -18
  73. package/dist/ast/index.d.ts +0 -18
  74. package/dist/ast/index.js +0 -17
  75. package/dist/bundler/unplugin.cjs +0 -20
  76. package/dist/bundler/unplugin.d.cts +0 -16
  77. package/dist/bundler/unplugin.d.ts +0 -14
  78. package/dist/chunk-24K5NDXH.cjs +0 -370
  79. package/dist/chunk-27HR647Q.js +0 -190
  80. package/dist/chunk-4TDLLEEU.cjs +0 -15
  81. package/dist/chunk-5LCMI2TL.js +0 -575
  82. package/dist/chunk-5M6Z7ZFT.cjs +0 -83
  83. package/dist/chunk-6N6S6WTQ.cjs +0 -423
  84. package/dist/chunk-7YVEHJVM.cjs +0 -575
  85. package/dist/chunk-J5CGNZDM.cjs +0 -190
  86. package/dist/chunk-KQWNFKT2.js +0 -423
  87. package/dist/chunk-LXP73HJC.cjs +0 -4532
  88. package/dist/chunk-R6EBIR3T.cjs +0 -14
  89. package/dist/chunk-S4S2WXGC.js +0 -14
  90. package/dist/chunk-UMPUYLLZ.js +0 -4532
  91. package/dist/chunk-X5MKMFMX.js +0 -83
  92. package/dist/cli/index.cjs +0 -324
  93. package/dist/cli/index.d.cts +0 -22
  94. package/dist/cli/index.d.ts +0 -22
  95. package/dist/esbuild.cjs +0 -15
  96. package/dist/esbuild.d.cts +0 -11
  97. package/dist/esbuild.d.ts +0 -11
  98. package/dist/esbuild.js +0 -13
  99. package/dist/next/adapter.cjs +0 -31
  100. package/dist/next/adapter.js +0 -31
  101. package/dist/next/index.cjs +0 -18
  102. package/dist/next/index.d.cts +0 -42
  103. package/dist/next/index.d.ts +0 -42
  104. package/dist/next/index.js +0 -18
  105. package/dist/rollup.cjs +0 -15
  106. package/dist/rollup.d.cts +0 -11
  107. package/dist/rollup.d.ts +0 -11
  108. package/dist/rollup.js +0 -13
  109. package/dist/runtime/index.cjs +0 -17
  110. package/dist/runtime/index.d.cts +0 -36
  111. package/dist/runtime/index.d.ts +0 -36
  112. package/dist/runtime/index.js +0 -17
  113. package/dist/vite.cjs +0 -15
  114. package/dist/vite.d.cts +0 -11
  115. package/dist/vite.d.ts +0 -11
  116. package/dist/vite.js +0 -13
  117. package/dist/webpack.cjs +0 -15
  118. package/dist/webpack.d.cts +0 -11
  119. package/dist/webpack.d.ts +0 -11
  120. package/dist/webpack.js +0 -13
@@ -1,575 +0,0 @@
1
- import {
2
- loadUnpeekConfig
3
- } from "./chunk-GZB7PFLY.js";
4
- import {
5
- transformJavaScript
6
- } from "./chunk-UMPUYLLZ.js";
7
- import {
8
- computeFnv1aHash,
9
- deriveWindowKeySymbol,
10
- generateRuntimeShield
11
- } from "./chunk-KQWNFKT2.js";
12
- import {
13
- UnpeekError
14
- } from "./chunk-S4S2WXGC.js";
15
-
16
- // src/core/protect.ts
17
- import fs3 from "fs";
18
- import path3 from "path";
19
- import zlib from "zlib";
20
-
21
- // src/bundler/detector.ts
22
- import fs from "fs";
23
- import path from "path";
24
- var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs"]);
25
- var EXCLUDED_DIR_NAMES = /* @__PURE__ */ new Set([
26
- "node_modules",
27
- ".unpeek-maps"
28
- ]);
29
- var NEXT_CONFIG_FILES = ["next.config.ts", "next.config.js", "next.config.mjs", "next.config.cjs"];
30
- var VITE_CONFIG_FILES = ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.cjs"];
31
- function escapeRegex(str) {
32
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
- }
34
- function extractConfigValue(rootDir, filenames, pattern) {
35
- for (const filename of filenames) {
36
- const filePath = path.join(rootDir, filename);
37
- if (fs.existsSync(filePath)) {
38
- try {
39
- const content = fs.readFileSync(filePath, "utf8");
40
- const match = content.match(pattern);
41
- if (match && match[1]) {
42
- return match[1].trim();
43
- }
44
- } catch {
45
- }
46
- }
47
- }
48
- return void 0;
49
- }
50
- function hasNextServerSegment(fullPath, rootDir, serverDirPrefixes) {
51
- const normalized = fullPath.replace(/\\/g, "/");
52
- if (normalized.includes("/node_modules/") || normalized.endsWith("/node_modules") || normalized.includes("/.unpeek-maps/") || normalized.endsWith("/.unpeek-maps")) {
53
- return true;
54
- }
55
- if (/(?:^|\/)\.next\/(?:server|ssr)(?:\/|$)/i.test(normalized)) {
56
- return true;
57
- }
58
- if (serverDirPrefixes && serverDirPrefixes.length > 0) {
59
- for (const prefix of serverDirPrefixes) {
60
- const normPrefix = prefix.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
61
- if (normPrefix) {
62
- const regex = new RegExp(`(?:^|\\/)${escapeRegex(normPrefix)}(?:\\/|$)`, "i");
63
- if (regex.test(normalized)) {
64
- return true;
65
- }
66
- }
67
- }
68
- }
69
- if (rootDir) {
70
- const rel = path.relative(rootDir, fullPath).replace(/\\/g, "/");
71
- const segments = rel.split("/").filter(Boolean);
72
- if (segments.length > 0 && (segments[0].toLowerCase() === "server" || segments[0].toLowerCase() === "ssr")) {
73
- return true;
74
- }
75
- }
76
- return false;
77
- }
78
- function detectTargetFramework(cwd, explicitOutDir, explicitConfig) {
79
- let config = explicitConfig;
80
- let outDirOverride;
81
- if (typeof explicitOutDir === "object" && explicitOutDir !== null) {
82
- config = explicitOutDir;
83
- outDirOverride = config.outDir;
84
- } else if (typeof explicitOutDir === "string") {
85
- outDirOverride = explicitOutDir;
86
- }
87
- const rootDir = path.resolve(cwd);
88
- let framework = config?.framework;
89
- const discoveredNextDist = extractConfigValue(
90
- rootDir,
91
- NEXT_CONFIG_FILES,
92
- /(?:["']?distDir["']?\s*:\s*["']([^"']+)["'])/
93
- );
94
- const discoveredViteOut = extractConfigValue(
95
- rootDir,
96
- VITE_CONFIG_FILES,
97
- /(?:["']?outDir["']?\s*:\s*["']([^"']+)["'])/
98
- );
99
- const discoveredViteAssets = extractConfigValue(
100
- rootDir,
101
- VITE_CONFIG_FILES,
102
- /(?:["']?assetsDir["']?\s*:\s*["']([^"']+)["'])/
103
- );
104
- const nextDist = config?.next?.distDir ?? discoveredNextDist ?? ".next";
105
- const viteOut = config?.vite?.outDir ?? discoveredViteOut ?? "dist";
106
- const viteAssets = config?.vite?.assetsDir ?? discoveredViteAssets ?? "assets";
107
- if (!framework) {
108
- const pkgPath = path.join(rootDir, "package.json");
109
- if (fs.existsSync(pkgPath)) {
110
- try {
111
- const pkgRaw = fs.readFileSync(pkgPath, "utf8");
112
- const pkg = JSON.parse(pkgRaw);
113
- const allDeps = {
114
- ...pkg.dependencies ?? {},
115
- ...pkg.devDependencies ?? {}
116
- };
117
- if ("next" in allDeps) {
118
- framework = "nextjs";
119
- } else if ("vite" in allDeps) {
120
- framework = "vite";
121
- } else if ("webpack" in allDeps || "react-scripts" in allDeps || "@rspack/core" in allDeps) {
122
- framework = "webpack";
123
- }
124
- } catch {
125
- }
126
- }
127
- }
128
- const nextChunksDir = path.join(rootDir, nextDist, "static", "chunks");
129
- const nextExportChunksDir = path.join(rootDir, "out", "_next", "static", "chunks");
130
- const nextExportDir = path.join(rootDir, "out");
131
- const nextDistDir = path.join(rootDir, nextDist);
132
- const distAssetsDir = path.join(rootDir, viteOut, viteAssets);
133
- const distDir = path.join(rootDir, viteOut);
134
- const buildDir = path.join(rootDir, "build");
135
- const publicDir = path.join(rootDir, "public");
136
- if (!framework) {
137
- if (fs.existsSync(nextChunksDir) || fs.existsSync(nextDistDir) || fs.existsSync(nextExportChunksDir) || discoveredNextDist !== void 0) {
138
- framework = "nextjs";
139
- } else if (fs.existsSync(distAssetsDir) || discoveredViteOut !== void 0) {
140
- framework = "vite";
141
- } else if (fs.existsSync(buildDir)) {
142
- framework = "webpack";
143
- } else if (outDirOverride) {
144
- const normExplicit = outDirOverride.replace(/\\/g, "/");
145
- if (normExplicit.includes(nextDist) || normExplicit.includes(".next") || normExplicit.includes("out/_next")) {
146
- framework = "nextjs";
147
- } else if (normExplicit.includes(`${viteOut}/${viteAssets}`) || normExplicit.includes("dist/assets")) {
148
- framework = "vite";
149
- } else if (normExplicit.includes("build")) {
150
- framework = "webpack";
151
- } else {
152
- framework = "vanilla";
153
- }
154
- } else {
155
- framework = "vanilla";
156
- }
157
- }
158
- if (outDirOverride) {
159
- return {
160
- framework,
161
- outDir: path.resolve(rootDir, outDirOverride)
162
- };
163
- }
164
- let outDir;
165
- if (framework === "nextjs") {
166
- if (fs.existsSync(nextExportChunksDir)) {
167
- outDir = nextExportChunksDir;
168
- } else if (fs.existsSync(nextChunksDir)) {
169
- outDir = nextChunksDir;
170
- } else if (fs.existsSync(nextExportDir)) {
171
- outDir = nextExportDir;
172
- } else if (fs.existsSync(nextDistDir)) {
173
- outDir = nextChunksDir;
174
- } else {
175
- outDir = nextChunksDir;
176
- }
177
- } else if (framework === "vite") {
178
- outDir = fs.existsSync(distAssetsDir) ? distAssetsDir : distDir;
179
- } else if (framework === "webpack") {
180
- if (fs.existsSync(distDir)) {
181
- outDir = distDir;
182
- } else if (fs.existsSync(buildDir)) {
183
- outDir = buildDir;
184
- } else {
185
- outDir = distDir;
186
- }
187
- } else {
188
- const candidates = [nextExportChunksDir, nextChunksDir, distAssetsDir, distDir, buildDir, publicDir];
189
- const existing = candidates.find((candidate) => fs.existsSync(candidate));
190
- outDir = existing ?? distDir;
191
- }
192
- return { framework, outDir };
193
- }
194
- function scanClientBundles(outDir, config) {
195
- const resolvedOutDir = path.resolve(outDir);
196
- if (!fs.existsSync(resolvedOutDir)) {
197
- return [];
198
- }
199
- const results = [];
200
- const serverDirPrefixes = [];
201
- if (config?.next?.distDir) {
202
- serverDirPrefixes.push(
203
- path.join(config.next.distDir, "server"),
204
- path.join(config.next.distDir, "ssr")
205
- );
206
- }
207
- if (config?.vite?.outDir) {
208
- serverDirPrefixes.push(path.join(config.vite.outDir, "server"));
209
- }
210
- const allowedExtensions = config?.extensions && config.extensions.length > 0 ? new Set(config.extensions.map((e) => e.startsWith(".") ? e.toLowerCase() : `.${e.toLowerCase()}`)) : SUPPORTED_EXTENSIONS;
211
- function walk(currentDir) {
212
- if (hasNextServerSegment(currentDir, resolvedOutDir, serverDirPrefixes)) {
213
- return;
214
- }
215
- let entries;
216
- try {
217
- entries = fs.readdirSync(currentDir, { withFileTypes: true });
218
- } catch {
219
- return;
220
- }
221
- for (const entry of entries) {
222
- const fullPath = path.join(currentDir, entry.name);
223
- if (entry.isDirectory()) {
224
- if (EXCLUDED_DIR_NAMES.has(entry.name.toLowerCase())) {
225
- continue;
226
- }
227
- if (hasNextServerSegment(fullPath, resolvedOutDir, serverDirPrefixes)) {
228
- continue;
229
- }
230
- walk(fullPath);
231
- } else if (entry.isFile()) {
232
- if (hasNextServerSegment(fullPath, resolvedOutDir, serverDirPrefixes)) {
233
- continue;
234
- }
235
- const ext = path.extname(entry.name).toLowerCase();
236
- if (allowedExtensions.has(ext)) {
237
- results.push(fullPath);
238
- }
239
- }
240
- }
241
- }
242
- walk(resolvedOutDir);
243
- return results.sort();
244
- }
245
-
246
- // src/bundler/sourcemap-vault.ts
247
- import fs2 from "fs";
248
- import path2 from "path";
249
- var SOURCE_MAP_COMMENT_REGEX = /(?:^\s*\/\/[#@]\s*sourceMappingURL=.*$|\/\*[#@]\s*sourceMappingURL=[\s\S]*?\*\/)\s*/gm;
250
- function ensureIgnoreEntry(dir, fileName, entryName) {
251
- const filePath = path2.join(path2.resolve(dir), fileName);
252
- if (!fs2.existsSync(filePath)) {
253
- return;
254
- }
255
- const content = fs2.readFileSync(filePath, "utf8");
256
- const normalizedEntry = entryName.endsWith("/") ? entryName : `${entryName}/`;
257
- const bareEntry = normalizedEntry.slice(0, -1);
258
- const lines = content.split(/\r?\n/).map((line) => line.trim());
259
- if (!lines.includes(normalizedEntry) && !lines.includes(bareEntry) && !lines.includes(".unpeek-maps") && !lines.includes(".unpeek-maps/")) {
260
- const prefix = content.length > 0 && !content.endsWith("\n") ? "\n" : "";
261
- fs2.writeFileSync(filePath, `${content}${prefix}${normalizedEntry}
262
- `, "utf8");
263
- }
264
- }
265
- function isSubdirectoryOrSame(parent, child) {
266
- const rel = path2.relative(parent, child);
267
- return rel === "" || !rel.startsWith("..") && !path2.isAbsolute(rel);
268
- }
269
- function findMonorepoRoots(cwd) {
270
- const resolved = path2.resolve(cwd);
271
- const dirs = [resolved];
272
- let curr = resolved;
273
- while (true) {
274
- const parent = path2.dirname(curr);
275
- if (!parent || parent === curr) {
276
- break;
277
- }
278
- const hasGit = fs2.existsSync(path2.join(parent, ".git"));
279
- const hasWorkspace = fs2.existsSync(path2.join(parent, "pnpm-workspace.yaml"));
280
- const hasGitIgnore = fs2.existsSync(path2.join(parent, ".gitignore"));
281
- const hasDockerIgnore = fs2.existsSync(path2.join(parent, ".dockerignore"));
282
- const hasPkgJson = fs2.existsSync(path2.join(parent, "package.json"));
283
- if (hasGit || hasWorkspace || hasGitIgnore || hasDockerIgnore || hasPkgJson) {
284
- dirs.push(parent);
285
- }
286
- if (hasGit || hasWorkspace) {
287
- break;
288
- }
289
- curr = parent;
290
- }
291
- return dirs;
292
- }
293
- function checkDockerIgnoreMissing(cwd, ignoreEntry) {
294
- const candidateDirs = findMonorepoRoots(cwd);
295
- let foundAnyDockerIgnore = false;
296
- for (const dir of candidateDirs) {
297
- const filePath = path2.join(dir, ".dockerignore");
298
- if (fs2.existsSync(filePath)) {
299
- foundAnyDockerIgnore = true;
300
- const content = fs2.readFileSync(filePath, "utf8");
301
- const normalizedEntry = ignoreEntry.endsWith("/") ? ignoreEntry : `${ignoreEntry}/`;
302
- const bareEntry = normalizedEntry.slice(0, -1);
303
- const lines = content.split(/\r?\n/).map((line) => line.trim());
304
- if (lines.includes(normalizedEntry) || lines.includes(bareEntry) || lines.includes(".unpeek-maps") || lines.includes(".unpeek-maps/")) {
305
- return false;
306
- }
307
- }
308
- }
309
- return true;
310
- }
311
- function updateAllIgnoreFiles(cwd, vaultDir) {
312
- const candidateDirs = findMonorepoRoots(cwd);
313
- for (const dir of candidateDirs) {
314
- const relFromDir = path2.relative(dir, vaultDir).replace(/\\/g, "/");
315
- const entry = relFromDir && !relFromDir.startsWith("..") ? `${relFromDir}/` : ".unpeek-maps/";
316
- ensureIgnoreEntry(dir, ".gitignore", entry);
317
- ensureIgnoreEntry(dir, ".dockerignore", entry);
318
- ensureIgnoreEntry(dir, ".npmignore", entry);
319
- }
320
- }
321
- function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir = ".unpeek-maps", stripComments = true, config, options) {
322
- const resolvedOutDir = path2.resolve(outDir);
323
- const resolvedCwd = path2.resolve(cwd);
324
- const effectiveVaultDirName = config?.sourcemaps?.vaultDir ?? privateMapsDir ?? ".unpeek-maps";
325
- const effectiveKeepPrivate = config?.sourcemaps?.keepPrivate ?? keepPrivateMaps;
326
- const effectiveStripComments = config?.sourcemaps?.stripComments ?? stripComments;
327
- const updateIgnoreFiles = typeof options === "boolean" ? options : options?.updateIgnoreFiles ?? true;
328
- const vaultDir = path2.resolve(resolvedCwd, effectiveVaultDirName);
329
- const publicDirsToCheck = /* @__PURE__ */ new Set();
330
- if (config?.publicDirs && config.publicDirs.length > 0) {
331
- for (const d of config.publicDirs) {
332
- publicDirsToCheck.add(d);
333
- }
334
- } else {
335
- publicDirsToCheck.add("public");
336
- publicDirsToCheck.add("static");
337
- publicDirsToCheck.add("assets");
338
- }
339
- if (effectiveKeepPrivate !== false) {
340
- if (!isSubdirectoryOrSame(resolvedCwd, vaultDir)) {
341
- throw new UnpeekError(
342
- "ERR_SECURITY_PATH_TRAVERSAL",
343
- `[unpeek] Security Error: privateMapsDir (${vaultDir}) cannot traverse outside cwd (${resolvedCwd}).`
344
- );
345
- }
346
- if (isSubdirectoryOrSame(resolvedOutDir, vaultDir)) {
347
- throw new Error(
348
- `[unpeek] Security Error: privateMapsDir cannot be located inside outDir (${resolvedOutDir}). This would expose private source maps to the web server.`
349
- );
350
- }
351
- for (const pubDir of publicDirsToCheck) {
352
- const resolvedPublicDir = path2.resolve(resolvedCwd, pubDir);
353
- if (isSubdirectoryOrSame(resolvedPublicDir, vaultDir)) {
354
- throw new Error(
355
- `[unpeek] Security Error: privateMapsDir cannot be located inside publicDir (${resolvedPublicDir}). This would expose private source maps to the web server.`
356
- );
357
- }
358
- }
359
- }
360
- const relVault = path2.relative(resolvedCwd, vaultDir).replace(/\\/g, "/");
361
- const ignoreEntry = relVault && !relVault.startsWith("..") ? `${relVault}/` : ".unpeek-maps/";
362
- const dockerIgnoreMissing = checkDockerIgnoreMissing(resolvedCwd, ignoreEntry);
363
- const movedFiles = [];
364
- let movedMapsCount = 0;
365
- let strippedFilesCount = 0;
366
- if (!fs2.existsSync(resolvedOutDir)) {
367
- return {
368
- movedMapsCount: 0,
369
- strippedFilesCount: 0,
370
- vaultDir,
371
- movedFiles: [],
372
- dockerIgnoreMissing
373
- };
374
- }
375
- function walkForMaps(currentDir) {
376
- if (hasNextServerSegment(currentDir, resolvedOutDir)) {
377
- return;
378
- }
379
- let entries;
380
- try {
381
- entries = fs2.readdirSync(currentDir, { withFileTypes: true });
382
- } catch {
383
- return;
384
- }
385
- for (const entry of entries) {
386
- const fullPath = path2.join(currentDir, entry.name);
387
- if (entry.isDirectory()) {
388
- if (entry.name === "node_modules" || entry.name === ".unpeek-maps") {
389
- continue;
390
- }
391
- if (hasNextServerSegment(fullPath, resolvedOutDir)) {
392
- continue;
393
- }
394
- walkForMaps(fullPath);
395
- } else if (entry.isFile() && entry.name.endsWith(".map")) {
396
- if (effectiveKeepPrivate !== false) {
397
- const relPath = path2.relative(resolvedOutDir, fullPath);
398
- const targetPath = path2.join(vaultDir, relPath);
399
- fs2.mkdirSync(path2.dirname(targetPath), { recursive: true });
400
- fs2.copyFileSync(fullPath, targetPath);
401
- fs2.unlinkSync(fullPath);
402
- movedFiles.push(targetPath);
403
- } else {
404
- fs2.unlinkSync(fullPath);
405
- }
406
- movedMapsCount++;
407
- }
408
- }
409
- }
410
- walkForMaps(resolvedOutDir);
411
- if (updateIgnoreFiles && effectiveKeepPrivate !== false && movedMapsCount > 0) {
412
- updateAllIgnoreFiles(resolvedCwd, vaultDir);
413
- }
414
- if (effectiveStripComments) {
415
- const clientFiles = scanClientBundles(resolvedOutDir, config);
416
- for (const filePath of clientFiles) {
417
- const original = fs2.readFileSync(filePath, "utf8");
418
- if (original.includes("sourceMappingURL=")) {
419
- const stripped = original.replace(SOURCE_MAP_COMMENT_REGEX, "");
420
- if (stripped !== original) {
421
- fs2.writeFileSync(filePath, stripped, "utf8");
422
- strippedFilesCount++;
423
- }
424
- }
425
- }
426
- }
427
- return {
428
- movedMapsCount,
429
- strippedFilesCount,
430
- vaultDir,
431
- movedFiles,
432
- dockerIgnoreMissing
433
- };
434
- }
435
-
436
- // src/core/protect.ts
437
- var ENTRY_PATTERN = /^(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
438
- function isEntryChunk(relPath, index, allRelPaths) {
439
- const norm = relPath.replace(/\\/g, "/");
440
- const base = path3.basename(norm);
441
- if (ENTRY_PATTERN.test(norm) || ENTRY_PATTERN.test(base)) {
442
- return true;
443
- }
444
- const hasAnyPatternMatch = allRelPaths.some((p) => {
445
- const n = p.replace(/\\/g, "/");
446
- return ENTRY_PATTERN.test(n) || ENTRY_PATTERN.test(path3.basename(n));
447
- });
448
- if (!hasAnyPatternMatch && index === 0) {
449
- return true;
450
- }
451
- return false;
452
- }
453
- async function protectProject(options = {}) {
454
- const startTime = performance.now();
455
- const cwd = path3.resolve(options.cwd ?? process.cwd());
456
- const config = await loadUnpeekConfig(cwd, options.config);
457
- const { framework, outDir } = detectTargetFramework(cwd, options.outDir, config);
458
- const seed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 1597463007;
459
- const keepPrivateMaps = options.keepPrivateMaps ?? config.sourcemaps?.keepPrivate ?? true;
460
- const privateMapsDir = options.privateMapsDir ?? config.sourcemaps?.vaultDir ?? ".unpeek-maps";
461
- const deterrentMode = options.deterrentMode ?? config.shield?.deterrentMode ?? "passive";
462
- const detectHeadless = options.detectHeadless ?? config.shield?.detectHeadless ?? false;
463
- const injectRuntimeShield = options.injectRuntimeShield ?? true;
464
- const minStringLength = options.minStringLength ?? config.vault?.minStringLength ?? 4;
465
- const aggressive = options.aggressive ?? false;
466
- const masterSym = deriveWindowKeySymbol(seed);
467
- const masterShield = injectRuntimeShield ? generateRuntimeShield({
468
- seed,
469
- deterrentMode,
470
- detectHeadless,
471
- windowKeySymbol: masterSym
472
- }) : void 0;
473
- const vaultResult = relocateSourceMaps(outDir, cwd, keepPrivateMaps, privateMapsDir, false, config);
474
- const clientFiles = scanClientBundles(outDir, config);
475
- const allRelPaths = clientFiles.map((f) => path3.relative(outDir, f).replace(/\\/g, "/"));
476
- let originalBytes = 0;
477
- let protectedBytes = 0;
478
- let totalHotFunctionsSkipped = 0;
479
- let totalColdFunctionsProtected = 0;
480
- let totalEncryptedStrings = 0;
481
- let totalMangledSymbols = 0;
482
- let processedFiles = 0;
483
- const allOrigBufs = [];
484
- const allProtBufs = [];
485
- const stagedFiles = [];
486
- try {
487
- for (let i = 0; i < clientFiles.length; i++) {
488
- const filePath = clientFiles[i];
489
- let codeToTransform = fs3.readFileSync(filePath, "utf8");
490
- if (codeToTransform.includes("sourceMappingURL=")) {
491
- codeToTransform = codeToTransform.replace(SOURCE_MAP_COMMENT_REGEX, "");
492
- vaultResult.strippedFilesCount++;
493
- }
494
- const origBuf = Buffer.from(codeToTransform, "utf8");
495
- originalBytes += origBuf.byteLength;
496
- allOrigBufs.push(origBuf);
497
- const relPath = allRelPaths[i];
498
- const isEntry = isEntryChunk(relPath, i, allRelPaths);
499
- const shouldInjectShield = injectRuntimeShield && isEntry;
500
- const fileSeed = computeFnv1aHash(`${relPath}:${i}`, seed);
501
- const transformOptions = {
502
- seed: fileSeed,
503
- minStringLength,
504
- filename: path3.basename(filePath),
505
- injectRuntimeShield: shouldInjectShield,
506
- skipShieldPreamble: true,
507
- shieldCoupled: injectRuntimeShield,
508
- windowKeySymbol: masterSym,
509
- expectedDelta: masterShield?.expectedDelta,
510
- deterrentMode,
511
- detectHeadless,
512
- aggressive,
513
- config
514
- };
515
- const result = transformJavaScript(codeToTransform, transformOptions);
516
- let finalCode = result.code;
517
- if (shouldInjectShield && masterShield?.preambleCode && !finalCode.includes("__unpeek_tampered") && !finalCode.includes(masterShield.integrityCheckFnName) && !finalCode.startsWith(masterShield.preambleCode)) {
518
- finalCode = `${masterShield.preambleCode}
519
- ${finalCode}`;
520
- }
521
- const tmpPath = `${filePath}.unpeek.tmp`;
522
- fs3.writeFileSync(tmpPath, finalCode, "utf8");
523
- stagedFiles.push({ tmpPath, finalPath: filePath });
524
- const protBuf = Buffer.from(finalCode, "utf8");
525
- protectedBytes += protBuf.byteLength;
526
- allProtBufs.push(protBuf);
527
- totalHotFunctionsSkipped += result.hotPathReport.hotFunctionsSkipped.length;
528
- totalColdFunctionsProtected += result.hotPathReport.coldFunctionsProtected.length;
529
- totalEncryptedStrings += result.encryptedStringsCount;
530
- totalMangledSymbols += result.mangledSymbolsCount;
531
- processedFiles++;
532
- }
533
- for (const { tmpPath, finalPath } of stagedFiles) {
534
- fs3.renameSync(tmpPath, finalPath);
535
- }
536
- } catch (error) {
537
- for (const { tmpPath } of stagedFiles) {
538
- if (fs3.existsSync(tmpPath)) {
539
- try {
540
- fs3.unlinkSync(tmpPath);
541
- } catch {
542
- }
543
- }
544
- }
545
- throw error;
546
- }
547
- const originalGzipBytes = allOrigBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allOrigBufs)).byteLength : 0;
548
- const protectedGzipBytes = allProtBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allProtBufs)).byteLength : 0;
549
- const gzipDeltaPercent = originalGzipBytes > 0 ? Number(((protectedGzipBytes - originalGzipBytes) / originalGzipBytes * 100).toFixed(2)) : 0;
550
- const elapsedMs = Math.max(1, Math.round(performance.now() - startTime));
551
- return {
552
- framework,
553
- outDir,
554
- processedFiles,
555
- movedSourceMaps: vaultResult.movedMapsCount,
556
- originalBytes,
557
- protectedBytes,
558
- originalGzipBytes,
559
- protectedGzipBytes,
560
- gzipDeltaPercent,
561
- totalHotFunctionsSkipped,
562
- totalColdFunctionsProtected,
563
- totalEncryptedStrings,
564
- totalMangledSymbols,
565
- elapsedMs,
566
- tier: aggressive ? "Tier 2" : "Tier 1",
567
- aggressive,
568
- dockerIgnoreMissing: vaultResult.dockerIgnoreMissing
569
- };
570
- }
571
-
572
- export {
573
- detectTargetFramework,
574
- protectProject
575
- };
@@ -1,83 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
- var _chunkLXP73HJCcjs = require('./chunk-LXP73HJC.cjs');
4
-
5
-
6
-
7
-
8
- var _chunk6N6S6WTQcjs = require('./chunk-6N6S6WTQ.cjs');
9
-
10
- // src/bundler/unplugin.ts
11
- var _unplugin = require('unplugin');
12
- var ENTRY_CHUNK_PATTERN = /(?:^|\/)(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
13
- var unpeekPlugin = _unplugin.createUnplugin.call(void 0, (options = {}) => {
14
- const config = _nullishCoalesce(options.config, () => ( ("framework" in options || "target" in options || "vault" in options || "hotPath" in options || "mangler" in options || "shield" in options || "sourcemaps" in options ? options : void 0)));
15
- const baseSeed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 322420463;
16
- const deterrentMode = _nullishCoalesce(_nullishCoalesce(options.deterrentMode, () => ( _optionalChain([config, 'optionalAccess', _ => _.shield, 'optionalAccess', _2 => _2.deterrentMode]))), () => ( "passive"));
17
- const detectHeadless = _nullishCoalesce(_nullishCoalesce(options.detectHeadless, () => ( _optionalChain([config, 'optionalAccess', _3 => _3.shield, 'optionalAccess', _4 => _4.detectHeadless]))), () => ( false));
18
- const injectRuntimeShield = _nullishCoalesce(options.injectRuntimeShield, () => ( true));
19
- const minStringLength = _nullishCoalesce(_nullishCoalesce(options.minStringLength, () => ( _optionalChain([config, 'optionalAccess', _5 => _5.vault, 'optionalAccess', _6 => _6.minStringLength]))), () => ( 4));
20
- const aggressive = _nullishCoalesce(options.aggressive, () => ( false));
21
- const masterSym = _chunk6N6S6WTQcjs.deriveWindowKeySymbol.call(void 0, baseSeed);
22
- const masterShield = injectRuntimeShield ? _chunk6N6S6WTQcjs.generateRuntimeShield.call(void 0, {
23
- seed: baseSeed,
24
- deterrentMode,
25
- detectHeadless,
26
- windowKeySymbol: masterSym
27
- }) : void 0;
28
- return {
29
- name: "unpeek",
30
- enforce: "post",
31
- renderChunk(code, chunk) {
32
- const normalizedFileName = chunk.fileName.replace(/\\/g, "/");
33
- if (!normalizedFileName.endsWith(".js") && !normalizedFileName.endsWith(".mjs") && !normalizedFileName.endsWith(".cjs")) {
34
- return null;
35
- }
36
- if (normalizedFileName.includes("server/") || normalizedFileName.includes("ssr/") || normalizedFileName.includes("node_modules/")) {
37
- return null;
38
- }
39
- const isEntry = chunk.isEntry !== void 0 ? chunk.isEntry : ENTRY_CHUNK_PATTERN.test(normalizedFileName);
40
- const shouldInjectShield = injectRuntimeShield && isEntry;
41
- const chunkSeed = _chunk6N6S6WTQcjs.computeFnv1aHash.call(void 0, chunk.fileName, baseSeed);
42
- const transformOptions = {
43
- seed: chunkSeed,
44
- minStringLength,
45
- filename: chunk.fileName,
46
- injectRuntimeShield: shouldInjectShield,
47
- skipShieldPreamble: true,
48
- shieldCoupled: injectRuntimeShield,
49
- windowKeySymbol: masterSym,
50
- expectedDelta: _optionalChain([masterShield, 'optionalAccess', _7 => _7.expectedDelta]),
51
- deterrentMode,
52
- detectHeadless,
53
- aggressive,
54
- config
55
- };
56
- const result = _chunkLXP73HJCcjs.transformJavaScript.call(void 0, code, transformOptions);
57
- let finalCode = result.code;
58
- const integrityCheckFnName = masterShield && "integrityCheckFnName" in masterShield ? masterShield.integrityCheckFnName : void 0;
59
- if (shouldInjectShield && _optionalChain([masterShield, 'optionalAccess', _8 => _8.preambleCode]) && !finalCode.includes("__unpeek_tampered") && !finalCode.includes("(function _u$") && (!integrityCheckFnName || !finalCode.includes(integrityCheckFnName)) && !finalCode.startsWith(masterShield.preambleCode)) {
60
- finalCode = `${masterShield.preambleCode}
61
- ${finalCode}`;
62
- }
63
- return {
64
- code: finalCode,
65
- map: null
66
- };
67
- }
68
- };
69
- });
70
- var vitePlugin = unpeekPlugin.vite;
71
- var webpackPlugin = unpeekPlugin.webpack;
72
- var rollupPlugin = unpeekPlugin.rollup;
73
- var esbuildPlugin = unpeekPlugin.esbuild;
74
- var unplugin_default = unpeekPlugin;
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
- exports.unpeekPlugin = unpeekPlugin; exports.vitePlugin = vitePlugin; exports.webpackPlugin = webpackPlugin; exports.rollupPlugin = rollupPlugin; exports.esbuildPlugin = esbuildPlugin; exports.unplugin_default = unplugin_default;