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/browser.cjs CHANGED
@@ -134,15 +134,100 @@ function analyzeAstHotPaths(ast) {
134
134
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
135
135
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
136
136
  const directHotNodes = /* @__PURE__ */ new Set();
137
+ const serializedFunctionNodes = /* @__PURE__ */ new Set();
138
+ const serializerHelperNodes = /* @__PURE__ */ new Set();
137
139
  const allFunctions = [];
138
140
  const fnByName = /* @__PURE__ */ new Map();
139
141
  const scopeFunctions = /* @__PURE__ */ new Map();
140
142
  const fnScopeChain = /* @__PURE__ */ new Map();
143
+ const fnParams = /* @__PURE__ */ new Map();
144
+ const fnVarAliases = /* @__PURE__ */ new Map();
141
145
  const callerToCallees = /* @__PURE__ */ new Map();
146
+ const pendingSerializedRefs = [];
147
+ const allCallSites = [];
148
+ function ensureFnParams(fnNode) {
149
+ let paramSet = fnParams.get(fnNode);
150
+ if (!paramSet) {
151
+ paramSet = /* @__PURE__ */ new Set();
152
+ for (const p of fnNode.params || []) {
153
+ if (p?.type === "Identifier") {
154
+ paramSet.add(p.name);
155
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
156
+ paramSet.add(p.left.name);
157
+ }
158
+ }
159
+ fnParams.set(fnNode, paramSet);
160
+ }
161
+ return paramSet;
162
+ }
163
+ function recordVarAlias(scopeNode, varName, rhsName) {
164
+ let map = fnVarAliases.get(scopeNode);
165
+ if (!map) {
166
+ map = /* @__PURE__ */ new Map();
167
+ fnVarAliases.set(scopeNode, map);
168
+ }
169
+ map.set(varName, rhsName);
170
+ }
171
+ function resolveAliasTarget(scopeNode, identName) {
172
+ const map = fnVarAliases.get(scopeNode);
173
+ let cur = identName;
174
+ const seen = /* @__PURE__ */ new Set();
175
+ while (map && map.has(cur) && !seen.has(cur)) {
176
+ seen.add(cur);
177
+ cur = map.get(cur);
178
+ }
179
+ return cur;
180
+ }
181
+ function markSerializedFunction(node) {
182
+ serializedFunctionNodes.add(node);
183
+ hotFunctionNodes.add(node);
184
+ directHotNodes.add(node);
185
+ hotExemptNodes.add(node);
186
+ }
187
+ function findEnclosingFunction(ancestors, selfNode) {
188
+ for (let i = ancestors.length - 1; i >= 0; i--) {
189
+ if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
190
+ return ancestors[i];
191
+ }
192
+ }
193
+ return null;
194
+ }
195
+ function findOutermostModuleFunction(ancestors) {
196
+ const fnList = [];
197
+ for (let i = 0; i < ancestors.length; i++) {
198
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
199
+ fnList.push(ancestors[i]);
200
+ }
201
+ }
202
+ if (fnList.length === 0) return null;
203
+ if (fnList.length === 1) return fnList[0];
204
+ return fnList[1];
205
+ }
206
+ function isZeroArgIifeFactoryFunction(node) {
207
+ if (!node || node.params && node.params.length > 0) return false;
208
+ if (!node.body || node.body.type !== "BlockStatement") return false;
209
+ const stmts = (node.body.body || []).filter(
210
+ (s) => !(s.type === "ExpressionStatement" && s.directive)
211
+ );
212
+ if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
213
+ const retArg = stmts[0].argument;
214
+ if (!retArg || retArg.type !== "CallExpression") return false;
215
+ const callee = retArg.callee;
216
+ return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
217
+ }
142
218
  function registerFunctionNode(node, ancestors) {
143
219
  const name = getFunctionLabel(node, ancestors);
144
220
  allFunctions.push({ node, name });
145
221
  fnByName.set(name, node);
222
+ const paramSet = /* @__PURE__ */ new Set();
223
+ for (const p of node.params || []) {
224
+ if (p?.type === "Identifier") {
225
+ paramSet.add(p.name);
226
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
227
+ paramSet.add(p.left.name);
228
+ }
229
+ }
230
+ fnParams.set(node, paramSet);
146
231
  const enclosingScope = findEnclosingScopeNode(ancestors, node);
147
232
  let localMap = scopeFunctions.get(enclosingScope);
148
233
  if (!localMap) {
@@ -151,6 +236,22 @@ function analyzeAstHotPaths(ast) {
151
236
  }
152
237
  localMap.set(name, node);
153
238
  const parent = ancestors[ancestors.length - 2];
239
+ if (parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
240
+ fnByName.set(parent.id.name, node);
241
+ localMap.set(parent.id.name, node);
242
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
243
+ fnByName.set(parent.left.name, node);
244
+ localMap.set(parent.left.name, node);
245
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "MemberExpression" && !parent.left.computed && parent.left.property?.type === "Identifier") {
246
+ const propName = parent.left.property.name;
247
+ fnByName.set(propName, node);
248
+ localMap.set(propName, node);
249
+ if (parent.left.object?.type === "Identifier") {
250
+ const qual = `${parent.left.object.name}.${propName}`;
251
+ fnByName.set(qual, node);
252
+ localMap.set(qual, node);
253
+ }
254
+ }
154
255
  const grandParent = ancestors[ancestors.length - 3];
155
256
  const greatGrandParent = ancestors[ancestors.length - 4];
156
257
  if (parent?.type === "Property" && parent.key?.type === "Identifier" && grandParent?.type === "ObjectExpression" && greatGrandParent?.type === "VariableDeclarator" && greatGrandParent.id?.type === "Identifier") {
@@ -160,7 +261,7 @@ function analyzeAstHotPaths(ast) {
160
261
  }
161
262
  const chain = [];
162
263
  for (let i = ancestors.length - 1; i >= 0; i--) {
163
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program") {
264
+ if (ancestors[i] !== node && (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program")) {
164
265
  chain.push(ancestors[i]);
165
266
  }
166
267
  }
@@ -169,8 +270,13 @@ function analyzeAstHotPaths(ast) {
169
270
  hotFunctionNodes.add(node);
170
271
  directHotNodes.add(node);
171
272
  }
273
+ if (isZeroArgIifeFactoryFunction(node)) {
274
+ markSerializedFunction(node);
275
+ }
172
276
  }
173
277
  function resolveCalleeNode(callerNode, calleeKey) {
278
+ const directLocal = scopeFunctions.get(callerNode)?.get(calleeKey);
279
+ if (directLocal) return directLocal;
174
280
  const chain = fnScopeChain.get(callerNode);
175
281
  if (chain) {
176
282
  for (const scopeNode of chain) {
@@ -181,6 +287,25 @@ function analyzeAstHotPaths(ast) {
181
287
  }
182
288
  return fnByName.get(calleeKey);
183
289
  }
290
+ function queueSerializedTarget(target, enclosingScope) {
291
+ if (!target) return;
292
+ if (FUNCTION_NODE_TYPES.has(target.type)) {
293
+ markSerializedFunction(target);
294
+ } else if (target.type === "Identifier") {
295
+ pendingSerializedRefs.push({ scopeNode: enclosingScope, name: target.name });
296
+ } else if (target.type === "MemberExpression" && !target.computed && target.property?.type === "Identifier") {
297
+ pendingSerializedRefs.push({
298
+ scopeNode: enclosingScope,
299
+ name: target.property.name
300
+ });
301
+ if (target.object?.type === "Identifier") {
302
+ pendingSerializedRefs.push({
303
+ scopeNode: enclosingScope,
304
+ name: `${target.object.name}.${target.property.name}`
305
+ });
306
+ }
307
+ }
308
+ }
184
309
  walk.ancestor(ast, {
185
310
  FunctionDeclaration(node, _state, ancestors) {
186
311
  registerFunctionNode(node, ancestors);
@@ -191,6 +316,59 @@ function analyzeAstHotPaths(ast) {
191
316
  ArrowFunctionExpression(node, _state, ancestors) {
192
317
  registerFunctionNode(node, ancestors);
193
318
  },
319
+ VariableDeclarator(node, _state, ancestors) {
320
+ if (node.id?.type === "Identifier" && node.init?.type === "Identifier") {
321
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
322
+ recordVarAlias(scopeNode, node.id.name, node.init.name);
323
+ }
324
+ },
325
+ AssignmentExpression(node, _state, ancestors) {
326
+ const left = node.left;
327
+ if (left?.type === "Identifier" && node.right?.type === "Identifier") {
328
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
329
+ recordVarAlias(scopeNode, left.name, node.right.name);
330
+ }
331
+ const isBareOnMessage = left?.type === "Identifier" && left.name === "onmessage";
332
+ const isSelfOnMessage = left?.type === "MemberExpression" && !left.computed && left.object?.type === "Identifier" && left.object.name === "self" && left.property?.type === "Identifier" && left.property.name === "onmessage";
333
+ if (isBareOnMessage || isSelfOnMessage) {
334
+ const enclosingFn = findEnclosingFunction(ancestors);
335
+ if (enclosingFn) {
336
+ markSerializedFunction(enclosingFn);
337
+ }
338
+ const outerFn = findOutermostModuleFunction(ancestors);
339
+ if (outerFn) {
340
+ markSerializedFunction(outerFn);
341
+ }
342
+ const scopeNode = enclosingFn ?? ast;
343
+ queueSerializedTarget(node.right, scopeNode);
344
+ }
345
+ },
346
+ ObjectExpression(node, _state, ancestors) {
347
+ const props = node.properties || [];
348
+ const propMap = /* @__PURE__ */ new Map();
349
+ for (const p of props) {
350
+ if (p?.type === "Property" && !p.computed) {
351
+ const keyName = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : "";
352
+ if (keyName) {
353
+ propMap.set(keyName, p.value);
354
+ }
355
+ }
356
+ }
357
+ const hasWorkerDescriptorShape = propMap.has("init") && propMap.has("dependencies") || propMap.has("isWorkerModule") || propMap.has("getTransferables") && (propMap.has("init") || propMap.has("dependencies"));
358
+ if (hasWorkerDescriptorShape) {
359
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
360
+ for (const key of ["init", "getTransferables", "worker"]) {
361
+ const val = propMap.get(key);
362
+ if (val) queueSerializedTarget(val, scopeNode);
363
+ }
364
+ const deps = propMap.get("dependencies");
365
+ if (deps?.type === "ArrayExpression") {
366
+ for (const el of deps.elements || []) {
367
+ if (el) queueSerializedTarget(el, scopeNode);
368
+ }
369
+ }
370
+ }
371
+ },
194
372
  CallExpression(node, _state, ancestors) {
195
373
  const callee = node.callee;
196
374
  let calleeName = "";
@@ -207,38 +385,76 @@ function analyzeAstHotPaths(ast) {
207
385
  qualifiedCall = memberProp;
208
386
  }
209
387
  }
388
+ const enclosingFn = findEnclosingFunction(ancestors);
389
+ const currentScope = enclosingFn ?? ast;
210
390
  if (qualifiedCall || memberProp) {
211
- for (let i = ancestors.length - 1; i >= 0; i--) {
212
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
213
- let set = callerToCallees.get(ancestors[i]);
214
- if (!set) {
215
- set = /* @__PURE__ */ new Set();
216
- callerToCallees.set(ancestors[i], set);
217
- }
218
- if (qualifiedCall) set.add(qualifiedCall);
219
- if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
220
- set.add(memberProp);
221
- }
222
- break;
391
+ allCallSites.push({
392
+ scopeNode: currentScope,
393
+ calleeKey: qualifiedCall || memberProp,
394
+ args: node.arguments || []
395
+ });
396
+ if (enclosingFn) {
397
+ let set = callerToCallees.get(enclosingFn);
398
+ if (!set) {
399
+ set = /* @__PURE__ */ new Set();
400
+ callerToCallees.set(enclosingFn, set);
401
+ }
402
+ if (qualifiedCall) set.add(qualifiedCall);
403
+ if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
404
+ set.add(memberProp);
405
+ }
406
+ }
407
+ }
408
+ if (memberProp === "toString" && (!node.arguments || node.arguments.length === 0) && callee?.type === "MemberExpression") {
409
+ const targetObj = callee.object;
410
+ queueSerializedTarget(targetObj, currentScope);
411
+ if (targetObj?.type === "Identifier" && enclosingFn) {
412
+ const resolvedName = resolveAliasTarget(enclosingFn, targetObj.name);
413
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
414
+ serializerHelperNodes.add(enclosingFn);
415
+ }
416
+ if (resolvedName !== targetObj.name) {
417
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
418
+ }
419
+ }
420
+ }
421
+ 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) {
422
+ const firstArg = node.arguments[0];
423
+ queueSerializedTarget(firstArg, currentScope);
424
+ if (firstArg?.type === "Identifier" && enclosingFn) {
425
+ const resolvedName = resolveAliasTarget(enclosingFn, firstArg.name);
426
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
427
+ serializerHelperNodes.add(enclosingFn);
428
+ }
429
+ if (resolvedName !== firstArg.name) {
430
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
223
431
  }
224
432
  }
225
433
  }
434
+ if (calleeName === "importScripts" || memberProp === "importScripts" && callee?.object?.type === "Identifier" && callee.object.name === "self") {
435
+ if (enclosingFn) markSerializedFunction(enclosingFn);
436
+ const outerFn = findOutermostModuleFunction(ancestors);
437
+ if (outerFn) markSerializedFunction(outerFn);
438
+ }
226
439
  if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame" || calleeName === "cancelAnimationFrame" || memberProp === "cancelAnimationFrame") {
227
440
  for (const arg of node.arguments || []) {
228
441
  if (FUNCTION_NODE_TYPES.has(arg.type)) {
229
442
  hotFunctionNodes.add(arg);
230
443
  directHotNodes.add(arg);
231
444
  hotExemptNodes.add(arg);
445
+ } else if (arg?.type === "Identifier") {
446
+ allCallSites.push({
447
+ scopeNode: currentScope,
448
+ calleeKey: arg.name,
449
+ args: [arg]
450
+ });
232
451
  }
233
452
  }
234
453
  }
235
454
  if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
236
- for (let i = ancestors.length - 1; i >= 0; i--) {
237
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
238
- hotFunctionNodes.add(ancestors[i]);
239
- directHotNodes.add(ancestors[i]);
240
- break;
241
- }
455
+ if (enclosingFn) {
456
+ hotFunctionNodes.add(enclosingFn);
457
+ directHotNodes.add(enclosingFn);
242
458
  }
243
459
  }
244
460
  },
@@ -263,10 +479,41 @@ function analyzeAstHotPaths(ast) {
263
479
  markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
264
480
  }
265
481
  });
482
+ for (const callSite of allCallSites) {
483
+ const resolvedCallee = resolveCalleeNode(callSite.scopeNode, callSite.calleeKey);
484
+ if (resolvedCallee && serializerHelperNodes.has(resolvedCallee)) {
485
+ for (const arg of callSite.args) {
486
+ queueSerializedTarget(arg, callSite.scopeNode);
487
+ }
488
+ }
489
+ }
490
+ for (const ref of pendingSerializedRefs) {
491
+ const targetNode = resolveCalleeNode(ref.scopeNode, ref.name);
492
+ if (targetNode) {
493
+ markSerializedFunction(targetNode);
494
+ }
495
+ }
266
496
  const forwardHotSet = new Set(directHotNodes);
267
497
  let forwardChanged = true;
268
498
  while (forwardChanged) {
269
499
  forwardChanged = false;
500
+ for (const fn of allFunctions) {
501
+ if (forwardHotSet.has(fn.node)) continue;
502
+ const chain = fnScopeChain.get(fn.node);
503
+ if (!chain) continue;
504
+ for (const anc of chain) {
505
+ if (anc !== fn.node && (serializedFunctionNodes.has(anc) || forwardHotSet.has(anc))) {
506
+ forwardHotSet.add(fn.node);
507
+ hotFunctionNodes.add(fn.node);
508
+ hotExemptNodes.add(fn.node);
509
+ if (serializedFunctionNodes.has(anc)) {
510
+ serializedFunctionNodes.add(fn.node);
511
+ }
512
+ forwardChanged = true;
513
+ break;
514
+ }
515
+ }
516
+ }
270
517
  for (const callerNode of Array.from(forwardHotSet)) {
271
518
  const calleeNames = callerToCallees.get(callerNode);
272
519
  if (!calleeNames) continue;
@@ -276,6 +523,9 @@ function analyzeAstHotPaths(ast) {
276
523
  forwardHotSet.add(targetNode);
277
524
  hotFunctionNodes.add(targetNode);
278
525
  hotExemptNodes.add(targetNode);
526
+ if (serializedFunctionNodes.has(callerNode)) {
527
+ serializedFunctionNodes.add(targetNode);
528
+ }
279
529
  forwardChanged = true;
280
530
  }
281
531
  }
@@ -350,7 +600,7 @@ var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
350
600
  "use asm"
351
601
  ]);
352
602
  var HELPER_TEMPLATE = acorn2.parse(
353
- `const _ = [].map(function f(a) {
603
+ `var _ = [].map(function f(a) {
354
604
  var s = "";
355
605
  for (var j = 0; j < a.length; j++) {
356
606
  s += String.fromCharCode(a.charCodeAt(j) ^ (((0 ^ ((a._u || /\\n/.test(f) * 14) | ((j & 1) * 0))) & 30) | 1));
@@ -396,8 +646,17 @@ function encodeStringWithSeed(str, mask, step) {
396
646
  return out;
397
647
  }
398
648
  function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
399
- const suffix = ((seed >>> 0) % 255).toString(36);
400
- const cacheVarName = `_uC${suffix}`;
649
+ const alreadyVaulted = ast.body.some(
650
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
651
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
652
+ )
653
+ );
654
+ if (alreadyVaulted) {
655
+ return {
656
+ encryptedStringsCount: 0,
657
+ integrityToken: computeFnv1aHash("already-vaulted", seed)
658
+ };
659
+ }
401
660
  const mask = seed >>> 0 & 30 | 3;
402
661
  const step = (seed >>> 5 & 7) * 2 + 3;
403
662
  const stringToIndex = /* @__PURE__ */ new Map();
@@ -443,6 +702,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
443
702
  integrityToken: computeFnv1aHash("empty", seed)
444
703
  };
445
704
  }
705
+ const serializedTable = JSON.stringify(encryptedPayloads);
706
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
707
+ const suffix = computeFnv1aHash(`vault:${seed}`, integrityToken).toString(36);
708
+ const cacheVarName = `_uC${suffix}`;
446
709
  for (const { node } of targetsToReplace) {
447
710
  const idx = stringToIndex.get(node.value);
448
711
  node.type = "MemberExpression";
@@ -460,8 +723,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
460
723
  delete node.value;
461
724
  delete node.raw;
462
725
  }
463
- const serializedTable = JSON.stringify(encryptedPayloads);
464
- const integrityToken = computeFnv1aHash(serializedTable, seed);
465
726
  const helperStmt = createVaultHelperAst(
466
727
  cacheVarName,
467
728
  encryptedPayloads,
@@ -533,167 +794,351 @@ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
533
794
  "FunctionExpression",
534
795
  "ArrowFunctionExpression"
535
796
  ]);
536
- function collectPatternIdentifiers(pattern, out) {
797
+ var LEXICAL_SCOPE_TYPES = /* @__PURE__ */ new Set([
798
+ "Program",
799
+ "FunctionDeclaration",
800
+ "FunctionExpression",
801
+ "ArrowFunctionExpression",
802
+ "BlockStatement",
803
+ "ForStatement",
804
+ "ForInStatement",
805
+ "ForOfStatement",
806
+ "SwitchStatement",
807
+ "CatchClause",
808
+ "ClassDeclaration",
809
+ "ClassExpression"
810
+ ]);
811
+ function collectPatternTargets(pattern, out, shorthandProp) {
537
812
  if (!pattern) return;
538
813
  switch (pattern.type) {
539
814
  case "Identifier":
540
- out.push(pattern);
815
+ out.push({ idNode: pattern, shorthandProp });
541
816
  break;
542
817
  case "AssignmentPattern":
543
- collectPatternIdentifiers(pattern.left, out);
818
+ collectPatternTargets(pattern.left, out, shorthandProp);
544
819
  break;
545
820
  case "RestElement":
546
- collectPatternIdentifiers(pattern.argument, out);
821
+ collectPatternTargets(pattern.argument, out);
547
822
  break;
548
823
  case "ArrayPattern":
549
824
  for (const el of pattern.elements || []) {
550
- if (el) collectPatternIdentifiers(el, out);
825
+ if (el) collectPatternTargets(el, out);
551
826
  }
552
827
  break;
553
828
  case "ObjectPattern":
554
829
  for (const prop of pattern.properties || []) {
555
830
  if (prop.type === "Property") {
556
- if (prop.shorthand) {
557
- prop.shorthand = false;
558
- prop.key = { ...prop.key };
559
- }
560
- collectPatternIdentifiers(prop.value, out);
831
+ collectPatternTargets(
832
+ prop.value,
833
+ out,
834
+ prop.shorthand ? prop : void 0
835
+ );
561
836
  } else if (prop.type === "RestElement") {
562
- collectPatternIdentifiers(prop.argument, out);
837
+ collectPatternTargets(prop.argument, out);
563
838
  }
564
839
  }
565
840
  break;
566
841
  }
567
842
  }
843
+ function isMangleableName(origName) {
844
+ return !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x");
845
+ }
568
846
  function applyPolymorphicMangler(ast, seed = 2654435769) {
569
- const scopeMap = /* @__PURE__ */ new Map();
570
- const scopeDepthMap = /* @__PURE__ */ new Map();
847
+ const scopeRecords = /* @__PURE__ */ new Map();
848
+ const existingIdentifiers = /* @__PURE__ */ new Set();
571
849
  let counter = 0;
572
- function makeScopedMangledName(scopeDepth, localIndex, usedValues) {
573
- counter++;
574
- let salt = 0;
575
- while (true) {
576
- const h = computeFnv1aHash(`s${scopeDepth}:i${localIndex}:${salt}`, seed);
577
- const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
578
- if (!usedValues.has(candidate)) {
579
- return candidate;
850
+ function ensureScopeChain(ancestors) {
851
+ let prevScope = null;
852
+ for (let i = 0; i < ancestors.length; i++) {
853
+ const node = ancestors[i];
854
+ if (!LEXICAL_SCOPE_TYPES.has(node.type)) continue;
855
+ let record = scopeRecords.get(node);
856
+ if (!record) {
857
+ const isFn = FUNCTION_TYPES.has(node.type);
858
+ const depth = prevScope ? prevScope.depth + (isFn ? 1 : 0) : 0;
859
+ record = {
860
+ node,
861
+ parent: prevScope,
862
+ children: [],
863
+ depth: Math.max(1, depth),
864
+ bindings: /* @__PURE__ */ new Map(),
865
+ usedNames: /* @__PURE__ */ new Set()
866
+ };
867
+ scopeRecords.set(node, record);
868
+ if (prevScope) {
869
+ prevScope.children.push(record);
870
+ }
580
871
  }
581
- salt++;
872
+ prevScope = record;
582
873
  }
874
+ return prevScope;
583
875
  }
584
- function countFunctionDepth(ancestors) {
585
- let depth = 0;
586
- for (let i = 0; i < ancestors.length; i++) {
876
+ function findEnclosingFunctionNode(ancestors) {
877
+ for (let i = ancestors.length - 1; i >= 0; i--) {
587
878
  if (FUNCTION_TYPES.has(ancestors[i].type)) {
588
- depth++;
879
+ return ancestors[i];
589
880
  }
590
881
  }
591
- return Math.max(1, depth);
882
+ return null;
592
883
  }
593
- function findEnclosingFunction(ancestors) {
884
+ function findEnclosingLexicalNode(ancestors) {
594
885
  for (let i = ancestors.length - 1; i >= 0; i--) {
595
- if (FUNCTION_TYPES.has(ancestors[i].type)) {
886
+ if (LEXICAL_SCOPE_TYPES.has(ancestors[i].type)) {
596
887
  return ancestors[i];
597
888
  }
598
889
  }
599
- return null;
890
+ return ancestors[0];
600
891
  }
601
- function registerBindingAndMutateDeclSite(idNode, bindings, scopeDepth) {
602
- const origName = idNode.name;
603
- if (RESERVED_IDENTIFIERS.has(origName) || origName.startsWith("_u") || origName.startsWith("_0x")) {
604
- return;
892
+ function registerBindingTarget(scopeNode, target, shouldMangle) {
893
+ const scope = scopeRecords.get(scopeNode);
894
+ if (!scope) return;
895
+ const origName = target.idNode.name;
896
+ const canMangle = shouldMangle && isMangleableName(origName);
897
+ let entry = scope.bindings.get(origName);
898
+ if (!entry) {
899
+ entry = {
900
+ origName,
901
+ shouldMangle: canMangle,
902
+ targets: [target],
903
+ mangledName: origName
904
+ };
905
+ scope.bindings.set(origName, entry);
906
+ } else {
907
+ if (!canMangle) {
908
+ entry.shouldMangle = false;
909
+ }
910
+ entry.targets.push(target);
605
911
  }
606
- let mangled = bindings.get(origName);
607
- if (!mangled) {
608
- const usedValues = new Set(bindings.values());
609
- mangled = makeScopedMangledName(scopeDepth, bindings.size, usedValues);
610
- bindings.set(origName, mangled);
912
+ }
913
+ function registerBarrierName(scopeNode, origName) {
914
+ const scope = scopeRecords.get(scopeNode);
915
+ if (!scope) return;
916
+ let entry = scope.bindings.get(origName);
917
+ if (!entry) {
918
+ entry = {
919
+ origName,
920
+ shouldMangle: false,
921
+ targets: [],
922
+ mangledName: origName
923
+ };
924
+ scope.bindings.set(origName, entry);
925
+ } else {
926
+ entry.shouldMangle = false;
611
927
  }
612
- idNode.name = mangled;
613
928
  }
614
929
  function registerFunctionParams(fnNode, ancestors) {
615
- let bindings = scopeMap.get(fnNode);
616
- const depth = countFunctionDepth(ancestors);
617
- scopeDepthMap.set(fnNode, depth);
618
- if (!bindings) {
619
- bindings = /* @__PURE__ */ new Map();
620
- scopeMap.set(fnNode, bindings);
621
- }
930
+ ensureScopeChain(ancestors);
622
931
  for (const param of fnNode.params || []) {
623
- const idNodes = [];
624
- collectPatternIdentifiers(param, idNodes);
625
- for (const idNode of idNodes) {
626
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
932
+ const targets = [];
933
+ collectPatternTargets(param, targets);
934
+ for (const target of targets) {
935
+ registerBindingTarget(fnNode, target, true);
627
936
  }
628
937
  }
629
938
  }
939
+ ensureScopeChain([ast]);
630
940
  walk3.ancestor(ast, {
941
+ Identifier(node) {
942
+ if (typeof node.name === "string") {
943
+ existingIdentifiers.add(node.name);
944
+ }
945
+ },
946
+ BlockStatement(_node, _state, ancestors) {
947
+ ensureScopeChain(ancestors);
948
+ },
949
+ ForStatement(_node, _state, ancestors) {
950
+ ensureScopeChain(ancestors);
951
+ },
952
+ ForInStatement(_node, _state, ancestors) {
953
+ ensureScopeChain(ancestors);
954
+ },
955
+ ForOfStatement(_node, _state, ancestors) {
956
+ ensureScopeChain(ancestors);
957
+ },
958
+ SwitchStatement(_node, _state, ancestors) {
959
+ ensureScopeChain(ancestors);
960
+ },
631
961
  FunctionDeclaration(node, _state, ancestors) {
632
962
  registerFunctionParams(node, ancestors);
963
+ if (node.id?.type === "Identifier") {
964
+ const parentAncestors = ancestors.slice(0, -1);
965
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
966
+ const fnNode = findEnclosingFunctionNode(parentAncestors) ?? ast;
967
+ registerBarrierName(lexNode, node.id.name);
968
+ if (lexNode === fnNode.body || fnNode === ast) {
969
+ registerBarrierName(fnNode, node.id.name);
970
+ }
971
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
972
+ registerBarrierName(node, node.id.name);
973
+ }
974
+ }
633
975
  },
634
976
  FunctionExpression(node, _state, ancestors) {
635
977
  registerFunctionParams(node, ancestors);
978
+ if (node.id?.type === "Identifier") {
979
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
980
+ registerBarrierName(node, node.id.name);
981
+ }
982
+ }
636
983
  },
637
984
  ArrowFunctionExpression(node, _state, ancestors) {
638
985
  registerFunctionParams(node, ancestors);
639
986
  },
987
+ ClassDeclaration(node, _state, ancestors) {
988
+ ensureScopeChain(ancestors);
989
+ if (node.id?.type === "Identifier") {
990
+ const parentAncestors = ancestors.slice(0, -1);
991
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
992
+ registerBarrierName(lexNode, node.id.name);
993
+ registerBarrierName(node, node.id.name);
994
+ }
995
+ },
996
+ ClassExpression(node, _state, ancestors) {
997
+ ensureScopeChain(ancestors);
998
+ if (node.id?.type === "Identifier") {
999
+ registerBarrierName(node, node.id.name);
1000
+ }
1001
+ },
1002
+ CatchClause(node, _state, ancestors) {
1003
+ ensureScopeChain(ancestors);
1004
+ if (node.param) {
1005
+ const targets = [];
1006
+ collectPatternTargets(node.param, targets);
1007
+ for (const target of targets) {
1008
+ registerBindingTarget(node, target, true);
1009
+ }
1010
+ }
1011
+ },
640
1012
  VariableDeclaration(node, _state, ancestors) {
641
- const fnScope = findEnclosingFunction(ancestors);
642
- if (!fnScope) return;
643
- let bindings = scopeMap.get(fnScope);
644
- const depth = scopeDepthMap.get(fnScope) ?? countFunctionDepth(ancestors);
645
- if (!bindings) {
646
- bindings = /* @__PURE__ */ new Map();
647
- scopeMap.set(fnScope, bindings);
1013
+ ensureScopeChain(ancestors);
1014
+ const fnScope = findEnclosingFunctionNode(ancestors);
1015
+ if (!fnScope) {
1016
+ for (const decl of node.declarations || []) {
1017
+ const targets = [];
1018
+ collectPatternTargets(decl.id, targets);
1019
+ for (const target of targets) {
1020
+ registerBarrierName(ast, target.idNode.name);
1021
+ }
1022
+ }
1023
+ return;
648
1024
  }
1025
+ const targetScopeNode = node.kind === "var" ? fnScope : findEnclosingLexicalNode(ancestors);
649
1026
  for (const decl of node.declarations || []) {
650
- const idNodes = [];
651
- collectPatternIdentifiers(decl.id, idNodes);
652
- for (const idNode of idNodes) {
653
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
1027
+ const targets = [];
1028
+ collectPatternTargets(decl.id, targets);
1029
+ for (const target of targets) {
1030
+ const origName = target.idNode.name;
1031
+ if (node.kind === "var") {
1032
+ for (let i = ancestors.length - 1; i >= 0; i--) {
1033
+ if (ancestors[i] === fnScope) break;
1034
+ if (ancestors[i].type === "CatchClause") {
1035
+ const catchScope = scopeRecords.get(ancestors[i]);
1036
+ if (catchScope?.bindings.has(origName)) {
1037
+ registerBarrierName(ancestors[i], origName);
1038
+ registerBarrierName(fnScope, origName);
1039
+ }
1040
+ }
1041
+ }
1042
+ }
1043
+ registerBindingTarget(targetScopeNode, target, true);
654
1044
  }
655
1045
  }
656
1046
  }
657
1047
  });
1048
+ function isNameUsedInScopeOrAncestors(candidate, scope) {
1049
+ if (existingIdentifiers.has(candidate)) return true;
1050
+ let curr = scope;
1051
+ while (curr) {
1052
+ if (curr.usedNames.has(candidate) || curr.bindings.has(candidate)) {
1053
+ return true;
1054
+ }
1055
+ curr = curr.parent;
1056
+ }
1057
+ return false;
1058
+ }
1059
+ function makeScopedMangledName(scope, localIndex) {
1060
+ counter++;
1061
+ let salt = 0;
1062
+ while (true) {
1063
+ const h = computeFnv1aHash(`s${scope.depth}:i${localIndex}:${salt}`, seed);
1064
+ const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
1065
+ if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
1066
+ return candidate;
1067
+ }
1068
+ salt++;
1069
+ }
1070
+ }
1071
+ function assignScopeNamesTopDown(scope) {
1072
+ let localIndex = 0;
1073
+ for (const entry of scope.bindings.values()) {
1074
+ if (!entry.shouldMangle) {
1075
+ entry.mangledName = entry.origName;
1076
+ scope.usedNames.add(entry.origName);
1077
+ continue;
1078
+ }
1079
+ const mangled = makeScopedMangledName(scope, localIndex);
1080
+ localIndex++;
1081
+ entry.mangledName = mangled;
1082
+ scope.usedNames.add(mangled);
1083
+ for (const target of entry.targets) {
1084
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1085
+ target.shorthandProp.shorthand = false;
1086
+ target.shorthandProp.key = {
1087
+ type: "Identifier",
1088
+ name: entry.origName
1089
+ };
1090
+ }
1091
+ target.idNode.name = mangled;
1092
+ }
1093
+ }
1094
+ for (const child of scope.children) {
1095
+ assignScopeNamesTopDown(child);
1096
+ }
1097
+ }
1098
+ const rootScope = scopeRecords.get(ast);
1099
+ if (rootScope) {
1100
+ assignScopeNamesTopDown(rootScope);
1101
+ }
658
1102
  if (counter === 0) return 0;
659
- walk3.ancestor(ast, {
660
- AssignmentExpression(node, _state, ancestors) {
661
- const idNodes = [];
662
- collectPatternIdentifiers(node.left, idNodes);
663
- for (const idNode of idNodes) {
664
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
665
- if (resolved) {
666
- idNode.name = resolved;
1103
+ function resolveBinding(name, ancestors) {
1104
+ for (let i = ancestors.length - 1; i >= 0; i--) {
1105
+ const scope = scopeRecords.get(ancestors[i]);
1106
+ if (scope && scope.bindings.has(name)) {
1107
+ return scope.bindings.get(name);
1108
+ }
1109
+ }
1110
+ return null;
1111
+ }
1112
+ function renamePatternTargetsInScope(pattern, ancestors) {
1113
+ const targets = [];
1114
+ collectPatternTargets(pattern, targets);
1115
+ for (const target of targets) {
1116
+ const origName = target.idNode.name;
1117
+ const entry = resolveBinding(origName, ancestors);
1118
+ if (entry && entry.shouldMangle && entry.mangledName !== origName) {
1119
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1120
+ target.shorthandProp.shorthand = false;
1121
+ target.shorthandProp.key = {
1122
+ type: "Identifier",
1123
+ name: origName
1124
+ };
667
1125
  }
1126
+ target.idNode.name = entry.mangledName;
668
1127
  }
1128
+ }
1129
+ }
1130
+ walk3.ancestor(ast, {
1131
+ AssignmentExpression(node, _state, ancestors) {
1132
+ renamePatternTargetsInScope(node.left, ancestors);
669
1133
  },
670
1134
  ForInStatement(node, _state, ancestors) {
671
1135
  if (node.left && node.left.type !== "VariableDeclaration") {
672
- const idNodes = [];
673
- collectPatternIdentifiers(node.left, idNodes);
674
- for (const idNode of idNodes) {
675
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
676
- if (resolved) idNode.name = resolved;
677
- }
1136
+ renamePatternTargetsInScope(node.left, ancestors);
678
1137
  }
679
1138
  },
680
1139
  ForOfStatement(node, _state, ancestors) {
681
1140
  if (node.left && node.left.type !== "VariableDeclaration") {
682
- const idNodes = [];
683
- collectPatternIdentifiers(node.left, idNodes);
684
- for (const idNode of idNodes) {
685
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
686
- if (resolved) idNode.name = resolved;
687
- }
688
- }
689
- },
690
- Property(node, _state, ancestors) {
691
- if (node.shorthand && node.value?.type === "Identifier") {
692
- const resolved = resolveMangledName(node.value.name, ancestors, scopeMap);
693
- if (resolved) {
694
- node.shorthand = false;
695
- node.key = { type: "Identifier", name: node.value.name };
696
- }
1141
+ renamePatternTargetsInScope(node.left, ancestors);
697
1142
  }
698
1143
  },
699
1144
  Identifier(node, _state, ancestors) {
@@ -711,24 +1156,18 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
711
1156
  if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier") {
712
1157
  return;
713
1158
  }
714
- const resolved = resolveMangledName(node.name, ancestors, scopeMap);
715
- if (resolved) {
716
- node.name = resolved;
1159
+ const entry = resolveBinding(node.name, ancestors);
1160
+ if (entry && entry.shouldMangle && entry.mangledName !== node.name) {
1161
+ if (parent.type === "Property" && parent.shorthand && parent.value === node) {
1162
+ parent.shorthand = false;
1163
+ parent.key = { type: "Identifier", name: node.name };
1164
+ }
1165
+ node.name = entry.mangledName;
717
1166
  }
718
1167
  }
719
1168
  });
720
1169
  return counter;
721
1170
  }
722
- function resolveMangledName(name, ancestors, scopeMap) {
723
- for (let i = ancestors.length - 1; i >= 0; i--) {
724
- const anc = ancestors[i];
725
- const bindings = scopeMap.get(anc);
726
- if (bindings && bindings.has(name)) {
727
- return bindings.get(name);
728
- }
729
- }
730
- return null;
731
- }
732
1171
 
733
1172
  // src/ast/cold-flow-guard.ts
734
1173
  var walk4 = __toESM(require("acorn-walk"), 1);
@@ -765,8 +1204,13 @@ function createOpaqueGuardStatement(seed, fnIndex) {
765
1204
  right: { type: "Literal", value: wrongVal, raw: String(wrongVal) }
766
1205
  },
767
1206
  consequent: {
768
- type: "ReturnStatement",
769
- argument: null
1207
+ type: "ExpressionStatement",
1208
+ expression: {
1209
+ type: "UnaryExpression",
1210
+ operator: "void",
1211
+ prefix: true,
1212
+ argument: { type: "Literal", value: 0, raw: "0" }
1213
+ }
770
1214
  },
771
1215
  alternate: null
772
1216
  };
@@ -847,6 +1291,20 @@ function generateRuntimeShield(config) {
847
1291
  }
848
1292
 
849
1293
  // src/ast/index.ts
1294
+ function isAstAlreadyProtected(ast) {
1295
+ if (!ast || !Array.isArray(ast.body)) return false;
1296
+ return ast.body.some((stmt) => {
1297
+ if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1298
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
1299
+ )) {
1300
+ return true;
1301
+ }
1302
+ 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$")) {
1303
+ return true;
1304
+ }
1305
+ return false;
1306
+ });
1307
+ }
850
1308
  function transformJavaScript(code, options = {}) {
851
1309
  const seed = options.seed ?? 2654435769;
852
1310
  const minStringLength = options.minStringLength ?? 4;
@@ -864,7 +1322,7 @@ function transformJavaScript(code, options = {}) {
864
1322
  };
865
1323
  }
866
1324
  const ast = parseJavaScriptAst(code);
867
- if (!ast) {
1325
+ if (!ast || isAstAlreadyProtected(ast)) {
868
1326
  return {
869
1327
  code,
870
1328
  encryptedStringsCount: 0,