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