unpeek 1.6.0 → 1.6.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/dist/webpack.js CHANGED
@@ -95,15 +95,100 @@ function analyzeAstHotPaths(ast) {
95
95
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
96
96
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
97
97
  const directHotNodes = /* @__PURE__ */ new Set();
98
+ const serializedFunctionNodes = /* @__PURE__ */ new Set();
99
+ const serializerHelperNodes = /* @__PURE__ */ new Set();
98
100
  const allFunctions = [];
99
101
  const fnByName = /* @__PURE__ */ new Map();
100
102
  const scopeFunctions = /* @__PURE__ */ new Map();
101
103
  const fnScopeChain = /* @__PURE__ */ new Map();
104
+ const fnParams = /* @__PURE__ */ new Map();
105
+ const fnVarAliases = /* @__PURE__ */ new Map();
102
106
  const callerToCallees = /* @__PURE__ */ new Map();
107
+ const pendingSerializedRefs = [];
108
+ const allCallSites = [];
109
+ function ensureFnParams(fnNode) {
110
+ let paramSet = fnParams.get(fnNode);
111
+ if (!paramSet) {
112
+ paramSet = /* @__PURE__ */ new Set();
113
+ for (const p of fnNode.params || []) {
114
+ if (p?.type === "Identifier") {
115
+ paramSet.add(p.name);
116
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
117
+ paramSet.add(p.left.name);
118
+ }
119
+ }
120
+ fnParams.set(fnNode, paramSet);
121
+ }
122
+ return paramSet;
123
+ }
124
+ function recordVarAlias(scopeNode, varName, rhsName) {
125
+ let map = fnVarAliases.get(scopeNode);
126
+ if (!map) {
127
+ map = /* @__PURE__ */ new Map();
128
+ fnVarAliases.set(scopeNode, map);
129
+ }
130
+ map.set(varName, rhsName);
131
+ }
132
+ function resolveAliasTarget(scopeNode, identName) {
133
+ const map = fnVarAliases.get(scopeNode);
134
+ let cur = identName;
135
+ const seen = /* @__PURE__ */ new Set();
136
+ while (map && map.has(cur) && !seen.has(cur)) {
137
+ seen.add(cur);
138
+ cur = map.get(cur);
139
+ }
140
+ return cur;
141
+ }
142
+ function markSerializedFunction(node) {
143
+ serializedFunctionNodes.add(node);
144
+ hotFunctionNodes.add(node);
145
+ directHotNodes.add(node);
146
+ hotExemptNodes.add(node);
147
+ }
148
+ function findEnclosingFunction(ancestors, selfNode) {
149
+ for (let i = ancestors.length - 1; i >= 0; i--) {
150
+ if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
151
+ return ancestors[i];
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+ function findOutermostModuleFunction(ancestors) {
157
+ const fnList = [];
158
+ for (let i = 0; i < ancestors.length; i++) {
159
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
160
+ fnList.push(ancestors[i]);
161
+ }
162
+ }
163
+ if (fnList.length === 0) return null;
164
+ if (fnList.length === 1) return fnList[0];
165
+ return fnList[1];
166
+ }
167
+ function isZeroArgIifeFactoryFunction(node) {
168
+ if (!node || node.params && node.params.length > 0) return false;
169
+ if (!node.body || node.body.type !== "BlockStatement") return false;
170
+ const stmts = (node.body.body || []).filter(
171
+ (s) => !(s.type === "ExpressionStatement" && s.directive)
172
+ );
173
+ if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
174
+ const retArg = stmts[0].argument;
175
+ if (!retArg || retArg.type !== "CallExpression") return false;
176
+ const callee = retArg.callee;
177
+ return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
178
+ }
103
179
  function registerFunctionNode(node, ancestors) {
104
180
  const name = getFunctionLabel(node, ancestors);
105
181
  allFunctions.push({ node, name });
106
182
  fnByName.set(name, node);
183
+ const paramSet = /* @__PURE__ */ new Set();
184
+ for (const p of node.params || []) {
185
+ if (p?.type === "Identifier") {
186
+ paramSet.add(p.name);
187
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
188
+ paramSet.add(p.left.name);
189
+ }
190
+ }
191
+ fnParams.set(node, paramSet);
107
192
  const enclosingScope = findEnclosingScopeNode(ancestors, node);
108
193
  let localMap = scopeFunctions.get(enclosingScope);
109
194
  if (!localMap) {
@@ -112,6 +197,22 @@ function analyzeAstHotPaths(ast) {
112
197
  }
113
198
  localMap.set(name, node);
114
199
  const parent = ancestors[ancestors.length - 2];
200
+ if (parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
201
+ fnByName.set(parent.id.name, node);
202
+ localMap.set(parent.id.name, node);
203
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
204
+ fnByName.set(parent.left.name, node);
205
+ localMap.set(parent.left.name, node);
206
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "MemberExpression" && !parent.left.computed && parent.left.property?.type === "Identifier") {
207
+ const propName = parent.left.property.name;
208
+ fnByName.set(propName, node);
209
+ localMap.set(propName, node);
210
+ if (parent.left.object?.type === "Identifier") {
211
+ const qual = `${parent.left.object.name}.${propName}`;
212
+ fnByName.set(qual, node);
213
+ localMap.set(qual, node);
214
+ }
215
+ }
115
216
  const grandParent = ancestors[ancestors.length - 3];
116
217
  const greatGrandParent = ancestors[ancestors.length - 4];
117
218
  if (parent?.type === "Property" && parent.key?.type === "Identifier" && grandParent?.type === "ObjectExpression" && greatGrandParent?.type === "VariableDeclarator" && greatGrandParent.id?.type === "Identifier") {
@@ -121,7 +222,7 @@ function analyzeAstHotPaths(ast) {
121
222
  }
122
223
  const chain = [];
123
224
  for (let i = ancestors.length - 1; i >= 0; i--) {
124
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program") {
225
+ if (ancestors[i] !== node && (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program")) {
125
226
  chain.push(ancestors[i]);
126
227
  }
127
228
  }
@@ -130,8 +231,13 @@ function analyzeAstHotPaths(ast) {
130
231
  hotFunctionNodes.add(node);
131
232
  directHotNodes.add(node);
132
233
  }
234
+ if (isZeroArgIifeFactoryFunction(node)) {
235
+ markSerializedFunction(node);
236
+ }
133
237
  }
134
238
  function resolveCalleeNode(callerNode, calleeKey) {
239
+ const directLocal = scopeFunctions.get(callerNode)?.get(calleeKey);
240
+ if (directLocal) return directLocal;
135
241
  const chain = fnScopeChain.get(callerNode);
136
242
  if (chain) {
137
243
  for (const scopeNode of chain) {
@@ -142,6 +248,25 @@ function analyzeAstHotPaths(ast) {
142
248
  }
143
249
  return fnByName.get(calleeKey);
144
250
  }
251
+ function queueSerializedTarget(target, enclosingScope) {
252
+ if (!target) return;
253
+ if (FUNCTION_NODE_TYPES.has(target.type)) {
254
+ markSerializedFunction(target);
255
+ } else if (target.type === "Identifier") {
256
+ pendingSerializedRefs.push({ scopeNode: enclosingScope, name: target.name });
257
+ } else if (target.type === "MemberExpression" && !target.computed && target.property?.type === "Identifier") {
258
+ pendingSerializedRefs.push({
259
+ scopeNode: enclosingScope,
260
+ name: target.property.name
261
+ });
262
+ if (target.object?.type === "Identifier") {
263
+ pendingSerializedRefs.push({
264
+ scopeNode: enclosingScope,
265
+ name: `${target.object.name}.${target.property.name}`
266
+ });
267
+ }
268
+ }
269
+ }
145
270
  walk.ancestor(ast, {
146
271
  FunctionDeclaration(node, _state, ancestors) {
147
272
  registerFunctionNode(node, ancestors);
@@ -152,6 +277,59 @@ function analyzeAstHotPaths(ast) {
152
277
  ArrowFunctionExpression(node, _state, ancestors) {
153
278
  registerFunctionNode(node, ancestors);
154
279
  },
280
+ VariableDeclarator(node, _state, ancestors) {
281
+ if (node.id?.type === "Identifier" && node.init?.type === "Identifier") {
282
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
283
+ recordVarAlias(scopeNode, node.id.name, node.init.name);
284
+ }
285
+ },
286
+ AssignmentExpression(node, _state, ancestors) {
287
+ const left = node.left;
288
+ if (left?.type === "Identifier" && node.right?.type === "Identifier") {
289
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
290
+ recordVarAlias(scopeNode, left.name, node.right.name);
291
+ }
292
+ const isBareOnMessage = left?.type === "Identifier" && left.name === "onmessage";
293
+ const isSelfOnMessage = left?.type === "MemberExpression" && !left.computed && left.object?.type === "Identifier" && left.object.name === "self" && left.property?.type === "Identifier" && left.property.name === "onmessage";
294
+ if (isBareOnMessage || isSelfOnMessage) {
295
+ const enclosingFn = findEnclosingFunction(ancestors);
296
+ if (enclosingFn) {
297
+ markSerializedFunction(enclosingFn);
298
+ }
299
+ const outerFn = findOutermostModuleFunction(ancestors);
300
+ if (outerFn) {
301
+ markSerializedFunction(outerFn);
302
+ }
303
+ const scopeNode = enclosingFn ?? ast;
304
+ queueSerializedTarget(node.right, scopeNode);
305
+ }
306
+ },
307
+ ObjectExpression(node, _state, ancestors) {
308
+ const props = node.properties || [];
309
+ const propMap = /* @__PURE__ */ new Map();
310
+ for (const p of props) {
311
+ if (p?.type === "Property" && !p.computed) {
312
+ const keyName = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : "";
313
+ if (keyName) {
314
+ propMap.set(keyName, p.value);
315
+ }
316
+ }
317
+ }
318
+ const hasWorkerDescriptorShape = propMap.has("init") && propMap.has("dependencies") || propMap.has("isWorkerModule") || propMap.has("getTransferables") && (propMap.has("init") || propMap.has("dependencies"));
319
+ if (hasWorkerDescriptorShape) {
320
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
321
+ for (const key of ["init", "getTransferables", "worker"]) {
322
+ const val = propMap.get(key);
323
+ if (val) queueSerializedTarget(val, scopeNode);
324
+ }
325
+ const deps = propMap.get("dependencies");
326
+ if (deps?.type === "ArrayExpression") {
327
+ for (const el of deps.elements || []) {
328
+ if (el) queueSerializedTarget(el, scopeNode);
329
+ }
330
+ }
331
+ }
332
+ },
155
333
  CallExpression(node, _state, ancestors) {
156
334
  const callee = node.callee;
157
335
  let calleeName = "";
@@ -168,38 +346,76 @@ function analyzeAstHotPaths(ast) {
168
346
  qualifiedCall = memberProp;
169
347
  }
170
348
  }
349
+ const enclosingFn = findEnclosingFunction(ancestors);
350
+ const currentScope = enclosingFn ?? ast;
171
351
  if (qualifiedCall || memberProp) {
172
- for (let i = ancestors.length - 1; i >= 0; i--) {
173
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
174
- let set = callerToCallees.get(ancestors[i]);
175
- if (!set) {
176
- set = /* @__PURE__ */ new Set();
177
- callerToCallees.set(ancestors[i], set);
178
- }
179
- if (qualifiedCall) set.add(qualifiedCall);
180
- if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
181
- set.add(memberProp);
182
- }
183
- break;
352
+ allCallSites.push({
353
+ scopeNode: currentScope,
354
+ calleeKey: qualifiedCall || memberProp,
355
+ args: node.arguments || []
356
+ });
357
+ if (enclosingFn) {
358
+ let set = callerToCallees.get(enclosingFn);
359
+ if (!set) {
360
+ set = /* @__PURE__ */ new Set();
361
+ callerToCallees.set(enclosingFn, set);
362
+ }
363
+ if (qualifiedCall) set.add(qualifiedCall);
364
+ if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
365
+ set.add(memberProp);
366
+ }
367
+ }
368
+ }
369
+ if (memberProp === "toString" && (!node.arguments || node.arguments.length === 0) && callee?.type === "MemberExpression") {
370
+ const targetObj = callee.object;
371
+ queueSerializedTarget(targetObj, currentScope);
372
+ if (targetObj?.type === "Identifier" && enclosingFn) {
373
+ const resolvedName = resolveAliasTarget(enclosingFn, targetObj.name);
374
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
375
+ serializerHelperNodes.add(enclosingFn);
376
+ }
377
+ if (resolvedName !== targetObj.name) {
378
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
184
379
  }
185
380
  }
186
381
  }
382
+ if ((memberProp === "call" || memberProp === "apply") && callee?.type === "MemberExpression" && callee.object?.type === "MemberExpression" && callee.object.property?.type === "Identifier" && callee.object.property.name === "toString" && node.arguments?.length > 0) {
383
+ const firstArg = node.arguments[0];
384
+ queueSerializedTarget(firstArg, currentScope);
385
+ if (firstArg?.type === "Identifier" && enclosingFn) {
386
+ const resolvedName = resolveAliasTarget(enclosingFn, firstArg.name);
387
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
388
+ serializerHelperNodes.add(enclosingFn);
389
+ }
390
+ if (resolvedName !== firstArg.name) {
391
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
392
+ }
393
+ }
394
+ }
395
+ if (calleeName === "importScripts" || memberProp === "importScripts" && callee?.object?.type === "Identifier" && callee.object.name === "self") {
396
+ if (enclosingFn) markSerializedFunction(enclosingFn);
397
+ const outerFn = findOutermostModuleFunction(ancestors);
398
+ if (outerFn) markSerializedFunction(outerFn);
399
+ }
187
400
  if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame" || calleeName === "cancelAnimationFrame" || memberProp === "cancelAnimationFrame") {
188
401
  for (const arg of node.arguments || []) {
189
402
  if (FUNCTION_NODE_TYPES.has(arg.type)) {
190
403
  hotFunctionNodes.add(arg);
191
404
  directHotNodes.add(arg);
192
405
  hotExemptNodes.add(arg);
406
+ } else if (arg?.type === "Identifier") {
407
+ allCallSites.push({
408
+ scopeNode: currentScope,
409
+ calleeKey: arg.name,
410
+ args: [arg]
411
+ });
193
412
  }
194
413
  }
195
414
  }
196
415
  if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
197
- for (let i = ancestors.length - 1; i >= 0; i--) {
198
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
199
- hotFunctionNodes.add(ancestors[i]);
200
- directHotNodes.add(ancestors[i]);
201
- break;
202
- }
416
+ if (enclosingFn) {
417
+ hotFunctionNodes.add(enclosingFn);
418
+ directHotNodes.add(enclosingFn);
203
419
  }
204
420
  }
205
421
  },
@@ -224,10 +440,41 @@ function analyzeAstHotPaths(ast) {
224
440
  markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
225
441
  }
226
442
  });
443
+ for (const callSite of allCallSites) {
444
+ const resolvedCallee = resolveCalleeNode(callSite.scopeNode, callSite.calleeKey);
445
+ if (resolvedCallee && serializerHelperNodes.has(resolvedCallee)) {
446
+ for (const arg of callSite.args) {
447
+ queueSerializedTarget(arg, callSite.scopeNode);
448
+ }
449
+ }
450
+ }
451
+ for (const ref of pendingSerializedRefs) {
452
+ const targetNode = resolveCalleeNode(ref.scopeNode, ref.name);
453
+ if (targetNode) {
454
+ markSerializedFunction(targetNode);
455
+ }
456
+ }
227
457
  const forwardHotSet = new Set(directHotNodes);
228
458
  let forwardChanged = true;
229
459
  while (forwardChanged) {
230
460
  forwardChanged = false;
461
+ for (const fn of allFunctions) {
462
+ if (forwardHotSet.has(fn.node)) continue;
463
+ const chain = fnScopeChain.get(fn.node);
464
+ if (!chain) continue;
465
+ for (const anc of chain) {
466
+ if (anc !== fn.node && (serializedFunctionNodes.has(anc) || forwardHotSet.has(anc))) {
467
+ forwardHotSet.add(fn.node);
468
+ hotFunctionNodes.add(fn.node);
469
+ hotExemptNodes.add(fn.node);
470
+ if (serializedFunctionNodes.has(anc)) {
471
+ serializedFunctionNodes.add(fn.node);
472
+ }
473
+ forwardChanged = true;
474
+ break;
475
+ }
476
+ }
477
+ }
231
478
  for (const callerNode of Array.from(forwardHotSet)) {
232
479
  const calleeNames = callerToCallees.get(callerNode);
233
480
  if (!calleeNames) continue;
@@ -237,6 +484,9 @@ function analyzeAstHotPaths(ast) {
237
484
  forwardHotSet.add(targetNode);
238
485
  hotFunctionNodes.add(targetNode);
239
486
  hotExemptNodes.add(targetNode);
487
+ if (serializedFunctionNodes.has(callerNode)) {
488
+ serializedFunctionNodes.add(targetNode);
489
+ }
240
490
  forwardChanged = true;
241
491
  }
242
492
  }
@@ -300,7 +550,7 @@ var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
300
550
  "use asm"
301
551
  ]);
302
552
  var HELPER_TEMPLATE = acorn2.parse(
303
- `const _ = [].map(function f(a) {
553
+ `var _ = [].map(function f(a) {
304
554
  var s = "";
305
555
  for (var j = 0; j < a.length; j++) {
306
556
  s += String.fromCharCode(a.charCodeAt(j) ^ (((0 ^ ((a._u || /\\n/.test(f) * 14) | ((j & 1) * 0))) & 30) | 1));
@@ -346,8 +596,17 @@ function encodeStringWithSeed(str, mask, step) {
346
596
  return out;
347
597
  }
348
598
  function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
349
- const suffix = ((seed >>> 0) % 255).toString(36);
350
- const cacheVarName = `_uC${suffix}`;
599
+ const alreadyVaulted = ast.body.some(
600
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
601
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
602
+ )
603
+ );
604
+ if (alreadyVaulted) {
605
+ return {
606
+ encryptedStringsCount: 0,
607
+ integrityToken: computeFnv1aHash("already-vaulted", seed)
608
+ };
609
+ }
351
610
  const mask = seed >>> 0 & 30 | 3;
352
611
  const step = (seed >>> 5 & 7) * 2 + 3;
353
612
  const stringToIndex = /* @__PURE__ */ new Map();
@@ -393,6 +652,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
393
652
  integrityToken: computeFnv1aHash("empty", seed)
394
653
  };
395
654
  }
655
+ const serializedTable = JSON.stringify(encryptedPayloads);
656
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
657
+ const suffix = computeFnv1aHash(`vault:${seed}`, integrityToken).toString(36);
658
+ const cacheVarName = `_uC${suffix}`;
396
659
  for (const { node } of targetsToReplace) {
397
660
  const idx = stringToIndex.get(node.value);
398
661
  node.type = "MemberExpression";
@@ -410,8 +673,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
410
673
  delete node.value;
411
674
  delete node.raw;
412
675
  }
413
- const serializedTable = JSON.stringify(encryptedPayloads);
414
- const integrityToken = computeFnv1aHash(serializedTable, seed);
415
676
  const helperStmt = createVaultHelperAst(
416
677
  cacheVarName,
417
678
  encryptedPayloads,
@@ -483,167 +744,351 @@ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
483
744
  "FunctionExpression",
484
745
  "ArrowFunctionExpression"
485
746
  ]);
486
- function collectPatternIdentifiers(pattern, out) {
747
+ var LEXICAL_SCOPE_TYPES = /* @__PURE__ */ new Set([
748
+ "Program",
749
+ "FunctionDeclaration",
750
+ "FunctionExpression",
751
+ "ArrowFunctionExpression",
752
+ "BlockStatement",
753
+ "ForStatement",
754
+ "ForInStatement",
755
+ "ForOfStatement",
756
+ "SwitchStatement",
757
+ "CatchClause",
758
+ "ClassDeclaration",
759
+ "ClassExpression"
760
+ ]);
761
+ function collectPatternTargets(pattern, out, shorthandProp) {
487
762
  if (!pattern) return;
488
763
  switch (pattern.type) {
489
764
  case "Identifier":
490
- out.push(pattern);
765
+ out.push({ idNode: pattern, shorthandProp });
491
766
  break;
492
767
  case "AssignmentPattern":
493
- collectPatternIdentifiers(pattern.left, out);
768
+ collectPatternTargets(pattern.left, out, shorthandProp);
494
769
  break;
495
770
  case "RestElement":
496
- collectPatternIdentifiers(pattern.argument, out);
771
+ collectPatternTargets(pattern.argument, out);
497
772
  break;
498
773
  case "ArrayPattern":
499
774
  for (const el of pattern.elements || []) {
500
- if (el) collectPatternIdentifiers(el, out);
775
+ if (el) collectPatternTargets(el, out);
501
776
  }
502
777
  break;
503
778
  case "ObjectPattern":
504
779
  for (const prop of pattern.properties || []) {
505
780
  if (prop.type === "Property") {
506
- if (prop.shorthand) {
507
- prop.shorthand = false;
508
- prop.key = { ...prop.key };
509
- }
510
- collectPatternIdentifiers(prop.value, out);
781
+ collectPatternTargets(
782
+ prop.value,
783
+ out,
784
+ prop.shorthand ? prop : void 0
785
+ );
511
786
  } else if (prop.type === "RestElement") {
512
- collectPatternIdentifiers(prop.argument, out);
787
+ collectPatternTargets(prop.argument, out);
513
788
  }
514
789
  }
515
790
  break;
516
791
  }
517
792
  }
793
+ function isMangleableName(origName) {
794
+ return !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x");
795
+ }
518
796
  function applyPolymorphicMangler(ast, seed = 2654435769) {
519
- const scopeMap = /* @__PURE__ */ new Map();
520
- const scopeDepthMap = /* @__PURE__ */ new Map();
797
+ const scopeRecords = /* @__PURE__ */ new Map();
798
+ const existingIdentifiers = /* @__PURE__ */ new Set();
521
799
  let counter = 0;
522
- function makeScopedMangledName(scopeDepth, localIndex, usedValues) {
523
- counter++;
524
- let salt = 0;
525
- while (true) {
526
- const h = computeFnv1aHash(`s${scopeDepth}:i${localIndex}:${salt}`, seed);
527
- const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
528
- if (!usedValues.has(candidate)) {
529
- return candidate;
800
+ function ensureScopeChain(ancestors) {
801
+ let prevScope = null;
802
+ for (let i = 0; i < ancestors.length; i++) {
803
+ const node = ancestors[i];
804
+ if (!LEXICAL_SCOPE_TYPES.has(node.type)) continue;
805
+ let record = scopeRecords.get(node);
806
+ if (!record) {
807
+ const isFn = FUNCTION_TYPES.has(node.type);
808
+ const depth = prevScope ? prevScope.depth + (isFn ? 1 : 0) : 0;
809
+ record = {
810
+ node,
811
+ parent: prevScope,
812
+ children: [],
813
+ depth: Math.max(1, depth),
814
+ bindings: /* @__PURE__ */ new Map(),
815
+ usedNames: /* @__PURE__ */ new Set()
816
+ };
817
+ scopeRecords.set(node, record);
818
+ if (prevScope) {
819
+ prevScope.children.push(record);
820
+ }
530
821
  }
531
- salt++;
822
+ prevScope = record;
532
823
  }
824
+ return prevScope;
533
825
  }
534
- function countFunctionDepth(ancestors) {
535
- let depth = 0;
536
- for (let i = 0; i < ancestors.length; i++) {
826
+ function findEnclosingFunctionNode(ancestors) {
827
+ for (let i = ancestors.length - 1; i >= 0; i--) {
537
828
  if (FUNCTION_TYPES.has(ancestors[i].type)) {
538
- depth++;
829
+ return ancestors[i];
539
830
  }
540
831
  }
541
- return Math.max(1, depth);
832
+ return null;
542
833
  }
543
- function findEnclosingFunction(ancestors) {
834
+ function findEnclosingLexicalNode(ancestors) {
544
835
  for (let i = ancestors.length - 1; i >= 0; i--) {
545
- if (FUNCTION_TYPES.has(ancestors[i].type)) {
836
+ if (LEXICAL_SCOPE_TYPES.has(ancestors[i].type)) {
546
837
  return ancestors[i];
547
838
  }
548
839
  }
549
- return null;
840
+ return ancestors[0];
550
841
  }
551
- function registerBindingAndMutateDeclSite(idNode, bindings, scopeDepth) {
552
- const origName = idNode.name;
553
- if (RESERVED_IDENTIFIERS.has(origName) || origName.startsWith("_u") || origName.startsWith("_0x")) {
554
- return;
842
+ function registerBindingTarget(scopeNode, target, shouldMangle) {
843
+ const scope = scopeRecords.get(scopeNode);
844
+ if (!scope) return;
845
+ const origName = target.idNode.name;
846
+ const canMangle = shouldMangle && isMangleableName(origName);
847
+ let entry = scope.bindings.get(origName);
848
+ if (!entry) {
849
+ entry = {
850
+ origName,
851
+ shouldMangle: canMangle,
852
+ targets: [target],
853
+ mangledName: origName
854
+ };
855
+ scope.bindings.set(origName, entry);
856
+ } else {
857
+ if (!canMangle) {
858
+ entry.shouldMangle = false;
859
+ }
860
+ entry.targets.push(target);
555
861
  }
556
- let mangled = bindings.get(origName);
557
- if (!mangled) {
558
- const usedValues = new Set(bindings.values());
559
- mangled = makeScopedMangledName(scopeDepth, bindings.size, usedValues);
560
- bindings.set(origName, mangled);
862
+ }
863
+ function registerBarrierName(scopeNode, origName) {
864
+ const scope = scopeRecords.get(scopeNode);
865
+ if (!scope) return;
866
+ let entry = scope.bindings.get(origName);
867
+ if (!entry) {
868
+ entry = {
869
+ origName,
870
+ shouldMangle: false,
871
+ targets: [],
872
+ mangledName: origName
873
+ };
874
+ scope.bindings.set(origName, entry);
875
+ } else {
876
+ entry.shouldMangle = false;
561
877
  }
562
- idNode.name = mangled;
563
878
  }
564
879
  function registerFunctionParams(fnNode, ancestors) {
565
- let bindings = scopeMap.get(fnNode);
566
- const depth = countFunctionDepth(ancestors);
567
- scopeDepthMap.set(fnNode, depth);
568
- if (!bindings) {
569
- bindings = /* @__PURE__ */ new Map();
570
- scopeMap.set(fnNode, bindings);
571
- }
880
+ ensureScopeChain(ancestors);
572
881
  for (const param of fnNode.params || []) {
573
- const idNodes = [];
574
- collectPatternIdentifiers(param, idNodes);
575
- for (const idNode of idNodes) {
576
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
882
+ const targets = [];
883
+ collectPatternTargets(param, targets);
884
+ for (const target of targets) {
885
+ registerBindingTarget(fnNode, target, true);
577
886
  }
578
887
  }
579
888
  }
889
+ ensureScopeChain([ast]);
580
890
  walk3.ancestor(ast, {
891
+ Identifier(node) {
892
+ if (typeof node.name === "string") {
893
+ existingIdentifiers.add(node.name);
894
+ }
895
+ },
896
+ BlockStatement(_node, _state, ancestors) {
897
+ ensureScopeChain(ancestors);
898
+ },
899
+ ForStatement(_node, _state, ancestors) {
900
+ ensureScopeChain(ancestors);
901
+ },
902
+ ForInStatement(_node, _state, ancestors) {
903
+ ensureScopeChain(ancestors);
904
+ },
905
+ ForOfStatement(_node, _state, ancestors) {
906
+ ensureScopeChain(ancestors);
907
+ },
908
+ SwitchStatement(_node, _state, ancestors) {
909
+ ensureScopeChain(ancestors);
910
+ },
581
911
  FunctionDeclaration(node, _state, ancestors) {
582
912
  registerFunctionParams(node, ancestors);
913
+ if (node.id?.type === "Identifier") {
914
+ const parentAncestors = ancestors.slice(0, -1);
915
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
916
+ const fnNode = findEnclosingFunctionNode(parentAncestors) ?? ast;
917
+ registerBarrierName(lexNode, node.id.name);
918
+ if (lexNode === fnNode.body || fnNode === ast) {
919
+ registerBarrierName(fnNode, node.id.name);
920
+ }
921
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
922
+ registerBarrierName(node, node.id.name);
923
+ }
924
+ }
583
925
  },
584
926
  FunctionExpression(node, _state, ancestors) {
585
927
  registerFunctionParams(node, ancestors);
928
+ if (node.id?.type === "Identifier") {
929
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
930
+ registerBarrierName(node, node.id.name);
931
+ }
932
+ }
586
933
  },
587
934
  ArrowFunctionExpression(node, _state, ancestors) {
588
935
  registerFunctionParams(node, ancestors);
589
936
  },
937
+ ClassDeclaration(node, _state, ancestors) {
938
+ ensureScopeChain(ancestors);
939
+ if (node.id?.type === "Identifier") {
940
+ const parentAncestors = ancestors.slice(0, -1);
941
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
942
+ registerBarrierName(lexNode, node.id.name);
943
+ registerBarrierName(node, node.id.name);
944
+ }
945
+ },
946
+ ClassExpression(node, _state, ancestors) {
947
+ ensureScopeChain(ancestors);
948
+ if (node.id?.type === "Identifier") {
949
+ registerBarrierName(node, node.id.name);
950
+ }
951
+ },
952
+ CatchClause(node, _state, ancestors) {
953
+ ensureScopeChain(ancestors);
954
+ if (node.param) {
955
+ const targets = [];
956
+ collectPatternTargets(node.param, targets);
957
+ for (const target of targets) {
958
+ registerBindingTarget(node, target, true);
959
+ }
960
+ }
961
+ },
590
962
  VariableDeclaration(node, _state, ancestors) {
591
- const fnScope = findEnclosingFunction(ancestors);
592
- if (!fnScope) return;
593
- let bindings = scopeMap.get(fnScope);
594
- const depth = scopeDepthMap.get(fnScope) ?? countFunctionDepth(ancestors);
595
- if (!bindings) {
596
- bindings = /* @__PURE__ */ new Map();
597
- scopeMap.set(fnScope, bindings);
963
+ ensureScopeChain(ancestors);
964
+ const fnScope = findEnclosingFunctionNode(ancestors);
965
+ if (!fnScope) {
966
+ for (const decl of node.declarations || []) {
967
+ const targets = [];
968
+ collectPatternTargets(decl.id, targets);
969
+ for (const target of targets) {
970
+ registerBarrierName(ast, target.idNode.name);
971
+ }
972
+ }
973
+ return;
598
974
  }
975
+ const targetScopeNode = node.kind === "var" ? fnScope : findEnclosingLexicalNode(ancestors);
599
976
  for (const decl of node.declarations || []) {
600
- const idNodes = [];
601
- collectPatternIdentifiers(decl.id, idNodes);
602
- for (const idNode of idNodes) {
603
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
977
+ const targets = [];
978
+ collectPatternTargets(decl.id, targets);
979
+ for (const target of targets) {
980
+ const origName = target.idNode.name;
981
+ if (node.kind === "var") {
982
+ for (let i = ancestors.length - 1; i >= 0; i--) {
983
+ if (ancestors[i] === fnScope) break;
984
+ if (ancestors[i].type === "CatchClause") {
985
+ const catchScope = scopeRecords.get(ancestors[i]);
986
+ if (catchScope?.bindings.has(origName)) {
987
+ registerBarrierName(ancestors[i], origName);
988
+ registerBarrierName(fnScope, origName);
989
+ }
990
+ }
991
+ }
992
+ }
993
+ registerBindingTarget(targetScopeNode, target, true);
604
994
  }
605
995
  }
606
996
  }
607
997
  });
998
+ function isNameUsedInScopeOrAncestors(candidate, scope) {
999
+ if (existingIdentifiers.has(candidate)) return true;
1000
+ let curr = scope;
1001
+ while (curr) {
1002
+ if (curr.usedNames.has(candidate) || curr.bindings.has(candidate)) {
1003
+ return true;
1004
+ }
1005
+ curr = curr.parent;
1006
+ }
1007
+ return false;
1008
+ }
1009
+ function makeScopedMangledName(scope, localIndex) {
1010
+ counter++;
1011
+ let salt = 0;
1012
+ while (true) {
1013
+ const h = computeFnv1aHash(`s${scope.depth}:i${localIndex}:${salt}`, seed);
1014
+ const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
1015
+ if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
1016
+ return candidate;
1017
+ }
1018
+ salt++;
1019
+ }
1020
+ }
1021
+ function assignScopeNamesTopDown(scope) {
1022
+ let localIndex = 0;
1023
+ for (const entry of scope.bindings.values()) {
1024
+ if (!entry.shouldMangle) {
1025
+ entry.mangledName = entry.origName;
1026
+ scope.usedNames.add(entry.origName);
1027
+ continue;
1028
+ }
1029
+ const mangled = makeScopedMangledName(scope, localIndex);
1030
+ localIndex++;
1031
+ entry.mangledName = mangled;
1032
+ scope.usedNames.add(mangled);
1033
+ for (const target of entry.targets) {
1034
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1035
+ target.shorthandProp.shorthand = false;
1036
+ target.shorthandProp.key = {
1037
+ type: "Identifier",
1038
+ name: entry.origName
1039
+ };
1040
+ }
1041
+ target.idNode.name = mangled;
1042
+ }
1043
+ }
1044
+ for (const child of scope.children) {
1045
+ assignScopeNamesTopDown(child);
1046
+ }
1047
+ }
1048
+ const rootScope = scopeRecords.get(ast);
1049
+ if (rootScope) {
1050
+ assignScopeNamesTopDown(rootScope);
1051
+ }
608
1052
  if (counter === 0) return 0;
609
- walk3.ancestor(ast, {
610
- AssignmentExpression(node, _state, ancestors) {
611
- const idNodes = [];
612
- collectPatternIdentifiers(node.left, idNodes);
613
- for (const idNode of idNodes) {
614
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
615
- if (resolved) {
616
- idNode.name = resolved;
1053
+ function resolveBinding(name, ancestors) {
1054
+ for (let i = ancestors.length - 1; i >= 0; i--) {
1055
+ const scope = scopeRecords.get(ancestors[i]);
1056
+ if (scope && scope.bindings.has(name)) {
1057
+ return scope.bindings.get(name);
1058
+ }
1059
+ }
1060
+ return null;
1061
+ }
1062
+ function renamePatternTargetsInScope(pattern, ancestors) {
1063
+ const targets = [];
1064
+ collectPatternTargets(pattern, targets);
1065
+ for (const target of targets) {
1066
+ const origName = target.idNode.name;
1067
+ const entry = resolveBinding(origName, ancestors);
1068
+ if (entry && entry.shouldMangle && entry.mangledName !== origName) {
1069
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1070
+ target.shorthandProp.shorthand = false;
1071
+ target.shorthandProp.key = {
1072
+ type: "Identifier",
1073
+ name: origName
1074
+ };
617
1075
  }
1076
+ target.idNode.name = entry.mangledName;
618
1077
  }
1078
+ }
1079
+ }
1080
+ walk3.ancestor(ast, {
1081
+ AssignmentExpression(node, _state, ancestors) {
1082
+ renamePatternTargetsInScope(node.left, ancestors);
619
1083
  },
620
1084
  ForInStatement(node, _state, ancestors) {
621
1085
  if (node.left && node.left.type !== "VariableDeclaration") {
622
- const idNodes = [];
623
- collectPatternIdentifiers(node.left, idNodes);
624
- for (const idNode of idNodes) {
625
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
626
- if (resolved) idNode.name = resolved;
627
- }
1086
+ renamePatternTargetsInScope(node.left, ancestors);
628
1087
  }
629
1088
  },
630
1089
  ForOfStatement(node, _state, ancestors) {
631
1090
  if (node.left && node.left.type !== "VariableDeclaration") {
632
- const idNodes = [];
633
- collectPatternIdentifiers(node.left, idNodes);
634
- for (const idNode of idNodes) {
635
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
636
- if (resolved) idNode.name = resolved;
637
- }
638
- }
639
- },
640
- Property(node, _state, ancestors) {
641
- if (node.shorthand && node.value?.type === "Identifier") {
642
- const resolved = resolveMangledName(node.value.name, ancestors, scopeMap);
643
- if (resolved) {
644
- node.shorthand = false;
645
- node.key = { type: "Identifier", name: node.value.name };
646
- }
1091
+ renamePatternTargetsInScope(node.left, ancestors);
647
1092
  }
648
1093
  },
649
1094
  Identifier(node, _state, ancestors) {
@@ -661,24 +1106,18 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
661
1106
  if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier") {
662
1107
  return;
663
1108
  }
664
- const resolved = resolveMangledName(node.name, ancestors, scopeMap);
665
- if (resolved) {
666
- node.name = resolved;
1109
+ const entry = resolveBinding(node.name, ancestors);
1110
+ if (entry && entry.shouldMangle && entry.mangledName !== node.name) {
1111
+ if (parent.type === "Property" && parent.shorthand && parent.value === node) {
1112
+ parent.shorthand = false;
1113
+ parent.key = { type: "Identifier", name: node.name };
1114
+ }
1115
+ node.name = entry.mangledName;
667
1116
  }
668
1117
  }
669
1118
  });
670
1119
  return counter;
671
1120
  }
672
- function resolveMangledName(name, ancestors, scopeMap) {
673
- for (let i = ancestors.length - 1; i >= 0; i--) {
674
- const anc = ancestors[i];
675
- const bindings = scopeMap.get(anc);
676
- if (bindings && bindings.has(name)) {
677
- return bindings.get(name);
678
- }
679
- }
680
- return null;
681
- }
682
1121
 
683
1122
  // src/ast/cold-flow-guard.ts
684
1123
  import * as walk4 from "acorn-walk";
@@ -715,8 +1154,13 @@ function createOpaqueGuardStatement(seed, fnIndex) {
715
1154
  right: { type: "Literal", value: wrongVal, raw: String(wrongVal) }
716
1155
  },
717
1156
  consequent: {
718
- type: "ReturnStatement",
719
- argument: null
1157
+ type: "ExpressionStatement",
1158
+ expression: {
1159
+ type: "UnaryExpression",
1160
+ operator: "void",
1161
+ prefix: true,
1162
+ argument: { type: "Literal", value: 0, raw: "0" }
1163
+ }
720
1164
  },
721
1165
  alternate: null
722
1166
  };
@@ -793,6 +1237,20 @@ function generateRuntimeShield(config) {
793
1237
  }
794
1238
 
795
1239
  // src/ast/index.ts
1240
+ function isAstAlreadyProtected(ast) {
1241
+ if (!ast || !Array.isArray(ast.body)) return false;
1242
+ return ast.body.some((stmt) => {
1243
+ if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1244
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
1245
+ )) {
1246
+ return true;
1247
+ }
1248
+ if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression" && stmt.expression.callee?.type === "FunctionExpression" && typeof stmt.expression.callee.id?.name === "string" && stmt.expression.callee.id.name.startsWith("_u$")) {
1249
+ return true;
1250
+ }
1251
+ return false;
1252
+ });
1253
+ }
796
1254
  function transformJavaScript(code, options = {}) {
797
1255
  const seed = options.seed ?? 2654435769;
798
1256
  const minStringLength = options.minStringLength ?? 4;
@@ -810,7 +1268,7 @@ function transformJavaScript(code, options = {}) {
810
1268
  };
811
1269
  }
812
1270
  const ast = parseJavaScriptAst(code);
813
- if (!ast) {
1271
+ if (!ast || isAstAlreadyProtected(ast)) {
814
1272
  return {
815
1273
  code,
816
1274
  encryptedStringsCount: 0,
@@ -875,8 +1333,9 @@ var unpeekPlugin = createUnplugin((options = {}) => {
875
1333
  return null;
876
1334
  }
877
1335
  const shouldInjectShield = injectRuntimeShield && (chunk.isEntry ?? true);
1336
+ const chunkSeed = computeFnv1aHash(chunk.fileName, baseSeed);
878
1337
  const result = transformJavaScript(code, {
879
- seed: baseSeed,
1338
+ seed: chunkSeed,
880
1339
  minStringLength,
881
1340
  filename: chunk.fileName,
882
1341
  injectRuntimeShield: shouldInjectShield,
@@ -885,11 +1344,11 @@ var unpeekPlugin = createUnplugin((options = {}) => {
885
1344
  let finalCode = result.code;
886
1345
  if (shouldInjectShield) {
887
1346
  const shield = generateRuntimeShield({
888
- seed: baseSeed,
1347
+ seed: chunkSeed,
889
1348
  deterrentMode,
890
1349
  expectedIntegrityHash: result.integrityToken
891
1350
  });
892
- if (shield.preambleCode && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
1351
+ if (shield.preambleCode && !finalCode.includes("(function _u$") && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
893
1352
  finalCode = `${shield.preambleCode}
894
1353
  ${finalCode}`;
895
1354
  }