unpeek 1.0.1 → 1.2.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 (102) hide show
  1. package/README.md +131 -60
  2. package/README.tr.md +317 -0
  3. package/dist/ast/index.cjs +802 -0
  4. package/dist/ast/index.cjs.map +1 -0
  5. package/dist/ast/index.d.cts +9 -0
  6. package/dist/ast/index.d.ts +9 -4
  7. package/dist/ast/index.js +762 -52
  8. package/dist/ast/index.js.map +1 -0
  9. package/dist/browser.cjs +816 -0
  10. package/dist/browser.cjs.map +1 -0
  11. package/dist/browser.d.cts +3 -0
  12. package/dist/browser.d.ts +3 -0
  13. package/dist/browser.js +773 -0
  14. package/dist/browser.js.map +1 -0
  15. package/dist/bundler/detector.cjs +180 -0
  16. package/dist/bundler/detector.cjs.map +1 -0
  17. package/dist/bundler/detector.d.cts +9 -0
  18. package/dist/bundler/detector.d.ts +6 -3
  19. package/dist/bundler/detector.js +130 -135
  20. package/dist/bundler/detector.js.map +1 -0
  21. package/dist/bundler/sourcemap-vault.cjs +210 -0
  22. package/dist/bundler/sourcemap-vault.cjs.map +1 -0
  23. package/dist/bundler/sourcemap-vault.d.cts +6 -0
  24. package/dist/bundler/sourcemap-vault.d.ts +6 -2
  25. package/dist/bundler/sourcemap-vault.js +161 -85
  26. package/dist/bundler/sourcemap-vault.js.map +1 -0
  27. package/dist/bundler/unplugin.cjs +848 -0
  28. package/dist/bundler/unplugin.cjs.map +1 -0
  29. package/dist/bundler/unplugin.d.cts +14 -0
  30. package/dist/bundler/unplugin.d.ts +14 -7
  31. package/dist/bundler/unplugin.js +805 -51
  32. package/dist/bundler/unplugin.js.map +1 -0
  33. package/dist/cli/index.cjs +1361 -0
  34. package/dist/cli/index.cjs.map +1 -0
  35. package/dist/cli/index.d.cts +3 -0
  36. package/dist/cli/index.d.ts +3 -1
  37. package/dist/cli/index.js +1309 -94
  38. package/dist/cli/index.js.map +1 -0
  39. package/dist/cli/init.cjs +200 -0
  40. package/dist/cli/init.cjs.map +1 -0
  41. package/dist/cli/init.d.cts +13 -0
  42. package/dist/cli/init.d.ts +10 -2
  43. package/dist/cli/init.js +162 -46
  44. package/dist/cli/init.js.map +1 -0
  45. package/dist/cli/protect.cjs +1147 -0
  46. package/dist/cli/protect.cjs.map +1 -0
  47. package/dist/cli/protect.d.cts +5 -0
  48. package/dist/cli/protect.d.ts +5 -2
  49. package/dist/cli/protect.js +1107 -83
  50. package/dist/cli/protect.js.map +1 -0
  51. package/dist/esbuild.cjs +844 -0
  52. package/dist/esbuild.cjs.map +1 -0
  53. package/dist/esbuild.d.cts +11 -0
  54. package/dist/esbuild.d.ts +11 -0
  55. package/dist/esbuild.js +807 -0
  56. package/dist/esbuild.js.map +1 -0
  57. package/dist/index.cjs +1453 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.cts +14 -0
  60. package/dist/index.d.ts +9 -4
  61. package/dist/index.js +1395 -8
  62. package/dist/index.js.map +1 -0
  63. package/dist/rollup.cjs +844 -0
  64. package/dist/rollup.cjs.map +1 -0
  65. package/dist/rollup.d.cts +11 -0
  66. package/dist/rollup.d.ts +11 -0
  67. package/dist/rollup.js +807 -0
  68. package/dist/rollup.js.map +1 -0
  69. package/dist/runtime/index.cjs +88 -0
  70. package/dist/runtime/index.cjs.map +1 -0
  71. package/dist/runtime/index.d.cts +23 -0
  72. package/dist/runtime/index.d.ts +23 -4
  73. package/dist/runtime/index.js +57 -15
  74. package/dist/runtime/index.js.map +1 -0
  75. package/dist/{types.d.ts → types-BTMkXmVE.d.cts} +14 -12
  76. package/dist/types-BTMkXmVE.d.ts +73 -0
  77. package/dist/vite.cjs +844 -0
  78. package/dist/vite.cjs.map +1 -0
  79. package/dist/vite.d.cts +11 -0
  80. package/dist/vite.d.ts +11 -0
  81. package/dist/vite.js +807 -0
  82. package/dist/vite.js.map +1 -0
  83. package/dist/webpack.cjs +844 -0
  84. package/dist/webpack.cjs.map +1 -0
  85. package/dist/webpack.d.cts +11 -0
  86. package/dist/webpack.d.ts +11 -0
  87. package/dist/webpack.js +807 -0
  88. package/dist/webpack.js.map +1 -0
  89. package/package.json +104 -7
  90. package/dist/ast/cold-flow-guard.d.ts +0 -2
  91. package/dist/ast/cold-flow-guard.js +0 -39
  92. package/dist/ast/hot-path-detector.d.ts +0 -10
  93. package/dist/ast/hot-path-detector.js +0 -235
  94. package/dist/ast/polymorphic-mangler.d.ts +0 -2
  95. package/dist/ast/polymorphic-mangler.js +0 -270
  96. package/dist/ast/string-vault.d.ts +0 -7
  97. package/dist/ast/string-vault.js +0 -139
  98. package/dist/runtime/devtools-deterrent.d.ts +0 -7
  99. package/dist/runtime/devtools-deterrent.js +0 -27
  100. package/dist/runtime/integrity-guard.d.ts +0 -11
  101. package/dist/runtime/integrity-guard.js +0 -25
  102. package/dist/types.js +0 -1
package/dist/ast/index.js CHANGED
@@ -1,55 +1,765 @@
1
- import { generate } from 'astring';
2
- import { analyzeAstHotPaths, parseJavaScriptAst, } from './hot-path-detector.js';
3
- import { applyStringVault, computeFnv1aHash } from './string-vault.js';
4
- import { applyPolymorphicMangler } from './polymorphic-mangler.js';
5
- import { applyColdFlowGuard } from './cold-flow-guard.js';
6
- export { detectHotPaths } from './hot-path-detector.js';
7
- export { computeFnv1aHash } from './string-vault.js';
8
- export function transformJavaScript(code, options = {}) {
9
- const seed = options.seed ?? 0x9e3779b9;
10
- const minStringLength = options.minStringLength ?? 4;
11
- if (!code || !code.trim()) {
12
- return {
13
- code,
14
- encryptedStringsCount: 0,
15
- mangledSymbolsCount: 0,
16
- hotPathReport: {
17
- totalFunctions: 0,
18
- hotFunctionsSkipped: [],
19
- coldFunctionsProtected: [],
20
- },
21
- integrityToken: computeFnv1aHash('', seed),
22
- };
23
- }
24
- const ast = parseJavaScriptAst(code);
25
- if (!ast) {
26
- return {
27
- code,
28
- encryptedStringsCount: 0,
29
- mangledSymbolsCount: 0,
30
- hotPathReport: {
31
- totalFunctions: 0,
32
- hotFunctionsSkipped: [],
33
- coldFunctionsProtected: [],
34
- },
35
- integrityToken: computeFnv1aHash(code, seed),
36
- };
37
- }
38
- // 1. Detect hot paths (loops, array HOF callbacks, rAF, UI components)
39
- const { report: hotPathReport, coldFunctionNodes } = analyzeAstHotPaths(ast);
40
- // 2. Inject polymorphic opaque guards only on cold functions (<2% runtime CPU budget)
41
- applyColdFlowGuard(ast, coldFunctionNodes, seed);
42
- // 3. Mangle local parameters & function-scoped variables safely
43
- const mangledSymbolsCount = applyPolymorphicMangler(ast, seed);
44
- // 4. Encrypt eligible string literals into an O(1) lazy inline-cached vault
45
- const { encryptedStringsCount, integrityToken } = applyStringVault(ast, seed, minStringLength);
46
- // 5. Generate compact single-line JavaScript output
47
- const outputCode = generate(ast, { indent: '', lineEnd: '' });
1
+ // src/ast/index.ts
2
+ import { generate } from "astring";
3
+
4
+ // src/ast/hot-path-detector.ts
5
+ import * as acorn from "acorn";
6
+ import * as walk from "acorn-walk";
7
+ var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
8
+ "map",
9
+ "filter",
10
+ "reduce",
11
+ "forEach",
12
+ "flatMap",
13
+ "find",
14
+ "some",
15
+ "every"
16
+ ]);
17
+ var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
18
+ "useState",
19
+ "useEffect",
20
+ "useMemo",
21
+ "useCallback",
22
+ "useRef",
23
+ "useLayoutEffect",
24
+ "jsx",
25
+ "jsxs",
26
+ "_jsx",
27
+ "_jsxs",
28
+ "createElement",
29
+ "requestAnimationFrame"
30
+ ]);
31
+ var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
32
+ "FunctionDeclaration",
33
+ "FunctionExpression",
34
+ "ArrowFunctionExpression"
35
+ ]);
36
+ function parseJavaScriptAst(code) {
37
+ try {
38
+ return acorn.parse(code, {
39
+ ecmaVersion: "latest",
40
+ sourceType: "module",
41
+ allowReturnOutsideFunction: true
42
+ });
43
+ } catch {
44
+ try {
45
+ return acorn.parse(code, {
46
+ ecmaVersion: "latest",
47
+ sourceType: "script",
48
+ allowReturnOutsideFunction: true
49
+ });
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ }
55
+ function getFunctionLabel(node, ancestors) {
56
+ if (node.id && typeof node.id.name === "string") {
57
+ return node.id.name;
58
+ }
59
+ const parent = ancestors[ancestors.length - 2];
60
+ if (parent) {
61
+ if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
62
+ return parent.id.name;
63
+ }
64
+ if (parent.type === "Property" && parent.key?.type === "Identifier") {
65
+ return parent.key.name;
66
+ }
67
+ if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
68
+ return parent.key.name;
69
+ }
70
+ if (parent.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
71
+ return parent.left.name;
72
+ }
73
+ }
74
+ return `anonymous_${node.start}`;
75
+ }
76
+ function isPascalCaseComponent(name) {
77
+ return /^[A-Z][a-zA-Z0-9]*$/.test(name);
78
+ }
79
+ function analyzeAstHotPaths(ast) {
80
+ const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
81
+ const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
82
+ const allFunctions = [];
83
+ const fnByName = /* @__PURE__ */ new Map();
84
+ const callerToCallees = /* @__PURE__ */ new Map();
85
+ walk.ancestor(ast, {
86
+ FunctionDeclaration(node, _state, ancestors) {
87
+ const name = getFunctionLabel(node, ancestors);
88
+ allFunctions.push({ node, name });
89
+ fnByName.set(name, node);
90
+ if (isPascalCaseComponent(name)) {
91
+ hotFunctionNodes.add(node);
92
+ }
93
+ },
94
+ FunctionExpression(node, _state, ancestors) {
95
+ const name = getFunctionLabel(node, ancestors);
96
+ allFunctions.push({ node, name });
97
+ fnByName.set(name, node);
98
+ if (isPascalCaseComponent(name)) {
99
+ hotFunctionNodes.add(node);
100
+ }
101
+ },
102
+ ArrowFunctionExpression(node, _state, ancestors) {
103
+ const name = getFunctionLabel(node, ancestors);
104
+ allFunctions.push({ node, name });
105
+ fnByName.set(name, node);
106
+ if (isPascalCaseComponent(name)) {
107
+ hotFunctionNodes.add(node);
108
+ }
109
+ },
110
+ CallExpression(node, _state, ancestors) {
111
+ const callee = node.callee;
112
+ let calleeName = "";
113
+ let memberProp = "";
114
+ if (callee?.type === "Identifier") {
115
+ calleeName = callee.name;
116
+ for (let i = ancestors.length - 1; i >= 0; i--) {
117
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
118
+ let set = callerToCallees.get(ancestors[i]);
119
+ if (!set) {
120
+ set = /* @__PURE__ */ new Set();
121
+ callerToCallees.set(ancestors[i], set);
122
+ }
123
+ set.add(calleeName);
124
+ break;
125
+ }
126
+ }
127
+ } else if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") {
128
+ memberProp = callee.property.name;
129
+ }
130
+ if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame") {
131
+ for (const arg of node.arguments || []) {
132
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
133
+ hotFunctionNodes.add(arg);
134
+ }
135
+ }
136
+ }
137
+ if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
138
+ for (let i = ancestors.length - 1; i >= 0; i--) {
139
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
140
+ hotFunctionNodes.add(ancestors[i]);
141
+ break;
142
+ }
143
+ }
144
+ }
145
+ },
146
+ ForStatement(_node, _state, ancestors) {
147
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
148
+ },
149
+ ForInStatement(_node, _state, ancestors) {
150
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
151
+ },
152
+ ForOfStatement(_node, _state, ancestors) {
153
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
154
+ },
155
+ WhileStatement(_node, _state, ancestors) {
156
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
157
+ },
158
+ DoWhileStatement(_node, _state, ancestors) {
159
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
160
+ }
161
+ });
162
+ let changed = true;
163
+ while (changed) {
164
+ changed = false;
165
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
166
+ if (hotFunctionNodes.has(callerNode)) continue;
167
+ for (const cName of calleeNames) {
168
+ const targetNode = fnByName.get(cName);
169
+ if (targetNode && hotFunctionNodes.has(targetNode)) {
170
+ hotFunctionNodes.add(callerNode);
171
+ changed = true;
172
+ break;
173
+ }
174
+ }
175
+ }
176
+ }
177
+ const hotFunctionsSkipped = [];
178
+ const coldFunctionsProtected = [];
179
+ for (const fn of allFunctions) {
180
+ if (hotFunctionNodes.has(fn.node)) {
181
+ hotFunctionsSkipped.push(fn.name);
182
+ } else {
183
+ coldFunctionNodes.add(fn.node);
184
+ coldFunctionsProtected.push(fn.name);
185
+ }
186
+ }
187
+ return {
188
+ report: {
189
+ totalFunctions: allFunctions.length,
190
+ hotFunctionsSkipped,
191
+ coldFunctionsProtected
192
+ },
193
+ hotFunctionNodes,
194
+ coldFunctionNodes
195
+ };
196
+ }
197
+ function markEnclosingFunctionHot(ancestors, hotSet) {
198
+ for (let i = ancestors.length - 1; i >= 0; i--) {
199
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
200
+ hotSet.add(ancestors[i]);
201
+ break;
202
+ }
203
+ }
204
+ }
205
+ function detectHotPaths(code) {
206
+ const ast = parseJavaScriptAst(code);
207
+ if (!ast) {
48
208
  return {
49
- code: outputCode,
50
- encryptedStringsCount,
51
- mangledSymbolsCount,
52
- hotPathReport,
53
- integrityToken,
209
+ totalFunctions: 0,
210
+ hotFunctionsSkipped: [],
211
+ coldFunctionsProtected: []
54
212
  };
213
+ }
214
+ return analyzeAstHotPaths(ast).report;
215
+ }
216
+
217
+ // src/ast/string-vault.ts
218
+ import * as acorn2 from "acorn";
219
+ import * as walk2 from "acorn-walk";
220
+ var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
221
+ "use strict",
222
+ "use client",
223
+ "use server",
224
+ "use asm"
225
+ ]);
226
+ var HELPER_TEMPLATE = acorn2.parse(
227
+ `const _ = [].map(function(a) {
228
+ var s = "";
229
+ for (var j = 0; j < a.length; j++) {
230
+ s += String.fromCharCode(a.charCodeAt(j) ^ (((0 ^ ((j & 1) * 0)) & 30) | 1));
231
+ }
232
+ return s;
233
+ });`,
234
+ { ecmaVersion: "latest", sourceType: "script" }
235
+ ).body[0];
236
+ function createVaultHelperAst(cacheVarName, encryptedPayloads, mask, step) {
237
+ const node = structuredClone(HELPER_TEMPLATE);
238
+ node.declarations[0].id.name = cacheVarName;
239
+ node.declarations[0].init.callee.object.elements = encryptedPayloads.map(
240
+ (str) => ({
241
+ type: "Literal",
242
+ value: str,
243
+ raw: JSON.stringify(str)
244
+ })
245
+ );
246
+ const fn = node.declarations[0].init.arguments[0];
247
+ const binaryXor = fn.body.body[1].body.body[0].expression.right.arguments[0];
248
+ const innerLeft = binaryXor.right.left.left;
249
+ innerLeft.left.value = mask;
250
+ innerLeft.left.raw = String(mask);
251
+ innerLeft.right.right.value = step;
252
+ innerLeft.right.right.raw = String(step);
253
+ return node;
254
+ }
255
+ function computeFnv1aHash(input, seed = 2166136261) {
256
+ let hash = seed >>> 0;
257
+ for (let i = 0; i < input.length; i++) {
258
+ hash ^= input.charCodeAt(i);
259
+ hash = Math.imul(hash, 16777619) >>> 0;
260
+ }
261
+ return hash >>> 0;
262
+ }
263
+ function encodeStringWithSeed(str, mask, step) {
264
+ let out = "";
265
+ for (let i = 0; i < str.length; i++) {
266
+ const code = str.charCodeAt(i);
267
+ const k = (mask ^ (i & 1) * step) & 30 | 1;
268
+ out += String.fromCharCode(code ^ k);
269
+ }
270
+ return out;
271
+ }
272
+ function applyStringVault(ast, seed = 2654435769, minStringLength = 4) {
273
+ const suffix = ((seed >>> 0) % 255).toString(36);
274
+ const cacheVarName = `_uC${suffix}`;
275
+ const mask = seed >>> 0 & 30 | 3;
276
+ const step = (seed >>> 5 & 7) * 2 + 3;
277
+ const stringToIndex = /* @__PURE__ */ new Map();
278
+ const encryptedPayloads = [];
279
+ const targetsToReplace = [];
280
+ walk2.ancestor(ast, {
281
+ Literal(node, _state, ancestors) {
282
+ if (typeof node.value !== "string") return;
283
+ const val = node.value;
284
+ if (val.length < minStringLength) return;
285
+ if (DIRECTIVE_STRINGS.has(val)) return;
286
+ const parent = ancestors[ancestors.length - 2];
287
+ if (!parent) return;
288
+ if (parent.type === "ExpressionStatement" && parent.directive) return;
289
+ if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
290
+ if (parent.source === node) return;
291
+ }
292
+ if ((parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
293
+ return;
294
+ }
295
+ if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
296
+ return;
297
+ }
298
+ let idx = stringToIndex.get(val);
299
+ if (idx === void 0) {
300
+ idx = encryptedPayloads.length;
301
+ stringToIndex.set(val, idx);
302
+ encryptedPayloads.push(encodeStringWithSeed(val, mask, step));
303
+ }
304
+ targetsToReplace.push({ node });
305
+ }
306
+ });
307
+ if (targetsToReplace.length === 0 || encryptedPayloads.length === 0) {
308
+ return {
309
+ encryptedStringsCount: 0,
310
+ integrityToken: computeFnv1aHash("empty", seed)
311
+ };
312
+ }
313
+ for (const { node } of targetsToReplace) {
314
+ const idx = stringToIndex.get(node.value);
315
+ node.type = "MemberExpression";
316
+ node.object = {
317
+ type: "Identifier",
318
+ name: cacheVarName
319
+ };
320
+ node.property = {
321
+ type: "Literal",
322
+ value: idx,
323
+ raw: String(idx)
324
+ };
325
+ node.computed = true;
326
+ node.optional = false;
327
+ delete node.value;
328
+ delete node.raw;
329
+ }
330
+ const serializedTable = JSON.stringify(encryptedPayloads);
331
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
332
+ const helperStmt = createVaultHelperAst(
333
+ cacheVarName,
334
+ encryptedPayloads,
335
+ mask,
336
+ step
337
+ );
338
+ let insertIdx = 0;
339
+ while (insertIdx < ast.body.length) {
340
+ const stmt = ast.body[insertIdx];
341
+ const isDirective = stmt.type === "ExpressionStatement" && (stmt.directive || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && DIRECTIVE_STRINGS.has(stmt.expression.value));
342
+ if (isDirective || stmt.type === "ImportDeclaration") {
343
+ insertIdx++;
344
+ } else {
345
+ break;
346
+ }
347
+ }
348
+ ast.body.splice(insertIdx, 0, helperStmt);
349
+ return {
350
+ encryptedStringsCount: encryptedPayloads.length,
351
+ integrityToken
352
+ };
353
+ }
354
+
355
+ // src/ast/polymorphic-mangler.ts
356
+ import * as walk3 from "acorn-walk";
357
+ var RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set([
358
+ "arguments",
359
+ "undefined",
360
+ "NaN",
361
+ "Infinity",
362
+ "window",
363
+ "document",
364
+ "globalThis",
365
+ "self",
366
+ "console",
367
+ "Math",
368
+ "JSON",
369
+ "Object",
370
+ "Array",
371
+ "String",
372
+ "Number",
373
+ "Boolean",
374
+ "Symbol",
375
+ "BigInt",
376
+ "Promise",
377
+ "Map",
378
+ "Set",
379
+ "WeakMap",
380
+ "WeakSet",
381
+ "Error",
382
+ "TypeError",
383
+ "RangeError",
384
+ "SyntaxError",
385
+ "RegExp",
386
+ "Date",
387
+ "Reflect",
388
+ "Proxy",
389
+ "Intl",
390
+ "eval",
391
+ "process",
392
+ "Buffer",
393
+ "require",
394
+ "module",
395
+ "exports",
396
+ "React"
397
+ ]);
398
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
399
+ "FunctionDeclaration",
400
+ "FunctionExpression",
401
+ "ArrowFunctionExpression"
402
+ ]);
403
+ function collectPatternIdentifiers(pattern, out) {
404
+ if (!pattern) return;
405
+ switch (pattern.type) {
406
+ case "Identifier":
407
+ out.push(pattern);
408
+ break;
409
+ case "AssignmentPattern":
410
+ collectPatternIdentifiers(pattern.left, out);
411
+ break;
412
+ case "RestElement":
413
+ collectPatternIdentifiers(pattern.argument, out);
414
+ break;
415
+ case "ArrayPattern":
416
+ for (const el of pattern.elements || []) {
417
+ if (el) collectPatternIdentifiers(el, out);
418
+ }
419
+ break;
420
+ case "ObjectPattern":
421
+ for (const prop of pattern.properties || []) {
422
+ if (prop.type === "Property") {
423
+ if (prop.shorthand) {
424
+ prop.shorthand = false;
425
+ prop.key = { ...prop.key };
426
+ }
427
+ collectPatternIdentifiers(prop.value, out);
428
+ } else if (prop.type === "RestElement") {
429
+ collectPatternIdentifiers(prop.argument, out);
430
+ }
431
+ }
432
+ break;
433
+ }
434
+ }
435
+ function applyPolymorphicMangler(ast, seed = 2654435769) {
436
+ const scopeMap = /* @__PURE__ */ new Map();
437
+ const scopeDepthMap = /* @__PURE__ */ new Map();
438
+ let counter = 0;
439
+ function makeScopedMangledName(scopeDepth, localIndex, usedValues) {
440
+ counter++;
441
+ let salt = 0;
442
+ while (true) {
443
+ const h = computeFnv1aHash(`s${scopeDepth}:i${localIndex}:${salt}`, seed);
444
+ const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
445
+ if (!usedValues.has(candidate)) {
446
+ return candidate;
447
+ }
448
+ salt++;
449
+ }
450
+ }
451
+ function countFunctionDepth(ancestors) {
452
+ let depth = 0;
453
+ for (let i = 0; i < ancestors.length; i++) {
454
+ if (FUNCTION_TYPES.has(ancestors[i].type)) {
455
+ depth++;
456
+ }
457
+ }
458
+ return Math.max(1, depth);
459
+ }
460
+ function findEnclosingFunction(ancestors) {
461
+ for (let i = ancestors.length - 1; i >= 0; i--) {
462
+ if (FUNCTION_TYPES.has(ancestors[i].type)) {
463
+ return ancestors[i];
464
+ }
465
+ }
466
+ return null;
467
+ }
468
+ function registerBindingAndMutateDeclSite(idNode, bindings, scopeDepth) {
469
+ const origName = idNode.name;
470
+ if (RESERVED_IDENTIFIERS.has(origName) || origName.startsWith("_u") || origName.startsWith("_0x")) {
471
+ return;
472
+ }
473
+ let mangled = bindings.get(origName);
474
+ if (!mangled) {
475
+ const usedValues = new Set(bindings.values());
476
+ mangled = makeScopedMangledName(scopeDepth, bindings.size, usedValues);
477
+ bindings.set(origName, mangled);
478
+ }
479
+ idNode.name = mangled;
480
+ }
481
+ function registerFunctionParams(fnNode, ancestors) {
482
+ let bindings = scopeMap.get(fnNode);
483
+ const depth = countFunctionDepth(ancestors);
484
+ scopeDepthMap.set(fnNode, depth);
485
+ if (!bindings) {
486
+ bindings = /* @__PURE__ */ new Map();
487
+ scopeMap.set(fnNode, bindings);
488
+ }
489
+ for (const param of fnNode.params || []) {
490
+ const idNodes = [];
491
+ collectPatternIdentifiers(param, idNodes);
492
+ for (const idNode of idNodes) {
493
+ registerBindingAndMutateDeclSite(idNode, bindings, depth);
494
+ }
495
+ }
496
+ }
497
+ walk3.ancestor(ast, {
498
+ FunctionDeclaration(node, _state, ancestors) {
499
+ registerFunctionParams(node, ancestors);
500
+ },
501
+ FunctionExpression(node, _state, ancestors) {
502
+ registerFunctionParams(node, ancestors);
503
+ },
504
+ ArrowFunctionExpression(node, _state, ancestors) {
505
+ registerFunctionParams(node, ancestors);
506
+ },
507
+ VariableDeclaration(node, _state, ancestors) {
508
+ const fnScope = findEnclosingFunction(ancestors);
509
+ if (!fnScope) return;
510
+ let bindings = scopeMap.get(fnScope);
511
+ const depth = scopeDepthMap.get(fnScope) ?? countFunctionDepth(ancestors);
512
+ if (!bindings) {
513
+ bindings = /* @__PURE__ */ new Map();
514
+ scopeMap.set(fnScope, bindings);
515
+ }
516
+ for (const decl of node.declarations || []) {
517
+ const idNodes = [];
518
+ collectPatternIdentifiers(decl.id, idNodes);
519
+ for (const idNode of idNodes) {
520
+ registerBindingAndMutateDeclSite(idNode, bindings, depth);
521
+ }
522
+ }
523
+ }
524
+ });
525
+ if (counter === 0) return 0;
526
+ walk3.ancestor(ast, {
527
+ AssignmentExpression(node, _state, ancestors) {
528
+ const idNodes = [];
529
+ collectPatternIdentifiers(node.left, idNodes);
530
+ for (const idNode of idNodes) {
531
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
532
+ if (resolved) {
533
+ idNode.name = resolved;
534
+ }
535
+ }
536
+ },
537
+ ForInStatement(node, _state, ancestors) {
538
+ if (node.left && node.left.type !== "VariableDeclaration") {
539
+ const idNodes = [];
540
+ collectPatternIdentifiers(node.left, idNodes);
541
+ for (const idNode of idNodes) {
542
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
543
+ if (resolved) idNode.name = resolved;
544
+ }
545
+ }
546
+ },
547
+ ForOfStatement(node, _state, ancestors) {
548
+ if (node.left && node.left.type !== "VariableDeclaration") {
549
+ const idNodes = [];
550
+ collectPatternIdentifiers(node.left, idNodes);
551
+ for (const idNode of idNodes) {
552
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
553
+ if (resolved) idNode.name = resolved;
554
+ }
555
+ }
556
+ },
557
+ Property(node, _state, ancestors) {
558
+ if (node.shorthand && node.value?.type === "Identifier") {
559
+ const resolved = resolveMangledName(node.value.name, ancestors, scopeMap);
560
+ if (resolved) {
561
+ node.shorthand = false;
562
+ node.key = { type: "Identifier", name: node.value.name };
563
+ }
564
+ }
565
+ },
566
+ Identifier(node, _state, ancestors) {
567
+ const parent = ancestors[ancestors.length - 2];
568
+ if (!parent) return;
569
+ if ((parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.id === node) {
570
+ return;
571
+ }
572
+ if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) {
573
+ return;
574
+ }
575
+ if ((parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
576
+ return;
577
+ }
578
+ if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier") {
579
+ return;
580
+ }
581
+ const resolved = resolveMangledName(node.name, ancestors, scopeMap);
582
+ if (resolved) {
583
+ node.name = resolved;
584
+ }
585
+ }
586
+ });
587
+ return counter;
588
+ }
589
+ function resolveMangledName(name, ancestors, scopeMap) {
590
+ for (let i = ancestors.length - 1; i >= 0; i--) {
591
+ const anc = ancestors[i];
592
+ const bindings = scopeMap.get(anc);
593
+ if (bindings && bindings.has(name)) {
594
+ return bindings.get(name);
595
+ }
596
+ }
597
+ return null;
598
+ }
599
+
600
+ // src/ast/cold-flow-guard.ts
601
+ import * as walk4 from "acorn-walk";
602
+ function createOpaqueGuardStatement(seed, fnIndex) {
603
+ const a = (seed >>> 0) + Math.imul(fnIndex + 1, 73244475) & 65535;
604
+ const b = (a ^ 4951) & 65535;
605
+ const wrongVal = (a ^ b) & 7 ^ 5;
606
+ return {
607
+ type: "IfStatement",
608
+ test: {
609
+ type: "BinaryExpression",
610
+ operator: "===",
611
+ left: {
612
+ type: "BinaryExpression",
613
+ operator: "&",
614
+ left: {
615
+ type: "BinaryExpression",
616
+ operator: "^",
617
+ left: { type: "Literal", value: a, raw: String(a) },
618
+ right: { type: "Literal", value: b, raw: String(b) }
619
+ },
620
+ right: { type: "Literal", value: 7, raw: "7" }
621
+ },
622
+ right: { type: "Literal", value: wrongVal, raw: String(wrongVal) }
623
+ },
624
+ consequent: {
625
+ type: "ReturnStatement",
626
+ argument: null
627
+ },
628
+ alternate: null
629
+ };
630
+ }
631
+ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769) {
632
+ let guardedCount = 0;
633
+ function maybeInjectGuard(node) {
634
+ if (!coldFunctionNodes.has(node)) return;
635
+ if (!node.body || node.body.type !== "BlockStatement") return;
636
+ guardedCount++;
637
+ const guardStmt = createOpaqueGuardStatement(seed, guardedCount);
638
+ let insertIdx = 0;
639
+ while (insertIdx < node.body.body.length && node.body.body[insertIdx].type === "ExpressionStatement" && node.body.body[insertIdx].directive) {
640
+ insertIdx++;
641
+ }
642
+ node.body.body.splice(insertIdx, 0, guardStmt);
643
+ }
644
+ walk4.simple(ast, {
645
+ FunctionDeclaration: maybeInjectGuard,
646
+ FunctionExpression: maybeInjectGuard,
647
+ ArrowFunctionExpression: maybeInjectGuard
648
+ });
649
+ return guardedCount;
650
+ }
651
+
652
+ // src/runtime/integrity-guard.ts
653
+ var FNV_OFFSET_BASIS = 2166136261;
654
+ var FNV_PRIME = 16777619;
655
+ function computeIntegrityHash(source, seed = 0) {
656
+ let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
657
+ for (let i = 0; i < source.length; i++) {
658
+ hash ^= source.charCodeAt(i);
659
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
660
+ }
661
+ return hash >>> 0;
662
+ }
663
+
664
+ // src/runtime/devtools-deterrent.ts
665
+ function deriveIntegrityFnName(seed) {
666
+ const hash = computeIntegrityHash(`unpeek:fn:${seed}`, seed);
667
+ return `_u$${hash.toString(36)}`;
668
+ }
669
+ function deriveLocalVar(label, seed) {
670
+ const hash = computeIntegrityHash(`unpeek:var:${label}:${seed}`, seed) & 1048575;
671
+ return `_${label}${hash.toString(36)}`;
672
+ }
673
+ function createDeterrentSnippet(config) {
674
+ const seed = config.seed >>> 0;
675
+ const deterrentMode = config.deterrentMode ?? "passive";
676
+ const fnName = deriveIntegrityFnName(seed);
677
+ const strVar = deriveLocalVar("s", seed);
678
+ const tamperVar = deriveLocalVar("t", seed);
679
+ const noopVar = deriveLocalVar("n", seed);
680
+ const methodsVar = deriveLocalVar("m", seed);
681
+ const idxVar = deriveLocalVar("i", seed);
682
+ const errVar = deriveLocalVar("e", seed);
683
+ const gradualConsoleSilence = deterrentMode === "gradual" ? `if(typeof console!=='undefined'){var ${noopVar}=function(){},${methodsVar}=['log','debug','info','table','dir'];for(var ${idxVar}=0;${idxVar}<${methodsVar}.length;${idxVar}++){try{console[${methodsVar}[${idxVar}]]=${noopVar};}catch(${errVar}){}}}` : "";
684
+ const tamperDispatch = `if(typeof window.dispatchEvent==='function'&&typeof CustomEvent==='function'){try{window.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(${errVar}){}}`;
685
+ return `(function ${fnName}(){if(typeof window!=='undefined'){try{var ${strVar}=Function.prototype.toString,${tamperVar}=${strVar}.call(${strVar}).indexOf('[native code]')===-1||${strVar}.call(${fnName}).indexOf('\\n')!==-1||${strVar}.call(${fnName}).indexOf('\\r')!==-1;if(${tamperVar}){window.__unpeek_tampered=!0;${tamperDispatch}${gradualConsoleSilence}}}catch(${errVar}){}}})();`;
686
+ }
687
+
688
+ // src/runtime/index.ts
689
+ function generateRuntimeShield(config) {
690
+ const preambleCode = createDeterrentSnippet(config);
691
+ const integrityCheckFnName = deriveIntegrityFnName(config.seed);
692
+ const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computeIntegrityHash(preambleCode, config.seed);
693
+ return {
694
+ preambleCode,
695
+ integrityCheckFnName,
696
+ expectedHash
697
+ };
698
+ }
699
+
700
+ // src/ast/index.ts
701
+ function transformJavaScript(code, options = {}) {
702
+ const seed = options.seed ?? 2654435769;
703
+ const minStringLength = options.minStringLength ?? 4;
704
+ if (!code || !code.trim()) {
705
+ return {
706
+ code,
707
+ encryptedStringsCount: 0,
708
+ mangledSymbolsCount: 0,
709
+ hotPathReport: {
710
+ totalFunctions: 0,
711
+ hotFunctionsSkipped: [],
712
+ coldFunctionsProtected: []
713
+ },
714
+ integrityToken: computeFnv1aHash("", seed)
715
+ };
716
+ }
717
+ const ast = parseJavaScriptAst(code);
718
+ if (!ast) {
719
+ return {
720
+ code,
721
+ encryptedStringsCount: 0,
722
+ mangledSymbolsCount: 0,
723
+ hotPathReport: {
724
+ totalFunctions: 0,
725
+ hotFunctionsSkipped: [],
726
+ coldFunctionsProtected: []
727
+ },
728
+ integrityToken: computeFnv1aHash(code, seed)
729
+ };
730
+ }
731
+ const { report: hotPathReport, coldFunctionNodes } = analyzeAstHotPaths(ast);
732
+ applyColdFlowGuard(ast, coldFunctionNodes, seed);
733
+ const mangledSymbolsCount = applyPolymorphicMangler(ast, seed);
734
+ const { encryptedStringsCount, integrityToken } = applyStringVault(
735
+ ast,
736
+ seed,
737
+ minStringLength
738
+ );
739
+ const outputCode = generate(ast, { indent: "", lineEnd: "" });
740
+ let finalCode = outputCode;
741
+ if (options.injectRuntimeShield) {
742
+ const shield = generateRuntimeShield({
743
+ seed,
744
+ deterrentMode: options.deterrentMode ?? "gradual",
745
+ expectedIntegrityHash: integrityToken
746
+ });
747
+ if (shield.preambleCode) {
748
+ finalCode = `${shield.preambleCode}
749
+ ${finalCode}`;
750
+ }
751
+ }
752
+ return {
753
+ code: finalCode,
754
+ encryptedStringsCount,
755
+ mangledSymbolsCount,
756
+ hotPathReport,
757
+ integrityToken
758
+ };
55
759
  }
760
+ export {
761
+ computeFnv1aHash,
762
+ detectHotPaths,
763
+ transformJavaScript
764
+ };
765
+ //# sourceMappingURL=index.js.map