unpeek 1.7.2 → 1.8.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.
Files changed (63) hide show
  1. package/dist/ast/index.cjs +2278 -386
  2. package/dist/ast/index.cjs.map +1 -1
  3. package/dist/ast/index.d.cts +69 -1
  4. package/dist/ast/index.d.ts +69 -1
  5. package/dist/ast/index.js +2266 -385
  6. package/dist/ast/index.js.map +1 -1
  7. package/dist/browser.cjs +2265 -393
  8. package/dist/browser.cjs.map +1 -1
  9. package/dist/browser.d.cts +2 -1
  10. package/dist/browser.d.ts +2 -1
  11. package/dist/browser.js +2260 -388
  12. package/dist/browser.js.map +1 -1
  13. package/dist/bundler/unplugin.cjs +2259 -385
  14. package/dist/bundler/unplugin.cjs.map +1 -1
  15. package/dist/bundler/unplugin.js +2258 -384
  16. package/dist/bundler/unplugin.js.map +1 -1
  17. package/dist/cli/index.cjs +2292 -396
  18. package/dist/cli/index.cjs.map +1 -1
  19. package/dist/cli/index.js +2292 -396
  20. package/dist/cli/index.js.map +1 -1
  21. package/dist/cli/protect.cjs +2284 -391
  22. package/dist/cli/protect.cjs.map +1 -1
  23. package/dist/cli/protect.js +2285 -392
  24. package/dist/cli/protect.js.map +1 -1
  25. package/dist/esbuild.cjs +2259 -385
  26. package/dist/esbuild.cjs.map +1 -1
  27. package/dist/esbuild.d.cts +1 -1
  28. package/dist/esbuild.d.ts +1 -1
  29. package/dist/esbuild.js +2258 -384
  30. package/dist/esbuild.js.map +1 -1
  31. package/dist/index.cjs +2309 -411
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +2 -1
  34. package/dist/index.d.ts +2 -1
  35. package/dist/index.js +2296 -398
  36. package/dist/index.js.map +1 -1
  37. package/dist/rollup.cjs +2259 -385
  38. package/dist/rollup.cjs.map +1 -1
  39. package/dist/rollup.d.cts +1 -1
  40. package/dist/rollup.d.ts +1 -1
  41. package/dist/rollup.js +2258 -384
  42. package/dist/rollup.js.map +1 -1
  43. package/dist/runtime/index.cjs +366 -8
  44. package/dist/runtime/index.cjs.map +1 -1
  45. package/dist/runtime/index.d.cts +11 -3
  46. package/dist/runtime/index.d.ts +11 -3
  47. package/dist/runtime/index.js +364 -8
  48. package/dist/runtime/index.js.map +1 -1
  49. package/dist/{types-D-lVfaDU.d.cts → types-CQHprSVk.d.cts} +10 -0
  50. package/dist/{types-D-lVfaDU.d.ts → types-CQHprSVk.d.ts} +10 -0
  51. package/dist/vite.cjs +2259 -385
  52. package/dist/vite.cjs.map +1 -1
  53. package/dist/vite.d.cts +1 -1
  54. package/dist/vite.d.ts +1 -1
  55. package/dist/vite.js +2258 -384
  56. package/dist/vite.js.map +1 -1
  57. package/dist/webpack.cjs +2259 -385
  58. package/dist/webpack.cjs.map +1 -1
  59. package/dist/webpack.d.cts +1 -1
  60. package/dist/webpack.d.ts +1 -1
  61. package/dist/webpack.js +2258 -384
  62. package/dist/webpack.js.map +1 -1
  63. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -111,7 +111,7 @@ function scanClientBundles(outDir) {
111
111
  return [];
112
112
  }
113
113
  const results = [];
114
- function walk5(currentDir) {
114
+ function walk7(currentDir) {
115
115
  if (hasNextServerSegment(currentDir, resolvedOutDir)) {
116
116
  return;
117
117
  }
@@ -130,7 +130,7 @@ function scanClientBundles(outDir) {
130
130
  if (hasNextServerSegment(fullPath, resolvedOutDir)) {
131
131
  continue;
132
132
  }
133
- walk5(fullPath);
133
+ walk7(fullPath);
134
134
  } else if (entry.isFile()) {
135
135
  if (hasNextServerSegment(fullPath, resolvedOutDir)) {
136
136
  continue;
@@ -141,7 +141,7 @@ function scanClientBundles(outDir) {
141
141
  }
142
142
  }
143
143
  }
144
- walk5(resolvedOutDir);
144
+ walk7(resolvedOutDir);
145
145
  return results.sort();
146
146
  }
147
147
 
@@ -332,9 +332,6 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
332
332
  };
333
333
  }
334
334
 
335
- // src/ast/index.ts
336
- import { generate } from "astring";
337
-
338
335
  // src/ast/hot-path-detector.ts
339
336
  import * as acorn from "acorn";
340
337
  import * as walk from "acorn-walk";
@@ -349,7 +346,12 @@ var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
349
346
  "some",
350
347
  "every"
351
348
  ]);
352
- var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
349
+ var ANIMATION_FRAME_CALLS = /* @__PURE__ */ new Set([
350
+ "requestAnimationFrame",
351
+ "cancelAnimationFrame",
352
+ "useFrame"
353
+ ]);
354
+ var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
353
355
  "useState",
354
356
  "useEffect",
355
357
  "useMemo",
@@ -360,9 +362,7 @@ var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
360
362
  "jsxs",
361
363
  "_jsx",
362
364
  "_jsxs",
363
- "createElement",
364
- "requestAnimationFrame",
365
- "cancelAnimationFrame"
365
+ "createElement"
366
366
  ]);
367
367
  var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
368
368
  "FunctionDeclaration",
@@ -397,8 +397,13 @@ function getFunctionLabel(node, ancestors) {
397
397
  if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
398
398
  return parent.id.name;
399
399
  }
400
- if (parent.type === "Property" && parent.key?.type === "Identifier") {
401
- return parent.key.name;
400
+ if (parent.type === "Property") {
401
+ if (parent.key?.type === "Identifier") {
402
+ return parent.key.name;
403
+ }
404
+ if (parent.key?.type === "Literal" && typeof parent.key.value === "string") {
405
+ return parent.key.value;
406
+ }
402
407
  }
403
408
  if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
404
409
  return parent.key.name;
@@ -412,6 +417,9 @@ function getFunctionLabel(node, ancestors) {
412
417
  function isPascalCaseComponent(name) {
413
418
  return /^[A-Z][a-zA-Z0-9]*$/.test(name);
414
419
  }
420
+ function isEventHandlerName(name) {
421
+ return /^(?:on|handle)[A-Z]/.test(name);
422
+ }
415
423
  function findEnclosingScopeNode(ancestors, selfNode) {
416
424
  for (let i = ancestors.length - 1; i >= 0; i--) {
417
425
  const anc = ancestors[i];
@@ -421,12 +429,80 @@ function findEnclosingScopeNode(ancestors, selfNode) {
421
429
  }
422
430
  return ancestors[0];
423
431
  }
432
+ function findEnclosingFunction(ancestors, selfNode) {
433
+ for (let i = ancestors.length - 1; i >= 0; i--) {
434
+ if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
435
+ return ancestors[i];
436
+ }
437
+ }
438
+ return null;
439
+ }
440
+ function findOutermostModuleFunction(ancestors) {
441
+ const fnList = [];
442
+ for (let i = 0; i < ancestors.length; i++) {
443
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
444
+ fnList.push(ancestors[i]);
445
+ }
446
+ }
447
+ if (fnList.length === 0) return null;
448
+ if (fnList.length === 1) return fnList[0];
449
+ return fnList[1];
450
+ }
451
+ function isZeroArgIifeFactoryFunction(node) {
452
+ if (!node || node.params && node.params.length > 0) return false;
453
+ if (!node.body || node.body.type !== "BlockStatement") return false;
454
+ const stmts = (node.body.body || []).filter(
455
+ (s) => !(s.type === "ExpressionStatement" && s.directive)
456
+ );
457
+ if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
458
+ const retArg = stmts[0].argument;
459
+ if (!retArg || retArg.type !== "CallExpression") return false;
460
+ const callee = retArg.callee;
461
+ return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
462
+ }
463
+ function containsLoopOrAnimation(fnNode) {
464
+ let found = false;
465
+ walk.simple(fnNode, {
466
+ ForStatement() {
467
+ found = true;
468
+ },
469
+ ForInStatement() {
470
+ found = true;
471
+ },
472
+ ForOfStatement() {
473
+ found = true;
474
+ },
475
+ WhileStatement() {
476
+ found = true;
477
+ },
478
+ DoWhileStatement() {
479
+ found = true;
480
+ },
481
+ CallExpression(callNode) {
482
+ let cName = "";
483
+ let mProp = "";
484
+ if (callNode.callee?.type === "Identifier") {
485
+ cName = callNode.callee.name;
486
+ } else if (callNode.callee?.type === "MemberExpression" && !callNode.callee.computed && callNode.callee.property?.type === "Identifier") {
487
+ mProp = callNode.callee.property.name;
488
+ }
489
+ if (ANIMATION_FRAME_CALLS.has(cName) || ANIMATION_FRAME_CALLS.has(mProp)) {
490
+ found = true;
491
+ }
492
+ }
493
+ });
494
+ return found;
495
+ }
424
496
  function analyzeAstHotPaths(ast) {
425
497
  const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
426
498
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
427
499
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
500
+ const serializedFunctionNodes = /* @__PURE__ */ new WeakSet();
501
+ const serializedWorkerNodes = /* @__PURE__ */ new Set();
502
+ const trueHotNodes = /* @__PURE__ */ new Set();
503
+ const shallowComponentNodes = /* @__PURE__ */ new Set();
504
+ const coldForcedNodes = /* @__PURE__ */ new Set();
428
505
  const directHotNodes = /* @__PURE__ */ new Set();
429
- const serializedFunctionNodes = /* @__PURE__ */ new Set();
430
506
  const serializerHelperNodes = /* @__PURE__ */ new Set();
431
507
  const allFunctions = [];
432
508
  const fnByName = /* @__PURE__ */ new Map();
@@ -471,42 +547,12 @@ function analyzeAstHotPaths(ast) {
471
547
  return cur;
472
548
  }
473
549
  function markSerializedFunction(node) {
550
+ serializedWorkerNodes.add(node);
474
551
  serializedFunctionNodes.add(node);
475
552
  hotFunctionNodes.add(node);
476
553
  directHotNodes.add(node);
477
554
  hotExemptNodes.add(node);
478
555
  }
479
- function findEnclosingFunction(ancestors, selfNode) {
480
- for (let i = ancestors.length - 1; i >= 0; i--) {
481
- if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
482
- return ancestors[i];
483
- }
484
- }
485
- return null;
486
- }
487
- function findOutermostModuleFunction(ancestors) {
488
- const fnList = [];
489
- for (let i = 0; i < ancestors.length; i++) {
490
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
491
- fnList.push(ancestors[i]);
492
- }
493
- }
494
- if (fnList.length === 0) return null;
495
- if (fnList.length === 1) return fnList[0];
496
- return fnList[1];
497
- }
498
- function isZeroArgIifeFactoryFunction(node) {
499
- if (!node || node.params && node.params.length > 0) return false;
500
- if (!node.body || node.body.type !== "BlockStatement") return false;
501
- const stmts = (node.body.body || []).filter(
502
- (s) => !(s.type === "ExpressionStatement" && s.directive)
503
- );
504
- if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
505
- const retArg = stmts[0].argument;
506
- if (!retArg || retArg.type !== "CallExpression") return false;
507
- const callee = retArg.callee;
508
- return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
509
- }
510
556
  function registerFunctionNode(node, ancestors) {
511
557
  const name = getFunctionLabel(node, ancestors);
512
558
  allFunctions.push({ node, name });
@@ -559,6 +605,7 @@ function analyzeAstHotPaths(ast) {
559
605
  }
560
606
  fnScopeChain.set(node, chain);
561
607
  if (isPascalCaseComponent(name)) {
608
+ shallowComponentNodes.add(node);
562
609
  hotFunctionNodes.add(node);
563
610
  directHotNodes.add(node);
564
611
  }
@@ -728,9 +775,15 @@ function analyzeAstHotPaths(ast) {
728
775
  const outerFn = findOutermostModuleFunction(ancestors);
729
776
  if (outerFn) markSerializedFunction(outerFn);
730
777
  }
731
- if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame" || calleeName === "cancelAnimationFrame" || memberProp === "cancelAnimationFrame") {
778
+ if (ANIMATION_FRAME_CALLS.has(calleeName) || ANIMATION_FRAME_CALLS.has(memberProp)) {
779
+ if (enclosingFn) {
780
+ trueHotNodes.add(enclosingFn);
781
+ hotFunctionNodes.add(enclosingFn);
782
+ directHotNodes.add(enclosingFn);
783
+ }
732
784
  for (const arg of node.arguments || []) {
733
785
  if (FUNCTION_NODE_TYPES.has(arg.type)) {
786
+ trueHotNodes.add(arg);
734
787
  hotFunctionNodes.add(arg);
735
788
  directHotNodes.add(arg);
736
789
  hotExemptNodes.add(arg);
@@ -743,8 +796,48 @@ function analyzeAstHotPaths(ast) {
743
796
  }
744
797
  }
745
798
  }
746
- if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
799
+ if (ARRAY_HOF_METHODS.has(memberProp)) {
800
+ if (enclosingFn !== null) {
801
+ for (const arg of node.arguments || []) {
802
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
803
+ trueHotNodes.add(arg);
804
+ hotFunctionNodes.add(arg);
805
+ directHotNodes.add(arg);
806
+ hotExemptNodes.add(arg);
807
+ } else if (arg?.type === "Identifier") {
808
+ allCallSites.push({
809
+ scopeNode: currentScope,
810
+ calleeKey: arg.name,
811
+ args: [arg]
812
+ });
813
+ }
814
+ }
815
+ } else {
816
+ for (const arg of node.arguments || []) {
817
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
818
+ coldForcedNodes.add(arg);
819
+ }
820
+ }
821
+ }
822
+ }
823
+ if (calleeName === "useEffect" || memberProp === "useEffect" || calleeName === "useLayoutEffect" || memberProp === "useLayoutEffect") {
824
+ const effectArg = node.arguments?.[0];
825
+ if (effectArg && FUNCTION_NODE_TYPES.has(effectArg.type)) {
826
+ if (!containsLoopOrAnimation(effectArg)) {
827
+ coldForcedNodes.add(effectArg);
828
+ if (effectArg.body?.type === "BlockStatement") {
829
+ for (const s of effectArg.body.body || []) {
830
+ if (s.type === "ReturnStatement" && s.argument && FUNCTION_NODE_TYPES.has(s.argument.type) && !containsLoopOrAnimation(s.argument)) {
831
+ coldForcedNodes.add(s.argument);
832
+ }
833
+ }
834
+ }
835
+ }
836
+ }
837
+ }
838
+ if (REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp)) {
747
839
  if (enclosingFn) {
840
+ shallowComponentNodes.add(enclosingFn);
748
841
  hotFunctionNodes.add(enclosingFn);
749
842
  directHotNodes.add(enclosingFn);
750
843
  }
@@ -752,23 +845,48 @@ function analyzeAstHotPaths(ast) {
752
845
  },
753
846
  ForStatement(node, _state, ancestors) {
754
847
  hotExemptNodes.add(node);
755
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
848
+ const enc = findEnclosingFunction(ancestors);
849
+ if (enc) {
850
+ trueHotNodes.add(enc);
851
+ hotFunctionNodes.add(enc);
852
+ directHotNodes.add(enc);
853
+ }
756
854
  },
757
855
  ForInStatement(node, _state, ancestors) {
758
856
  hotExemptNodes.add(node);
759
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
857
+ const enc = findEnclosingFunction(ancestors);
858
+ if (enc) {
859
+ trueHotNodes.add(enc);
860
+ hotFunctionNodes.add(enc);
861
+ directHotNodes.add(enc);
862
+ }
760
863
  },
761
864
  ForOfStatement(node, _state, ancestors) {
762
865
  hotExemptNodes.add(node);
763
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
866
+ const enc = findEnclosingFunction(ancestors);
867
+ if (enc) {
868
+ trueHotNodes.add(enc);
869
+ hotFunctionNodes.add(enc);
870
+ directHotNodes.add(enc);
871
+ }
764
872
  },
765
873
  WhileStatement(node, _state, ancestors) {
766
874
  hotExemptNodes.add(node);
767
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
875
+ const enc = findEnclosingFunction(ancestors);
876
+ if (enc) {
877
+ trueHotNodes.add(enc);
878
+ hotFunctionNodes.add(enc);
879
+ directHotNodes.add(enc);
880
+ }
768
881
  },
769
882
  DoWhileStatement(node, _state, ancestors) {
770
883
  hotExemptNodes.add(node);
771
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
884
+ const enc = findEnclosingFunction(ancestors);
885
+ if (enc) {
886
+ trueHotNodes.add(enc);
887
+ hotFunctionNodes.add(enc);
888
+ directHotNodes.add(enc);
889
+ }
772
890
  }
773
891
  });
774
892
  for (const callSite of allCallSites) {
@@ -785,59 +903,113 @@ function analyzeAstHotPaths(ast) {
785
903
  markSerializedFunction(targetNode);
786
904
  }
787
905
  }
788
- const forwardHotSet = new Set(directHotNodes);
906
+ for (const fn of allFunctions) {
907
+ if (!trueHotNodes.has(fn.node) && !containsLoopOrAnimation(fn.node)) {
908
+ if (fn.node.async === true || isEventHandlerName(fn.name)) {
909
+ coldForcedNodes.add(fn.node);
910
+ }
911
+ }
912
+ }
789
913
  let forwardChanged = true;
790
914
  while (forwardChanged) {
791
915
  forwardChanged = false;
792
916
  for (const fn of allFunctions) {
793
- if (forwardHotSet.has(fn.node)) continue;
917
+ if (coldForcedNodes.has(fn.node)) continue;
794
918
  const chain = fnScopeChain.get(fn.node);
795
919
  if (!chain) continue;
796
920
  for (const anc of chain) {
797
- if (anc !== fn.node && (serializedFunctionNodes.has(anc) || forwardHotSet.has(anc))) {
798
- forwardHotSet.add(fn.node);
799
- hotFunctionNodes.add(fn.node);
800
- hotExemptNodes.add(fn.node);
801
- if (serializedFunctionNodes.has(anc)) {
921
+ if (anc === fn.node) continue;
922
+ if (serializedWorkerNodes.has(anc)) {
923
+ if (!serializedWorkerNodes.has(fn.node)) {
924
+ serializedWorkerNodes.add(fn.node);
802
925
  serializedFunctionNodes.add(fn.node);
926
+ hotFunctionNodes.add(fn.node);
927
+ hotExemptNodes.add(fn.node);
928
+ forwardChanged = true;
929
+ }
930
+ break;
931
+ }
932
+ const isModuleContainer = (fnScopeChain.get(anc)?.length ?? 0) <= 1;
933
+ if (trueHotNodes.has(anc) && !shallowComponentNodes.has(anc) && !isModuleContainer) {
934
+ if (!trueHotNodes.has(fn.node)) {
935
+ trueHotNodes.add(fn.node);
936
+ hotFunctionNodes.add(fn.node);
937
+ hotExemptNodes.add(fn.node);
938
+ forwardChanged = true;
803
939
  }
804
- forwardChanged = true;
805
940
  break;
806
941
  }
807
942
  }
808
943
  }
809
- for (const callerNode of Array.from(forwardHotSet)) {
944
+ for (const callerNode of Array.from(serializedWorkerNodes)) {
810
945
  const calleeNames = callerToCallees.get(callerNode);
811
946
  if (!calleeNames) continue;
812
947
  for (const cName of calleeNames) {
813
948
  const targetNode = resolveCalleeNode(callerNode, cName);
814
- if (targetNode && !forwardHotSet.has(targetNode)) {
815
- forwardHotSet.add(targetNode);
949
+ if (targetNode && !serializedWorkerNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
950
+ serializedWorkerNodes.add(targetNode);
951
+ serializedFunctionNodes.add(targetNode);
952
+ hotFunctionNodes.add(targetNode);
953
+ hotExemptNodes.add(targetNode);
954
+ forwardChanged = true;
955
+ }
956
+ }
957
+ }
958
+ for (const callerNode of Array.from(trueHotNodes)) {
959
+ const calleeNames = callerToCallees.get(callerNode);
960
+ if (!calleeNames) continue;
961
+ for (const cName of calleeNames) {
962
+ const targetNode = resolveCalleeNode(callerNode, cName);
963
+ if (targetNode && !trueHotNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
964
+ trueHotNodes.add(targetNode);
816
965
  hotFunctionNodes.add(targetNode);
817
966
  hotExemptNodes.add(targetNode);
818
- if (serializedFunctionNodes.has(callerNode)) {
819
- serializedFunctionNodes.add(targetNode);
820
- }
821
967
  forwardChanged = true;
822
968
  }
823
969
  }
824
970
  }
825
971
  }
972
+ const calleeToCallers = /* @__PURE__ */ new Map();
973
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
974
+ for (const cName of calleeNames) {
975
+ const targetNode = resolveCalleeNode(callerNode, cName);
976
+ if (targetNode) {
977
+ let set = calleeToCallers.get(targetNode);
978
+ if (!set) {
979
+ set = /* @__PURE__ */ new Set();
980
+ calleeToCallers.set(targetNode, set);
981
+ }
982
+ set.add(callerNode);
983
+ }
984
+ }
985
+ }
826
986
  let changed = true;
827
987
  while (changed) {
828
988
  changed = false;
829
989
  for (const [callerNode, calleeNames] of callerToCallees.entries()) {
830
- if (hotFunctionNodes.has(callerNode)) continue;
990
+ if (hotFunctionNodes.has(callerNode) || shallowComponentNodes.has(callerNode) || coldForcedNodes.has(callerNode)) {
991
+ continue;
992
+ }
831
993
  for (const cName of calleeNames) {
832
994
  const targetNode = resolveCalleeNode(callerNode, cName);
833
- if (targetNode && hotFunctionNodes.has(targetNode)) {
834
- hotFunctionNodes.add(callerNode);
835
- changed = true;
836
- break;
995
+ if (targetNode && trueHotNodes.has(targetNode)) {
996
+ const callers = calleeToCallers.get(targetNode);
997
+ const isDedicatedPipeline = callers && callers.size <= 2;
998
+ if (isDedicatedPipeline) {
999
+ trueHotNodes.add(callerNode);
1000
+ hotFunctionNodes.add(callerNode);
1001
+ hotExemptNodes.add(callerNode);
1002
+ changed = true;
1003
+ break;
1004
+ }
837
1005
  }
838
1006
  }
839
1007
  }
840
1008
  }
1009
+ for (const node of coldForcedNodes) {
1010
+ hotFunctionNodes.delete(node);
1011
+ hotExemptNodes.delete(node);
1012
+ }
841
1013
  const hotFunctionsSkipped = [];
842
1014
  const coldFunctionsProtected = [];
843
1015
  for (const fn of allFunctions) {
@@ -856,56 +1028,454 @@ function analyzeAstHotPaths(ast) {
856
1028
  },
857
1029
  hotFunctionNodes,
858
1030
  coldFunctionNodes,
859
- hotExemptNodes
1031
+ hotExemptNodes,
1032
+ serializedFunctionNodes
860
1033
  };
861
1034
  }
862
- function markEnclosingFunctionHot(ancestors, hotSet, directHotSet) {
863
- for (let i = ancestors.length - 1; i >= 0; i--) {
864
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
865
- hotSet.add(ancestors[i]);
866
- if (directHotSet) {
867
- directHotSet.add(ancestors[i]);
1035
+
1036
+ // src/ast/string-vault.ts
1037
+ import * as acorn2 from "acorn";
1038
+ import * as walk2 from "acorn-walk";
1039
+
1040
+ // src/ast/codegen.ts
1041
+ import { generate, baseGenerator } from "astring";
1042
+ function derivePolymorphicIdent(seed, role) {
1043
+ let h = (2166136261 ^ seed >>> 0) >>> 0;
1044
+ for (let i = 0; i < role.length; i++) {
1045
+ h ^= role.charCodeAt(i);
1046
+ h = Math.imul(h, 16777619) >>> 0;
1047
+ }
1048
+ const rolePrefixes = {
1049
+ vault: "_a",
1050
+ shield: "$b",
1051
+ decoy: "_d",
1052
+ shader: "_s",
1053
+ vm: "_m",
1054
+ wasm: "_w",
1055
+ salted: "_k",
1056
+ windowKey: "_z"
1057
+ };
1058
+ const prefix = rolePrefixes[role] ?? `_${String.fromCharCode(97 + h % 26)}`;
1059
+ const suffix = ((h >>> 4) % 1296).toString(36).padStart(2, "0");
1060
+ return `${prefix}${suffix}`;
1061
+ }
1062
+ var OPERATOR_PRECEDENCE = {
1063
+ "||": 2,
1064
+ "??": 3,
1065
+ "&&": 4,
1066
+ "|": 5,
1067
+ "^": 6,
1068
+ "&": 7,
1069
+ "==": 8,
1070
+ "!=": 8,
1071
+ "===": 8,
1072
+ "!==": 8,
1073
+ "<": 9,
1074
+ ">": 9,
1075
+ "<=": 9,
1076
+ ">=": 9,
1077
+ "in": 9,
1078
+ "instanceof": 9,
1079
+ "<<": 10,
1080
+ ">>": 10,
1081
+ ">>>": 10,
1082
+ "+": 11,
1083
+ "-": 11,
1084
+ "*": 12,
1085
+ "%": 12,
1086
+ "/": 12,
1087
+ "**": 13
1088
+ };
1089
+ var NEEDS_PARENTHESES = 17;
1090
+ function expressionNeedsParenthesis(state, node, parentNode, isRightHand) {
1091
+ const nodePrecedence = state.expressionsPrecedence[node.type];
1092
+ if (nodePrecedence === NEEDS_PARENTHESES) {
1093
+ return true;
1094
+ }
1095
+ const parentNodePrecedence = state.expressionsPrecedence[parentNode.type];
1096
+ if (nodePrecedence !== parentNodePrecedence) {
1097
+ return !isRightHand && nodePrecedence === 15 && parentNodePrecedence === 14 && parentNode.operator === "**" || nodePrecedence < parentNodePrecedence;
1098
+ }
1099
+ if (nodePrecedence !== 13 && nodePrecedence !== 14) {
1100
+ return false;
1101
+ }
1102
+ if (node.operator === "**" && parentNode.operator === "**") {
1103
+ return !isRightHand;
1104
+ }
1105
+ if (nodePrecedence === 13 && parentNodePrecedence === 13 && (node.operator === "??" || parentNode.operator === "??")) {
1106
+ return true;
1107
+ }
1108
+ if (isRightHand) {
1109
+ return OPERATOR_PRECEDENCE[node.operator] <= OPERATOR_PRECEDENCE[parentNode.operator];
1110
+ }
1111
+ return OPERATOR_PRECEDENCE[node.operator] < OPERATOR_PRECEDENCE[parentNode.operator];
1112
+ }
1113
+ function formatExpression(state, node, parentNode, isRightHand) {
1114
+ const generator = state.generator;
1115
+ if (expressionNeedsParenthesis(state, node, parentNode, isRightHand)) {
1116
+ state.write("(");
1117
+ generator[node.type](node, state);
1118
+ state.write(")");
1119
+ } else {
1120
+ generator[node.type](node, state);
1121
+ }
1122
+ }
1123
+ function formatSequence(state, expressions) {
1124
+ const length = expressions.length;
1125
+ if (length > 0) {
1126
+ state.write("(");
1127
+ state.generator[expressions[0].type](expressions[0], state);
1128
+ for (let i = 1; i < length; i++) {
1129
+ state.write(",");
1130
+ state.generator[expressions[i].type](expressions[i], state);
1131
+ }
1132
+ state.write(")");
1133
+ } else {
1134
+ state.write("()");
1135
+ }
1136
+ }
1137
+ function expressionStartsWith(node, char) {
1138
+ if (!node) return false;
1139
+ if (node.type === "UnaryExpression" && node.prefix) {
1140
+ return node.operator === char;
1141
+ }
1142
+ if (node.type === "UpdateExpression" && node.prefix) {
1143
+ return node.operator[0] === char;
1144
+ }
1145
+ return false;
1146
+ }
1147
+ function expressionEndsWith(node, char) {
1148
+ if (!node) return false;
1149
+ if (node.type === "UpdateExpression" && !node.prefix) {
1150
+ return node.operator[0] === char;
1151
+ }
1152
+ return false;
1153
+ }
1154
+ function isRegExp(node) {
1155
+ return node && (node.type === "Literal" && !!node.regex || node.type === "RegExpLiteral");
1156
+ }
1157
+ var compactGenerator = Object.assign({}, baseGenerator, {
1158
+ BinaryExpression(node, state) {
1159
+ const isIn = node.operator === "in";
1160
+ if (isIn) {
1161
+ state.write("(");
1162
+ }
1163
+ formatExpression(state, node.left, node, false);
1164
+ const op = node.operator;
1165
+ let spaceBefore = false;
1166
+ let spaceAfter = false;
1167
+ if (op === "in" || op === "instanceof") {
1168
+ spaceBefore = true;
1169
+ spaceAfter = true;
1170
+ } else {
1171
+ if ((op === "+" || op === "-") && expressionEndsWith(node.left, op) && !expressionNeedsParenthesis(state, node.left, node, false)) {
1172
+ spaceBefore = true;
1173
+ }
1174
+ if ((op === "+" || op === "-") && expressionStartsWith(node.right, op) && !expressionNeedsParenthesis(state, node.right, node, true) || op === "/" && isRegExp(node.right)) {
1175
+ spaceAfter = true;
1176
+ }
1177
+ }
1178
+ if (spaceBefore) state.write(" ");
1179
+ state.write(op);
1180
+ if (spaceAfter) state.write(" ");
1181
+ formatExpression(state, node.right, node, true);
1182
+ if (isIn) {
1183
+ state.write(")");
1184
+ }
1185
+ },
1186
+ LogicalExpression(node, state) {
1187
+ formatExpression(state, node.left, node, false);
1188
+ state.write(node.operator);
1189
+ formatExpression(state, node.right, node, true);
1190
+ },
1191
+ AssignmentExpression(node, state) {
1192
+ this[node.left.type](node.left, state);
1193
+ const op = node.operator;
1194
+ if (op.endsWith("+") && expressionStartsWith(node.right, "+") || op.endsWith("-") && expressionStartsWith(node.right, "-") || op.endsWith("/") && isRegExp(node.right)) {
1195
+ state.write(op + " ");
1196
+ } else {
1197
+ state.write(op);
1198
+ }
1199
+ this[node.right.type](node.right, state);
1200
+ },
1201
+ ConditionalExpression(node, state) {
1202
+ const test = node.test;
1203
+ const precedence = state.expressionsPrecedence[test.type];
1204
+ if (precedence === NEEDS_PARENTHESES || precedence <= state.expressionsPrecedence.ConditionalExpression) {
1205
+ state.write("(");
1206
+ this[test.type](test, state);
1207
+ state.write(")");
1208
+ } else {
1209
+ this[test.type](test, state);
1210
+ }
1211
+ state.write("?");
1212
+ this[node.consequent.type](node.consequent, state);
1213
+ state.write(":");
1214
+ this[node.alternate.type](node.alternate, state);
1215
+ },
1216
+ ArrayExpression(node, state) {
1217
+ state.write("[");
1218
+ const elements = node.elements;
1219
+ const length = elements.length;
1220
+ for (let i = 0; i < length; i++) {
1221
+ const element = elements[i];
1222
+ if (element != null) {
1223
+ this[element.type](element, state);
1224
+ }
1225
+ if (i + 1 < length) {
1226
+ state.write(",");
1227
+ }
1228
+ }
1229
+ state.write("]");
1230
+ },
1231
+ ObjectExpression(node, state) {
1232
+ state.write("{");
1233
+ const properties = node.properties;
1234
+ const length = properties.length;
1235
+ for (let i = 0; i < length; i++) {
1236
+ const property = properties[i];
1237
+ this[property.type](property, state);
1238
+ if (i + 1 < length) {
1239
+ state.write(",");
1240
+ }
1241
+ }
1242
+ state.write("}");
1243
+ },
1244
+ Property(node, state) {
1245
+ if (node.method || node.kind[0] !== "i") {
1246
+ this.MethodDefinition(node, state);
1247
+ } else {
1248
+ if (!node.shorthand) {
1249
+ if (node.computed) {
1250
+ state.write("[");
1251
+ this[node.key.type](node.key, state);
1252
+ state.write("]");
1253
+ } else {
1254
+ this[node.key.type](node.key, state);
1255
+ }
1256
+ state.write(":");
1257
+ }
1258
+ this[node.value.type](node.value, state);
1259
+ }
1260
+ },
1261
+ CallExpression(node, state) {
1262
+ formatExpression(state, node.callee, node, false);
1263
+ if (node.optional) {
1264
+ state.write("?.");
1265
+ }
1266
+ formatSequence(state, node.arguments);
1267
+ },
1268
+ SequenceExpression(node, state) {
1269
+ formatSequence(state, node.expressions);
1270
+ },
1271
+ FunctionDeclaration(node, state) {
1272
+ state.write(
1273
+ (node.async ? "async " : "") + (node.generator ? "function* " : "function ") + (node.id ? node.id.name : ""),
1274
+ node
1275
+ );
1276
+ formatSequence(state, node.params);
1277
+ this[node.body.type](node.body, state);
1278
+ },
1279
+ FunctionExpression(node, state) {
1280
+ compactGenerator.FunctionDeclaration.call(this, node, state);
1281
+ },
1282
+ ArrowFunctionExpression(node, state) {
1283
+ state.write(node.async ? "async " : "", node);
1284
+ const params = node.params;
1285
+ if (params != null) {
1286
+ if (params.length === 0) {
1287
+ state.write("()");
1288
+ } else if (params.length === 1 && params[0].type === "Identifier") {
1289
+ state.write(params[0].name, params[0]);
1290
+ } else {
1291
+ formatSequence(state, node.params);
868
1292
  }
869
- break;
1293
+ } else {
1294
+ state.write("()");
870
1295
  }
1296
+ state.write("=>");
1297
+ if (node.body.type[0] === "O") {
1298
+ state.write("(");
1299
+ this.ObjectExpression(node.body, state);
1300
+ state.write(")");
1301
+ } else {
1302
+ this[node.body.type](node.body, state);
1303
+ }
1304
+ },
1305
+ ForStatement(node, state) {
1306
+ state.write("for(");
1307
+ if (node.init != null) {
1308
+ const init = node.init;
1309
+ if (init.type[0] === "V") {
1310
+ this.VariableDeclaration(init, state);
1311
+ } else {
1312
+ this[init.type](init, state);
1313
+ state.write(";");
1314
+ }
1315
+ } else {
1316
+ state.write(";");
1317
+ }
1318
+ if (node.test) {
1319
+ this[node.test.type](node.test, state);
1320
+ }
1321
+ state.write(";");
1322
+ if (node.update) {
1323
+ this[node.update.type](node.update, state);
1324
+ }
1325
+ state.write(")");
1326
+ this[node.body.type](node.body, state);
1327
+ },
1328
+ IfStatement(node, state) {
1329
+ state.write("if(");
1330
+ this[node.test.type](node.test, state);
1331
+ state.write(")");
1332
+ this[node.consequent.type](node.consequent, state);
1333
+ if (node.alternate != null) {
1334
+ if (node.consequent.type === "BlockStatement") {
1335
+ state.write("else");
1336
+ } else {
1337
+ state.write(" else");
1338
+ }
1339
+ if (node.alternate.type === "BlockStatement") {
1340
+ this[node.alternate.type](node.alternate, state);
1341
+ } else if (node.alternate.type === "IfStatement") {
1342
+ state.write(" ");
1343
+ this[node.alternate.type](node.alternate, state);
1344
+ } else {
1345
+ state.write(" ");
1346
+ this[node.alternate.type](node.alternate, state);
1347
+ }
1348
+ }
1349
+ },
1350
+ VariableDeclaration(node, state) {
1351
+ state.write(node.kind + " ");
1352
+ const declarations = node.declarations;
1353
+ const length = declarations.length;
1354
+ for (let i = 0; i < length; i++) {
1355
+ this.VariableDeclarator(declarations[i], state);
1356
+ if (i + 1 < length) {
1357
+ state.write(",");
1358
+ }
1359
+ }
1360
+ state.write(";");
1361
+ },
1362
+ VariableDeclarator(node, state) {
1363
+ this[node.id.type](node.id, state);
1364
+ if (node.init != null) {
1365
+ state.write("=");
1366
+ this[node.init.type](node.init, state);
1367
+ }
1368
+ },
1369
+ ReturnStatement(node, state) {
1370
+ state.write("return");
1371
+ if (node.argument) {
1372
+ state.write(" ");
1373
+ this[node.argument.type](node.argument, state);
1374
+ }
1375
+ state.write(";");
1376
+ }
1377
+ });
1378
+ function generateCompactJs(ast) {
1379
+ return generate(ast, {
1380
+ generator: compactGenerator,
1381
+ indent: "",
1382
+ lineEnd: ""
1383
+ });
1384
+ }
1385
+
1386
+ // src/runtime/integrity-guard.ts
1387
+ var FNV_OFFSET_BASIS = 2166136261;
1388
+ var FNV_PRIME = 16777619;
1389
+ function computeIntegrityHash(source, seed = 0) {
1390
+ let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
1391
+ for (let i = 0; i < source.length; i++) {
1392
+ hash ^= source.charCodeAt(i);
1393
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
871
1394
  }
1395
+ return hash >>> 0;
1396
+ }
1397
+
1398
+ // src/runtime/devtools-deterrent.ts
1399
+ function deriveIntegrityFnName(seed) {
1400
+ return derivePolymorphicIdent(seed, "shield");
1401
+ }
1402
+ function deriveWindowKeySymbol(seed) {
1403
+ return derivePolymorphicIdent(seed, "windowKey");
1404
+ }
1405
+ function createDeterrentSnippet(config) {
1406
+ const seed = config.seed >>> 0;
1407
+ const deterrentMode = config.deterrentMode ?? "passive";
1408
+ const fnName = deriveIntegrityFnName(seed);
1409
+ const sym = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1410
+ const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=function(){return 0;};" : "";
1411
+ return `(function ${fnName}(w){if(w){try{var s=Function.prototype.toString,n=w.navigator||0,src=s.call(${fnName}),t=s.call(s).indexOf('[native code]')<0||/\\n/.test(src)||n.webdriver||/HeadlessChrome/.test(n.userAgent);for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=(h&31);if(t){w.__unpeek_tampered=!0;w.__unpeek_seed=((w.__unpeek_seed||${seed})^1)>>>0;String.prototype._u=14;w['${sym}']=d^29;try{${consoleSilence}w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else{w['${sym}']=d;}}catch(e){}}})(typeof window!=='undefined'&&window);`;
1412
+ }
1413
+
1414
+ // src/runtime/index.ts
1415
+ function generateRuntimeShield(config) {
1416
+ const seed = config.seed >>> 0;
1417
+ const windowKeySymbol = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1418
+ const integrityCheckFnName = deriveIntegrityFnName(seed);
1419
+ const preambleCode = createDeterrentSnippet({
1420
+ ...config,
1421
+ windowKeySymbol
1422
+ });
1423
+ const fnStart = preambleCode.indexOf("function");
1424
+ const fnEnd = preambleCode.lastIndexOf("(") - 1;
1425
+ const fnDecl = preambleCode.slice(fnStart, fnEnd);
1426
+ const computedHash = computeIntegrityHash(fnDecl, 0);
1427
+ const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computedHash;
1428
+ const expectedDelta = config.expectedDelta !== void 0 ? config.expectedDelta & 31 : computedHash >>> 0 & 31;
1429
+ return {
1430
+ preambleCode,
1431
+ integrityCheckFnName,
1432
+ expectedHash,
1433
+ windowKeySymbol,
1434
+ expectedDelta
1435
+ };
872
1436
  }
873
1437
 
874
1438
  // src/ast/string-vault.ts
875
- import * as acorn2 from "acorn";
876
- import * as walk2 from "acorn-walk";
1439
+ var SAFE_ALPHA = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~";
877
1440
  var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
878
1441
  "use strict",
879
1442
  "use client",
880
1443
  "use server",
881
1444
  "use asm"
882
1445
  ]);
883
- var HELPER_TEMPLATE = acorn2.parse(
884
- `var _ = (function f(a){return a.map(function(s){var o="";for(var j=0;j<s.length;j++)o+=String.fromCharCode(s.charCodeAt(j)^(((0^((a._u||/\\n/.test(f)*14)|((j&1)*0)))&30)|1));return o;});})([]);`,
885
- { ecmaVersion: "latest", sourceType: "script" }
886
- ).body[0];
887
- function createVaultHelperAst(cacheVarName, encryptedPayloads, mask, step) {
888
- const node = structuredClone(HELPER_TEMPLATE);
889
- node.declarations[0].id.name = cacheVarName;
890
- node.declarations[0].init.arguments[0].elements = encryptedPayloads.map(
891
- (str) => ({
892
- type: "Literal",
893
- value: str,
894
- raw: JSON.stringify(str)
895
- })
896
- );
897
- const outerFn = node.declarations[0].init.callee;
898
- const returnStmt = outerFn.body.body[0];
899
- const innerFn = returnStmt.argument.arguments[0];
900
- const forStmt = innerFn.body.body[1];
901
- const expr = forStmt.body.type === "BlockStatement" ? forStmt.body.body[0].expression : forStmt.body.expression;
902
- const binaryXor = expr.right.arguments[0];
903
- const innerLeft = binaryXor.right.left.left;
904
- innerLeft.left.value = mask;
905
- innerLeft.left.raw = String(mask);
906
- innerLeft.right.right.right.value = step;
907
- innerLeft.right.right.right.raw = String(step);
908
- return node;
1446
+ var STANDARD_PROP_KEYS = /* @__PURE__ */ new Set([
1447
+ "id",
1448
+ "type",
1449
+ "key",
1450
+ "ref",
1451
+ "className",
1452
+ "style",
1453
+ "name",
1454
+ "value",
1455
+ "children",
1456
+ "src",
1457
+ "href",
1458
+ "alt",
1459
+ "role",
1460
+ "tabIndex"
1461
+ ]);
1462
+ var TAILWIND_TOKEN_RE = /^(?:flex|grid|block|inline|hidden|relative|absolute|fixed|w-|h-|min-|max-|p[xytrbl]?-|m[xytrbl]?-|space-[xy]-|text-|font-|bg-|border|rounded|shadow|ring|outline|transition|duration|opacity|cursor|pointer-events|select-|items-|justify-|gap-|overflow-|z-|inset-|top-|left-|right-|bottom-|hover:|focus:|focus-visible:|disabled:|dark:|data-\[|aria-|\[&_)/;
1463
+ var SVG_PATH_RE = /^[Mm]\s*-?\d+(?:\.\d+)?[\s,]+-?\d+/;
1464
+ var SHADER_SIG_RE = /@group|@binding|@vertex|@fragment|@compute|vec4f|gl_Position|uniform/;
1465
+ function shouldEncryptString(val, minLen) {
1466
+ if (val.length < minLen || DIRECTIVE_STRINGS.has(val)) return false;
1467
+ if (SVG_PATH_RE.test(val)) return false;
1468
+ if (val.includes(" ")) {
1469
+ const tokens = val.trim().split(/\s+/);
1470
+ if (tokens.length >= 3) {
1471
+ let twHits = 0;
1472
+ for (const t of tokens) {
1473
+ if (TAILWIND_TOKEN_RE.test(t)) twHits++;
1474
+ }
1475
+ if (twHits / tokens.length >= 0.5) return false;
1476
+ }
1477
+ }
1478
+ return true;
909
1479
  }
910
1480
  function computeFnv1aHash(input, seed = 2166136261) {
911
1481
  let hash = seed >>> 0;
@@ -915,31 +1485,127 @@ function computeFnv1aHash(input, seed = 2166136261) {
915
1485
  }
916
1486
  return hash >>> 0;
917
1487
  }
918
- function encodeStringWithSeed(str, mask, step) {
1488
+ function createPermutationTable(seed) {
1489
+ let s = (seed || 305419896) >>> 0;
1490
+ function xorshift() {
1491
+ s ^= s << 13;
1492
+ s ^= s >>> 17;
1493
+ s ^= s << 5;
1494
+ return s >>> 0;
1495
+ }
1496
+ const indices = [];
1497
+ for (let i = 0; i < 92; i++) indices.push(i);
1498
+ for (let i = 91; i > 0; i--) {
1499
+ const j = xorshift() % (i + 1);
1500
+ const tmp = indices[i];
1501
+ indices[i] = indices[j];
1502
+ indices[j] = tmp;
1503
+ }
1504
+ const B = new Array(92);
1505
+ for (let i = 0; i < 46; i++) {
1506
+ const a = indices[2 * i];
1507
+ const b = indices[2 * i + 1];
1508
+ B[a] = b;
1509
+ B[b] = a;
1510
+ }
1511
+ let P_CHARS = "";
1512
+ for (let i = 0; i < 92; i++) {
1513
+ P_CHARS += SAFE_ALPHA[B[i]];
1514
+ }
1515
+ return P_CHARS;
1516
+ }
1517
+ function encodeStringWithSeed(str, P_CHARS, expectedRot) {
919
1518
  let out = "";
920
1519
  for (let i = 0; i < str.length; i++) {
921
- const code = str.charCodeAt(i);
922
- const k = (mask ^ (i & 1) * step) & 30 | 1;
923
- out += String.fromCharCode(code ^ k);
1520
+ const c = str.charAt(i);
1521
+ const k = SAFE_ALPHA.indexOf(c);
1522
+ if (k < 0) {
1523
+ out += c;
1524
+ } else {
1525
+ const y = (k + expectedRot) % 92;
1526
+ const z = SAFE_ALPHA.indexOf(P_CHARS.charAt(y));
1527
+ out += SAFE_ALPHA.charAt((z - expectedRot + 92) % 92);
1528
+ }
924
1529
  }
925
1530
  return out;
926
1531
  }
927
- function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
1532
+ function createVaultHelperAst(cacheVarName, encryptedPayloads, fnAst) {
1533
+ return {
1534
+ type: "VariableDeclaration",
1535
+ kind: "var",
1536
+ declarations: [
1537
+ {
1538
+ type: "VariableDeclarator",
1539
+ id: { type: "Identifier", name: cacheVarName },
1540
+ init: {
1541
+ type: "CallExpression",
1542
+ callee: fnAst,
1543
+ arguments: [
1544
+ {
1545
+ type: "ArrayExpression",
1546
+ elements: encryptedPayloads.map((str) => ({
1547
+ type: "Literal",
1548
+ value: str,
1549
+ raw: JSON.stringify(str)
1550
+ }))
1551
+ }
1552
+ ],
1553
+ optional: false
1554
+ }
1555
+ }
1556
+ ]
1557
+ };
1558
+ }
1559
+ function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
1560
+ const b64List = [];
1561
+ const key = seed >>> 0 & 255 ^ 90;
1562
+ for (let idx = 0; idx < shaderPayloads.length; idx++) {
1563
+ const str = shaderPayloads[idx];
1564
+ const buf = Buffer.from(str, "utf8");
1565
+ for (let i = 0; i < buf.length; i++) {
1566
+ buf[i] ^= key;
1567
+ }
1568
+ b64List.push(buf.toString("base64"));
1569
+ }
1570
+ const shaderCode = `var ${shaderVarName} = (function(){var B=${JSON.stringify(
1571
+ b64List
1572
+ )};var k=${key};var b=B.map(function(s){var bin=typeof atob==='function'?atob(s):(typeof Buffer!=='undefined'?Buffer.from(s,'base64').toString('binary'):'');var u=new Uint8Array(bin.length);for(var i=0;i<bin.length;i++)u[i]=bin.charCodeAt(i);return u;});var d=typeof TextDecoder!=='undefined'?new TextDecoder():null;return function(i){var u=b[i];for(var j=0;j<u.length;j++)u[j]^=k;try{return d?d.decode(u):String.fromCharCode.apply(null,u);}finally{for(var j=0;j<u.length;j++)u[j]^=k;}};})();`;
1573
+ return acorn2.parse(shaderCode, { ecmaVersion: "latest", sourceType: "script" }).body[0];
1574
+ }
1575
+ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta) {
1576
+ const cacheVarName = derivePolymorphicIdent(seed, "vault");
1577
+ const shaderVarName = derivePolymorphicIdent(seed, "shader");
1578
+ const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
1579
+ let expDelta = expectedDelta;
1580
+ if (expDelta === void 0) {
1581
+ const shield = generateRuntimeShield({ seed, windowKeySymbol: sym });
1582
+ expDelta = shield.expectedDelta ?? 0;
1583
+ }
928
1584
  const alreadyVaulted = ast.body.some(
929
1585
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
930
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
1586
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uC") || d.id.name === cacheVarName || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
931
1587
  )
932
1588
  );
933
1589
  if (alreadyVaulted) {
934
1590
  return {
935
1591
  encryptedStringsCount: 0,
936
- integrityToken: computeFnv1aHash("already-vaulted", seed)
1592
+ integrityToken: computeFnv1aHash("already-vaulted", seed),
1593
+ shaderBuffersCount: 0
937
1594
  };
938
1595
  }
939
- const mask = seed >>> 0 & 30 | 3;
940
- const step = 1;
1596
+ const P_CHARS = createPermutationTable(seed);
1597
+ const fBody = `var s=Function.prototype.toString,w=typeof window!=='undefined'&&window,src=s.call(f);for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var rot=(h^(a._u||0)^(w&&w['${sym}']!=null?w['${sym}']:${expDelta}))&31;var A="${SAFE_ALPHA}";var P="${P_CHARS}";return a.map(function(s){var o="";for(var j=0;j<s.length;j++){var c=s.charAt(j),k=A.indexOf(c);if(k<0){o+=c;}else{var y=(k+rot)%92;var z=A.indexOf(P.charAt(y));o+=A.charAt((z-rot+92)%92);}}return o;});`;
1598
+ const fnAst = acorn2.parse(`(function f(a){${fBody}})`, {
1599
+ ecmaVersion: "latest",
1600
+ sourceType: "script"
1601
+ }).body[0].expression;
1602
+ const compactFnStr = generateCompactJs(fnAst);
1603
+ const buildH = computeIntegrityHash(compactFnStr, 0);
1604
+ const expectedRot = (buildH ^ 0 ^ expDelta) & 31;
941
1605
  const stringToIndex = /* @__PURE__ */ new Map();
942
1606
  const encryptedPayloads = [];
1607
+ const shaderToIndex = /* @__PURE__ */ new Map();
1608
+ const shaderPayloads = [];
943
1609
  const targetsToReplace = [];
944
1610
  const customWalkBase = {
945
1611
  ...walk2.base,
@@ -954,7 +1620,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
954
1620
  Literal(node, _state, ancestors) {
955
1621
  if (typeof node.value !== "string") return;
956
1622
  const val = node.value;
957
- if (val.length < minStringLength) return;
958
1623
  if (DIRECTIVE_STRINGS.has(val)) return;
959
1624
  if (hotExemptNodes) {
960
1625
  for (let i = ancestors.length - 2; i >= 0; i--) {
@@ -972,59 +1637,125 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
972
1637
  if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
973
1638
  return;
974
1639
  }
975
- if (parent.type === "Property" && parent.key === node) {
976
- parent.computed = true;
977
- }
978
1640
  if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
979
1641
  return;
980
1642
  }
981
- let idx = stringToIndex.get(val);
982
- if (idx === void 0) {
983
- idx = encryptedPayloads.length;
984
- stringToIndex.set(val, idx);
985
- encryptedPayloads.push(encodeStringWithSeed(val, mask, step));
1643
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
1644
+ if (STANDARD_PROP_KEYS.has(val)) {
1645
+ return;
1646
+ }
1647
+ }
1648
+ const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
1649
+ if (isShader) {
1650
+ let idx = shaderToIndex.get(val);
1651
+ if (idx === void 0) {
1652
+ idx = shaderPayloads.length;
1653
+ shaderToIndex.set(val, idx);
1654
+ shaderPayloads.push(val);
1655
+ }
1656
+ targetsToReplace.push({ type: "shader", node, parent, idx });
1657
+ } else {
1658
+ if (!shouldEncryptString(val, minStringLength)) return;
1659
+ let idx = stringToIndex.get(val);
1660
+ if (idx === void 0) {
1661
+ idx = encryptedPayloads.length;
1662
+ stringToIndex.set(val, idx);
1663
+ encryptedPayloads.push(
1664
+ encodeStringWithSeed(val, P_CHARS, expectedRot)
1665
+ );
1666
+ }
1667
+ targetsToReplace.push({ type: "string", node, parent, idx });
1668
+ }
1669
+ },
1670
+ TemplateLiteral(node, _state, ancestors) {
1671
+ if (!node.quasis || node.quasis.length !== 1) return;
1672
+ if (node.expressions && node.expressions.length !== 0) return;
1673
+ if (hotExemptNodes) {
1674
+ for (let i = ancestors.length - 2; i >= 0; i--) {
1675
+ if (hotExemptNodes.has(ancestors[i])) {
1676
+ return;
1677
+ }
1678
+ }
1679
+ }
1680
+ const parent = ancestors[ancestors.length - 2];
1681
+ if (!parent) return;
1682
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
1683
+ if (typeof val !== "string" || DIRECTIVE_STRINGS.has(val)) return;
1684
+ const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
1685
+ if (isShader) {
1686
+ let idx = shaderToIndex.get(val);
1687
+ if (idx === void 0) {
1688
+ idx = shaderPayloads.length;
1689
+ shaderToIndex.set(val, idx);
1690
+ shaderPayloads.push(val);
1691
+ }
1692
+ targetsToReplace.push({ type: "shader", node, parent, idx });
1693
+ } else {
1694
+ if (!shouldEncryptString(val, minStringLength)) return;
1695
+ let idx = stringToIndex.get(val);
1696
+ if (idx === void 0) {
1697
+ idx = encryptedPayloads.length;
1698
+ stringToIndex.set(val, idx);
1699
+ encryptedPayloads.push(
1700
+ encodeStringWithSeed(val, P_CHARS, expectedRot)
1701
+ );
1702
+ }
1703
+ targetsToReplace.push({ type: "string", node, parent, idx });
986
1704
  }
987
- targetsToReplace.push({ node, parent });
988
1705
  }
989
1706
  },
990
1707
  customWalkBase
991
1708
  );
992
- if (targetsToReplace.length === 0 || encryptedPayloads.length === 0) {
1709
+ if (targetsToReplace.length === 0) {
993
1710
  return {
994
1711
  encryptedStringsCount: 0,
995
- integrityToken: computeFnv1aHash("empty", seed)
1712
+ integrityToken: computeFnv1aHash("empty", seed),
1713
+ shaderBuffersCount: 0
996
1714
  };
997
1715
  }
998
1716
  const serializedTable = JSON.stringify(encryptedPayloads);
999
1717
  const integrityToken = computeFnv1aHash(serializedTable, seed);
1000
- const suffix = computeFnv1aHash(`vault:${seed}`, integrityToken).toString(36);
1001
- const cacheVarName = `_uC${suffix}`;
1002
- for (const { node, parent } of targetsToReplace) {
1718
+ for (const { type, node, parent, idx } of targetsToReplace) {
1003
1719
  if (parent?.type === "Property" && parent.key === node) {
1004
1720
  parent.computed = true;
1005
1721
  }
1006
- const idx = stringToIndex.get(node.value);
1007
- node.type = "MemberExpression";
1008
- node.object = {
1009
- type: "Identifier",
1010
- name: cacheVarName
1011
- };
1012
- node.property = {
1013
- type: "Literal",
1014
- value: idx,
1015
- raw: String(idx)
1016
- };
1017
- node.computed = true;
1018
- node.optional = false;
1019
- delete node.value;
1020
- delete node.raw;
1021
- }
1022
- const helperStmt = createVaultHelperAst(
1023
- cacheVarName,
1024
- encryptedPayloads,
1025
- mask,
1026
- step
1027
- );
1722
+ if (type === "shader") {
1723
+ node.type = "CallExpression";
1724
+ node.callee = {
1725
+ type: "Identifier",
1726
+ name: shaderVarName
1727
+ };
1728
+ node.arguments = [
1729
+ {
1730
+ type: "Literal",
1731
+ value: idx,
1732
+ raw: String(idx)
1733
+ }
1734
+ ];
1735
+ node.optional = false;
1736
+ delete node.value;
1737
+ delete node.raw;
1738
+ delete node.quasis;
1739
+ delete node.expressions;
1740
+ } else {
1741
+ node.type = "MemberExpression";
1742
+ node.object = {
1743
+ type: "Identifier",
1744
+ name: cacheVarName
1745
+ };
1746
+ node.property = {
1747
+ type: "Literal",
1748
+ value: idx,
1749
+ raw: String(idx)
1750
+ };
1751
+ node.computed = true;
1752
+ node.optional = false;
1753
+ delete node.value;
1754
+ delete node.raw;
1755
+ delete node.quasis;
1756
+ delete node.expressions;
1757
+ }
1758
+ }
1028
1759
  let insertIdx = 0;
1029
1760
  while (insertIdx < ast.body.length) {
1030
1761
  const stmt = ast.body[insertIdx];
@@ -1035,10 +1766,26 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
1035
1766
  break;
1036
1767
  }
1037
1768
  }
1038
- ast.body.splice(insertIdx, 0, helperStmt);
1769
+ if (encryptedPayloads.length > 0) {
1770
+ const vaultHelperStmt = createVaultHelperAst(
1771
+ cacheVarName,
1772
+ encryptedPayloads,
1773
+ fnAst
1774
+ );
1775
+ ast.body.splice(insertIdx++, 0, vaultHelperStmt);
1776
+ }
1777
+ if (shaderPayloads.length > 0) {
1778
+ const shaderHelperStmt = createShaderVaultAst(
1779
+ shaderVarName,
1780
+ shaderPayloads,
1781
+ seed
1782
+ );
1783
+ ast.body.splice(insertIdx++, 0, shaderHelperStmt);
1784
+ }
1039
1785
  return {
1040
1786
  encryptedStringsCount: encryptedPayloads.length,
1041
- integrityToken
1787
+ integrityToken,
1788
+ shaderBuffersCount: shaderPayloads.length
1042
1789
  };
1043
1790
  }
1044
1791
 
@@ -1137,9 +1884,9 @@ function collectPatternTargets(pattern, out, shorthandProp) {
1137
1884
  }
1138
1885
  }
1139
1886
  function isMangleableName(origName) {
1140
- return !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x");
1887
+ return origName.length > 2 && !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x") && !origName.startsWith("$$");
1141
1888
  }
1142
- function applyPolymorphicMangler(ast, seed = 2654435769) {
1889
+ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes) {
1143
1890
  const scopeRecords = /* @__PURE__ */ new Map();
1144
1891
  const existingIdentifiers = /* @__PURE__ */ new Set();
1145
1892
  let counter = 0;
@@ -1185,11 +1932,16 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1185
1932
  }
1186
1933
  return ancestors[0];
1187
1934
  }
1188
- function registerBindingTarget(scopeNode, target, shouldMangle) {
1935
+ function registerBindingTarget(scopeNode, target, shouldMangle, fnScope) {
1189
1936
  const scope = scopeRecords.get(scopeNode);
1190
1937
  if (!scope) return;
1191
1938
  const origName = target.idNode.name;
1192
- const canMangle = shouldMangle && isMangleableName(origName);
1939
+ let canMangle = shouldMangle && isMangleableName(origName);
1940
+ if (canMangle && fnScope) {
1941
+ if (serializedFunctionNodes && serializedFunctionNodes.has(fnScope)) {
1942
+ canMangle = false;
1943
+ }
1944
+ }
1193
1945
  let entry = scope.bindings.get(origName);
1194
1946
  if (!entry) {
1195
1947
  entry = {
@@ -1228,7 +1980,7 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1228
1980
  const targets = [];
1229
1981
  collectPatternTargets(param, targets);
1230
1982
  for (const target of targets) {
1231
- registerBindingTarget(fnNode, target, true);
1983
+ registerBindingTarget(fnNode, target, true, fnNode);
1232
1984
  }
1233
1985
  }
1234
1986
  }
@@ -1298,10 +2050,11 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1298
2050
  CatchClause(node, _state, ancestors) {
1299
2051
  ensureScopeChain(ancestors);
1300
2052
  if (node.param) {
2053
+ const fnScope = findEnclosingFunctionNode(ancestors);
1301
2054
  const targets = [];
1302
2055
  collectPatternTargets(node.param, targets);
1303
2056
  for (const target of targets) {
1304
- registerBindingTarget(node, target, true);
2057
+ registerBindingTarget(node, target, true, fnScope);
1305
2058
  }
1306
2059
  }
1307
2060
  },
@@ -1336,7 +2089,7 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1336
2089
  }
1337
2090
  }
1338
2091
  }
1339
- registerBindingTarget(targetScopeNode, target, true);
2092
+ registerBindingTarget(targetScopeNode, target, true, fnScope);
1340
2093
  }
1341
2094
  }
1342
2095
  }
@@ -1352,12 +2105,16 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1352
2105
  }
1353
2106
  return false;
1354
2107
  }
2108
+ const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
1355
2109
  function makeScopedMangledName(scope, localIndex) {
1356
2110
  counter++;
1357
2111
  let salt = 0;
1358
2112
  while (true) {
1359
2113
  const h = computeFnv1aHash(`s${scope.depth}:i${localIndex}:${salt}`, seed);
1360
- const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
2114
+ const prefix = (h & 1) === 0 ? "_" : "$";
2115
+ const ch = ALPHABET[((h >>> 1) + localIndex) % ALPHABET.length];
2116
+ const num = (localIndex + salt).toString(36);
2117
+ const candidate = `${prefix}${ch}${num}`;
1361
2118
  if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
1362
2119
  return candidate;
1363
2120
  }
@@ -1467,227 +2224,420 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1467
2224
 
1468
2225
  // src/ast/cold-flow-guard.ts
1469
2226
  import * as walk4 from "acorn-walk";
1470
- function createDecoyConsequent(fnIndex) {
1471
- const model = Math.abs(fnIndex) % 3;
1472
- if (model === 0) {
2227
+ function createDecoyObjectExpression(model) {
2228
+ const m = Math.abs(model) % 3;
2229
+ if (m === 0) {
1473
2230
  return {
1474
- type: "BlockStatement",
1475
- body: [
2231
+ type: "ObjectExpression",
2232
+ properties: [
1476
2233
  {
1477
- type: "ReturnStatement",
1478
- argument: {
1479
- type: "ObjectExpression",
1480
- properties: [
1481
- {
1482
- type: "Property",
1483
- key: { type: "Identifier", name: "endpoint" },
1484
- value: {
1485
- type: "Literal",
1486
- value: "/api/v2/auth/admin-bypass",
1487
- raw: '"/api/v2/auth/admin-bypass"'
1488
- },
1489
- kind: "init",
1490
- computed: false,
1491
- method: false,
1492
- shorthand: false
1493
- },
1494
- {
1495
- type: "Property",
1496
- key: { type: "Identifier", name: "superadmin_token" },
1497
- value: { type: "Literal", value: 1, raw: "1" },
1498
- kind: "init",
1499
- computed: false,
1500
- method: false,
1501
- shorthand: false
1502
- },
1503
- {
1504
- type: "Property",
1505
- key: { type: "Identifier", name: "elevate" },
1506
- value: { type: "Literal", value: 1, raw: "1" },
1507
- kind: "init",
1508
- computed: false,
1509
- method: false,
1510
- shorthand: false
1511
- }
1512
- ]
1513
- }
2234
+ type: "Property",
2235
+ key: { type: "Identifier", name: "endpoint" },
2236
+ value: {
2237
+ type: "Literal",
2238
+ value: "/api/v2/auth/admin-bypass",
2239
+ raw: '"/api/v2/auth/admin-bypass"'
2240
+ },
2241
+ kind: "init",
2242
+ computed: false,
2243
+ method: false,
2244
+ shorthand: false
2245
+ },
2246
+ {
2247
+ type: "Property",
2248
+ key: { type: "Identifier", name: "superadmin_token" },
2249
+ value: { type: "Literal", value: 1, raw: "1" },
2250
+ kind: "init",
2251
+ computed: false,
2252
+ method: false,
2253
+ shorthand: false
2254
+ },
2255
+ {
2256
+ type: "Property",
2257
+ key: { type: "Identifier", name: "elevate" },
2258
+ value: { type: "Literal", value: 1, raw: "1" },
2259
+ kind: "init",
2260
+ computed: false,
2261
+ method: false,
2262
+ shorthand: false
1514
2263
  }
1515
2264
  ]
1516
2265
  };
1517
2266
  }
1518
- if (model === 1) {
2267
+ if (m === 1) {
1519
2268
  return {
1520
- type: "BlockStatement",
1521
- body: [
2269
+ type: "ObjectExpression",
2270
+ properties: [
1522
2271
  {
1523
- type: "ReturnStatement",
1524
- argument: {
1525
- type: "ObjectExpression",
1526
- properties: [
1527
- {
1528
- type: "Property",
1529
- key: { type: "Identifier", name: "endpoint" },
1530
- value: {
1531
- type: "Literal",
1532
- value: "/api/v2/auth/verify-master",
1533
- raw: '"/api/v2/auth/verify-master"'
1534
- },
1535
- kind: "init",
1536
- computed: false,
1537
- method: false,
1538
- shorthand: false
1539
- },
1540
- {
1541
- type: "Property",
1542
- key: { type: "Identifier", name: "_verifyMasterToken" },
1543
- value: { type: "Literal", value: true, raw: "true" },
1544
- kind: "init",
1545
- computed: false,
1546
- method: false,
1547
- shorthand: false
1548
- },
1549
- {
1550
- type: "Property",
1551
- key: { type: "Identifier", name: "_bypassToken" },
1552
- value: {
1553
- type: "Literal",
1554
- value: "mock_jwt_bypass_signature",
1555
- raw: '"mock_jwt_bypass_signature"'
1556
- },
1557
- kind: "init",
1558
- computed: false,
1559
- method: false,
1560
- shorthand: false
1561
- },
1562
- {
1563
- type: "Property",
1564
- key: { type: "Identifier", name: "authorized" },
1565
- value: { type: "Literal", value: true, raw: "true" },
1566
- kind: "init",
1567
- computed: false,
1568
- method: false,
1569
- shorthand: false
1570
- }
1571
- ]
1572
- }
2272
+ type: "Property",
2273
+ key: { type: "Identifier", name: "endpoint" },
2274
+ value: {
2275
+ type: "Literal",
2276
+ value: "/api/v2/auth/verify-master",
2277
+ raw: '"/api/v2/auth/verify-master"'
2278
+ },
2279
+ kind: "init",
2280
+ computed: false,
2281
+ method: false,
2282
+ shorthand: false
2283
+ },
2284
+ {
2285
+ type: "Property",
2286
+ key: { type: "Identifier", name: "_verifyMasterToken" },
2287
+ value: { type: "Literal", value: true, raw: "true" },
2288
+ kind: "init",
2289
+ computed: false,
2290
+ method: false,
2291
+ shorthand: false
2292
+ },
2293
+ {
2294
+ type: "Property",
2295
+ key: { type: "Identifier", name: "_bypassToken" },
2296
+ value: {
2297
+ type: "Literal",
2298
+ value: "mock_jwt_bypass_signature",
2299
+ raw: '"mock_jwt_bypass_signature"'
2300
+ },
2301
+ kind: "init",
2302
+ computed: false,
2303
+ method: false,
2304
+ shorthand: false
2305
+ },
2306
+ {
2307
+ type: "Property",
2308
+ key: { type: "Identifier", name: "authorized" },
2309
+ value: { type: "Literal", value: true, raw: "true" },
2310
+ kind: "init",
2311
+ computed: false,
2312
+ method: false,
2313
+ shorthand: false
1573
2314
  }
1574
2315
  ]
1575
2316
  };
1576
2317
  }
1577
2318
  return {
1578
- type: "BlockStatement",
1579
- body: [
2319
+ type: "ObjectExpression",
2320
+ properties: [
1580
2321
  {
1581
- type: "ReturnStatement",
1582
- argument: {
1583
- type: "ObjectExpression",
1584
- properties: [
1585
- {
1586
- type: "Property",
1587
- key: { type: "Identifier", name: "endpoint" },
1588
- value: {
1589
- type: "Literal",
1590
- value: "/api/v2/auth/debug-telemetry",
1591
- raw: '"/api/v2/auth/debug-telemetry"'
1592
- },
1593
- kind: "init",
1594
- computed: false,
1595
- method: false,
1596
- shorthand: false
1597
- },
1598
- {
1599
- type: "Property",
1600
- key: { type: "Identifier", name: "debug_supervisor_override" },
1601
- value: { type: "Literal", value: true, raw: "true" },
1602
- kind: "init",
1603
- computed: false,
1604
- method: false,
1605
- shorthand: false
1606
- },
1607
- {
1608
- type: "Property",
1609
- key: { type: "Identifier", name: "_bypassToken" },
1610
- value: {
1611
- type: "Literal",
1612
- value: "superadmin_token",
1613
- raw: '"superadmin_token"'
1614
- },
1615
- kind: "init",
1616
- computed: false,
1617
- method: false,
1618
- shorthand: false
1619
- },
1620
- {
1621
- type: "Property",
1622
- key: { type: "Identifier", name: "mfa_bypassed" },
1623
- value: { type: "Literal", value: true, raw: "true" },
1624
- kind: "init",
1625
- computed: false,
1626
- method: false,
1627
- shorthand: false
2322
+ type: "Property",
2323
+ key: { type: "Identifier", name: "endpoint" },
2324
+ value: {
2325
+ type: "Literal",
2326
+ value: "/api/v2/auth/debug-telemetry",
2327
+ raw: '"/api/v2/auth/debug-telemetry"'
2328
+ },
2329
+ kind: "init",
2330
+ computed: false,
2331
+ method: false,
2332
+ shorthand: false
2333
+ },
2334
+ {
2335
+ type: "Property",
2336
+ key: { type: "Identifier", name: "debug_supervisor_override" },
2337
+ value: { type: "Literal", value: true, raw: "true" },
2338
+ kind: "init",
2339
+ computed: false,
2340
+ method: false,
2341
+ shorthand: false
2342
+ },
2343
+ {
2344
+ type: "Property",
2345
+ key: { type: "Identifier", name: "_bypassToken" },
2346
+ value: {
2347
+ type: "Literal",
2348
+ value: "superadmin_token",
2349
+ raw: '"superadmin_token"'
2350
+ },
2351
+ kind: "init",
2352
+ computed: false,
2353
+ method: false,
2354
+ shorthand: false
2355
+ },
2356
+ {
2357
+ type: "Property",
2358
+ key: { type: "Identifier", name: "mfa_bypassed" },
2359
+ value: { type: "Literal", value: true, raw: "true" },
2360
+ kind: "init",
2361
+ computed: false,
2362
+ method: false,
2363
+ shorthand: false
2364
+ }
2365
+ ]
2366
+ };
2367
+ }
2368
+ function createDecoyConsequent(fnIndex) {
2369
+ return {
2370
+ type: "BlockStatement",
2371
+ body: [
2372
+ {
2373
+ type: "ReturnStatement",
2374
+ argument: createDecoyObjectExpression(fnIndex)
2375
+ }
2376
+ ]
2377
+ };
2378
+ }
2379
+ function createSharedDecoyConsequent(decoyIdent, fnIndex) {
2380
+ const model = Math.abs(fnIndex) % 3;
2381
+ return {
2382
+ type: "BlockStatement",
2383
+ body: [
2384
+ {
2385
+ type: "ReturnStatement",
2386
+ argument: {
2387
+ type: "CallExpression",
2388
+ callee: {
2389
+ type: "MemberExpression",
2390
+ computed: true,
2391
+ object: { type: "Identifier", name: decoyIdent },
2392
+ property: {
2393
+ type: "Literal",
2394
+ value: model,
2395
+ raw: String(model)
1628
2396
  }
1629
- ]
2397
+ },
2398
+ arguments: []
1630
2399
  }
1631
2400
  }
1632
2401
  ]
1633
2402
  };
1634
2403
  }
1635
- function createSotaMbaPredicate(seed, fnIndex = 0) {
1636
- const x = (seed >>> 0) + Math.imul(fnIndex + 1, 73244475) | 0;
1637
- const y = x ^ 1515870810 | 0;
2404
+ function createSharedDecoyDeclaration(decoyIdent = "_d") {
2405
+ return {
2406
+ type: "VariableDeclaration",
2407
+ kind: "var",
2408
+ declarations: [
2409
+ {
2410
+ type: "VariableDeclarator",
2411
+ id: { type: "Identifier", name: decoyIdent },
2412
+ init: {
2413
+ type: "ArrayExpression",
2414
+ elements: [0, 1, 2].map((m) => ({
2415
+ type: "ArrowFunctionExpression",
2416
+ id: null,
2417
+ params: [],
2418
+ body: createDecoyObjectExpression(m),
2419
+ generator: false,
2420
+ async: false,
2421
+ expression: true
2422
+ }))
2423
+ }
2424
+ }
2425
+ ]
2426
+ };
2427
+ }
2428
+ function cloneNode(node) {
2429
+ return JSON.parse(JSON.stringify(node));
2430
+ }
2431
+ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false) {
2432
+ const family = Math.abs(seed + fnIndex & 3);
2433
+ const c1 = (seed >>> 0) + Math.imul(family + 1, 73244475) | 0;
2434
+ const c2 = c1 ^ 1515870810 | 0;
2435
+ const target = (seed ^ Math.imul(family + 1, 2654435761)) & 8388607 | 1;
2436
+ let paramName = null;
2437
+ if (typeof paramNode === "string") {
2438
+ paramName = paramNode;
2439
+ } else if (paramNode?.type === "Identifier") {
2440
+ paramName = paramNode.name;
2441
+ } else if (paramNode?.type === "AssignmentPattern" && paramNode.left?.type === "Identifier") {
2442
+ paramName = paramNode.left.name;
2443
+ }
2444
+ const zNode = {
2445
+ type: "UnaryExpression",
2446
+ operator: "+",
2447
+ prefix: true,
2448
+ argument: {
2449
+ type: "UnaryExpression",
2450
+ operator: "!",
2451
+ prefix: true,
2452
+ argument: { type: "Identifier", name: "String" }
2453
+ }
2454
+ };
2455
+ const vNode = {
2456
+ type: "BinaryExpression",
2457
+ operator: "|",
2458
+ left: zNode,
2459
+ right: { type: "Literal", value: c1, raw: String(c1) }
2460
+ };
2461
+ const kNode = {
2462
+ type: "BinaryExpression",
2463
+ operator: "|",
2464
+ left: { type: "Literal", value: c2, raw: String(c2) },
2465
+ right: {
2466
+ type: "UnaryExpression",
2467
+ operator: "!",
2468
+ prefix: true,
2469
+ argument: { type: "Identifier", name: "String" }
2470
+ }
2471
+ };
2472
+ let mbaExpr;
2473
+ if (family === 0) {
2474
+ const vXorK = {
2475
+ type: "BinaryExpression",
2476
+ operator: "^",
2477
+ left: cloneNode(vNode),
2478
+ right: cloneNode(kNode)
2479
+ };
2480
+ const vAndK = {
2481
+ type: "BinaryExpression",
2482
+ operator: "&",
2483
+ left: cloneNode(vNode),
2484
+ right: cloneNode(kNode)
2485
+ };
2486
+ const shift = {
2487
+ type: "BinaryExpression",
2488
+ operator: "<<",
2489
+ left: vAndK,
2490
+ right: { type: "Literal", value: 1, raw: "1" }
2491
+ };
2492
+ const addLeft = {
2493
+ type: "BinaryExpression",
2494
+ operator: "+",
2495
+ left: vXorK,
2496
+ right: shift
2497
+ };
2498
+ const vPlusK = {
2499
+ type: "BinaryExpression",
2500
+ operator: "+",
2501
+ left: cloneNode(vNode),
2502
+ right: cloneNode(kNode)
2503
+ };
2504
+ mbaExpr = {
2505
+ type: "BinaryExpression",
2506
+ operator: "-",
2507
+ left: addLeft,
2508
+ right: vPlusK
2509
+ };
2510
+ } else if (family === 1) {
2511
+ const vOrK = {
2512
+ type: "BinaryExpression",
2513
+ operator: "|",
2514
+ left: cloneNode(vNode),
2515
+ right: cloneNode(kNode)
2516
+ };
2517
+ const vAndK = {
2518
+ type: "BinaryExpression",
2519
+ operator: "&",
2520
+ left: cloneNode(vNode),
2521
+ right: cloneNode(kNode)
2522
+ };
2523
+ const addLeft = {
2524
+ type: "BinaryExpression",
2525
+ operator: "+",
2526
+ left: vOrK,
2527
+ right: vAndK
2528
+ };
2529
+ const vPlusK = {
2530
+ type: "BinaryExpression",
2531
+ operator: "+",
2532
+ left: cloneNode(vNode),
2533
+ right: cloneNode(kNode)
2534
+ };
2535
+ mbaExpr = {
2536
+ type: "BinaryExpression",
2537
+ operator: "^",
2538
+ left: addLeft,
2539
+ right: vPlusK
2540
+ };
2541
+ } else if (family === 2) {
2542
+ const notK = {
2543
+ type: "UnaryExpression",
2544
+ operator: "~",
2545
+ prefix: true,
2546
+ argument: cloneNode(kNode)
2547
+ };
2548
+ const vOrNotK = {
2549
+ type: "BinaryExpression",
2550
+ operator: "|",
2551
+ left: cloneNode(vNode),
2552
+ right: cloneNode(notK)
2553
+ };
2554
+ const subLeft = {
2555
+ type: "BinaryExpression",
2556
+ operator: "-",
2557
+ left: vOrNotK,
2558
+ right: cloneNode(notK)
2559
+ };
2560
+ const vAndK = {
2561
+ type: "BinaryExpression",
2562
+ operator: "&",
2563
+ left: cloneNode(vNode),
2564
+ right: cloneNode(kNode)
2565
+ };
2566
+ mbaExpr = {
2567
+ type: "BinaryExpression",
2568
+ operator: "^",
2569
+ left: subLeft,
2570
+ right: vAndK
2571
+ };
2572
+ } else {
2573
+ const notK = {
2574
+ type: "UnaryExpression",
2575
+ operator: "~",
2576
+ prefix: true,
2577
+ argument: cloneNode(kNode)
2578
+ };
2579
+ const vAndNotK = {
2580
+ type: "BinaryExpression",
2581
+ operator: "&",
2582
+ left: cloneNode(vNode),
2583
+ right: cloneNode(notK)
2584
+ };
2585
+ const vAndK = {
2586
+ type: "BinaryExpression",
2587
+ operator: "&",
2588
+ left: cloneNode(vNode),
2589
+ right: cloneNode(kNode)
2590
+ };
2591
+ const addLeft = {
2592
+ type: "BinaryExpression",
2593
+ operator: "+",
2594
+ left: vAndNotK,
2595
+ right: vAndK
2596
+ };
2597
+ mbaExpr = {
2598
+ type: "BinaryExpression",
2599
+ operator: "^",
2600
+ left: addLeft,
2601
+ right: cloneNode(vNode)
2602
+ };
2603
+ }
2604
+ const decoyIdx = Math.abs(fnIndex) % 3;
2605
+ const consequent = decoyIdent ? createSharedDecoyConsequent(decoyIdent, decoyIdx) : createDecoyConsequent(decoyIdx);
1638
2606
  return {
1639
2607
  type: "IfStatement",
1640
2608
  test: {
1641
2609
  type: "BinaryExpression",
1642
2610
  operator: "===",
1643
- left: {
1644
- type: "BinaryExpression",
1645
- operator: "|",
1646
- left: {
1647
- type: "BinaryExpression",
1648
- operator: "^",
1649
- left: {
1650
- type: "BinaryExpression",
1651
- operator: "+",
1652
- left: {
1653
- type: "BinaryExpression",
1654
- operator: "|",
1655
- left: { type: "Literal", value: x, raw: String(x) },
1656
- right: { type: "Literal", value: y, raw: String(y) }
1657
- },
1658
- right: {
1659
- type: "BinaryExpression",
1660
- operator: "&",
1661
- left: { type: "Literal", value: x, raw: String(x) },
1662
- right: { type: "Literal", value: y, raw: String(y) }
1663
- }
1664
- },
1665
- right: {
1666
- type: "BinaryExpression",
1667
- operator: "+",
1668
- left: { type: "Literal", value: x, raw: String(x) },
1669
- right: { type: "Literal", value: y, raw: String(y) }
1670
- }
1671
- },
1672
- right: {
1673
- type: "UnaryExpression",
1674
- operator: "!",
1675
- prefix: true,
1676
- argument: { type: "Identifier", name: "String" }
1677
- }
1678
- },
1679
- right: { type: "Literal", value: 2147483647, raw: "0x7fffffff" }
2611
+ left: mbaExpr,
2612
+ right: { type: "Literal", value: target, raw: String(target) }
1680
2613
  },
1681
- consequent: createDecoyConsequent(fnIndex),
2614
+ consequent,
1682
2615
  alternate: null
1683
2616
  };
1684
2617
  }
1685
2618
  function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
2619
+ const decoyIdent = "_d";
2620
+ if (Array.isArray(ast.body)) {
2621
+ const alreadyGuarded = ast.body.some(
2622
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
2623
+ (d) => d.id?.type === "Identifier" && d.id.name === decoyIdent
2624
+ )
2625
+ );
2626
+ if (alreadyGuarded) return 0;
2627
+ }
1686
2628
  let guardedCount = 0;
1687
2629
  function maybeInjectGuard(node) {
1688
2630
  if (!coldFunctionNodes.has(node)) return;
1689
2631
  if (!node.body || node.body.type !== "BlockStatement") return;
1690
- const guardStmt = createSotaMbaPredicate(seed, 0);
2632
+ const firstParam = node.params?.[0];
2633
+ const isArrow = node.type === "ArrowFunctionExpression";
2634
+ const guardStmt = createSotaMbaPredicate(
2635
+ seed,
2636
+ guardedCount,
2637
+ firstParam,
2638
+ decoyIdent,
2639
+ isArrow
2640
+ );
1691
2641
  guardedCount++;
1692
2642
  if (hotExemptNodes) {
1693
2643
  hotExemptNodes.add(guardStmt);
@@ -1704,64 +2654,946 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
1704
2654
  FunctionExpression: maybeInjectGuard,
1705
2655
  ArrowFunctionExpression: maybeInjectGuard
1706
2656
  });
2657
+ if (guardedCount > 0 && Array.isArray(ast.body)) {
2658
+ const sharedDecoyDecl = createSharedDecoyDeclaration(decoyIdent);
2659
+ if (hotExemptNodes) {
2660
+ hotExemptNodes.add(sharedDecoyDecl);
2661
+ for (const decl of sharedDecoyDecl.declarations || []) {
2662
+ if (decl.init?.elements) {
2663
+ for (const el of decl.init.elements) {
2664
+ hotExemptNodes.add(el);
2665
+ }
2666
+ }
2667
+ }
2668
+ }
2669
+ let insertIdx = 0;
2670
+ while (insertIdx < ast.body.length && ast.body[insertIdx].type === "ExpressionStatement" && ast.body[insertIdx].directive) {
2671
+ insertIdx++;
2672
+ }
2673
+ ast.body.splice(insertIdx, 0, sharedDecoyDecl);
2674
+ }
1707
2675
  return guardedCount;
1708
2676
  }
1709
2677
 
1710
- // src/runtime/integrity-guard.ts
1711
- var FNV_OFFSET_BASIS = 2166136261;
1712
- var FNV_PRIME = 16777619;
1713
- function computeIntegrityHash(source, seed = 0) {
1714
- let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
1715
- for (let i = 0; i < source.length; i++) {
1716
- hash ^= source.charCodeAt(i);
1717
- hash = Math.imul(hash, FNV_PRIME) >>> 0;
2678
+ // src/ast/micro-vm.ts
2679
+ import * as acorn3 from "acorn";
2680
+ import * as walk5 from "acorn-walk";
2681
+ var OP_LDC = 0;
2682
+ var OP_LDV = 1;
2683
+ var OP_STV = 2;
2684
+ var OP_LDG = 3;
2685
+ var OP_GETP = 4;
2686
+ var OP_SETP = 5;
2687
+ var OP_CALL = 6;
2688
+ var OP_MCALL = 7;
2689
+ var OP_ADD = 8;
2690
+ var OP_SUB = 9;
2691
+ var OP_MUL = 10;
2692
+ var OP_XOR = 11;
2693
+ var OP_AND = 12;
2694
+ var OP_OR = 13;
2695
+ var OP_SEQ = 14;
2696
+ var OP_LT = 15;
2697
+ var OP_NOT = 16;
2698
+ var OP_JMP = 17;
2699
+ var OP_JZ = 18;
2700
+ var OP_RET = 19;
2701
+ var OP_THROW = 20;
2702
+ var OP_AWAIT = 21;
2703
+ var OP_OBJ = 22;
2704
+ var OP_ARR = 23;
2705
+ function generateOpcodeMap(seed) {
2706
+ const pool = [];
2707
+ for (let i = 0; i < 256; i++) pool.push(i);
2708
+ let s = (seed ^ 2779096485) >>> 0;
2709
+ function rand() {
2710
+ s ^= s << 13;
2711
+ s ^= s >>> 17;
2712
+ s ^= s << 5;
2713
+ return (s >>> 0) / 4294967296;
2714
+ }
2715
+ for (let i = pool.length - 1; i > 0; i--) {
2716
+ const j = Math.floor(rand() * (i + 1));
2717
+ const tmp = pool[i];
2718
+ pool[i] = pool[j];
2719
+ pool[j] = tmp;
2720
+ }
2721
+ return pool.slice(0, 24);
2722
+ }
2723
+ function createInterpreterSource(vmHelperName, opMap) {
2724
+ return `function ${vmHelperName}(c, k, s, t) {
2725
+ var p = 0, r = 0, q = [];
2726
+ var G = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this);
2727
+ function x() {
2728
+ while (p < c.length) {
2729
+ var o = c[p++];
2730
+ switch (o) {
2731
+ case ${opMap[OP_LDC]}: q[r++] = k[c[p++]]; break;
2732
+ case ${opMap[OP_LDV]}: q[r++] = s[c[p++]]; break;
2733
+ case ${opMap[OP_STV]}: s[c[p++]] = q[--r]; break;
2734
+ case ${opMap[OP_LDG]}: q[r++] = G[k[c[p++]]]; break;
2735
+ case ${opMap[OP_GETP]}: { var b = q[--r], a = q[--r]; q[r++] = a[b]; break; }
2736
+ case ${opMap[OP_SETP]}: { var v = q[--r], b = q[--r], a = q[--r]; q[r++] = (a[b] = v); break; }
2737
+ case ${opMap[OP_CALL]}: {
2738
+ var n = c[p++], g = [];
2739
+ for (var i = n - 1; i >= 0; i--) g[i] = q[--r];
2740
+ var f = q[--r]; q[r++] = f.apply(null, g); break;
2741
+ }
2742
+ case ${opMap[OP_MCALL]}: {
2743
+ var n = c[p++], g = [];
2744
+ for (var i = n - 1; i >= 0; i--) g[i] = q[--r];
2745
+ var b = q[--r], a = q[--r]; q[r++] = a[b].apply(a, g); break;
2746
+ }
2747
+ case ${opMap[OP_ADD]}: { var b = q[--r], a = q[--r]; q[r++] = a + b; break; }
2748
+ case ${opMap[OP_SUB]}: { var b = q[--r], a = q[--r]; q[r++] = a - b; break; }
2749
+ case ${opMap[OP_MUL]}: { var b = q[--r], a = q[--r]; q[r++] = a * b; break; }
2750
+ case ${opMap[OP_XOR]}: { var b = q[--r], a = q[--r]; q[r++] = a ^ b; break; }
2751
+ case ${opMap[OP_AND]}: { var b = q[--r], a = q[--r]; q[r++] = a & b; break; }
2752
+ case ${opMap[OP_OR]}: { var b = q[--r], a = q[--r]; q[r++] = a | b; break; }
2753
+ case ${opMap[OP_SEQ]}: { var b = q[--r], a = q[--r]; q[r++] = a === b; break; }
2754
+ case ${opMap[OP_LT]}: { var b = q[--r], a = q[--r]; q[r++] = a < b; break; }
2755
+ case ${opMap[OP_NOT]}: { q[r - 1] = !q[r - 1]; break; }
2756
+ case ${opMap[OP_JMP]}: { p = c[p]; break; }
2757
+ case ${opMap[OP_JZ]}: { var j = c[p++]; if (!q[--r]) p = j; break; }
2758
+ case ${opMap[OP_RET]}: return q[--r];
2759
+ case ${opMap[OP_THROW]}: throw q[--r];
2760
+ case ${opMap[OP_AWAIT]}: {
2761
+ var v = q[--r];
2762
+ return Promise.resolve(v).then(function(w) { q[r++] = w; return x(); });
2763
+ }
2764
+ case ${opMap[OP_OBJ]}: {
2765
+ var n = c[p++], o = {}, e = [];
2766
+ for (var i = 0; i < n; i++) { var v = q[--r], k0 = q[--r]; e.push([k0, v]); }
2767
+ for (var i = e.length - 1; i >= 0; i--) { o[e[i][0]] = e[i][1]; }
2768
+ q[r++] = o;
2769
+ break;
2770
+ }
2771
+ case ${opMap[OP_ARR]}: {
2772
+ var n = c[p++], a = [];
2773
+ for (var i = n - 1; i >= 0; i--) a[i] = q[--r];
2774
+ q[r++] = a;
2775
+ break;
2776
+ }
2777
+ }
2778
+ }
1718
2779
  }
1719
- return hash >>> 0;
2780
+ return x();
2781
+ }`;
1720
2782
  }
1721
-
1722
- // src/runtime/devtools-deterrent.ts
1723
- function deriveIntegrityFnName(seed) {
1724
- const hash = computeIntegrityHash(`unpeek:fn:${seed}`, seed);
1725
- return `_u$${hash.toString(36)}`;
2783
+ function countAstNodes(node) {
2784
+ let count = 0;
2785
+ walk5.full(node, () => {
2786
+ count++;
2787
+ });
2788
+ return count;
1726
2789
  }
1727
- function createDeterrentSnippet(config) {
1728
- const seed = config.seed >>> 0;
1729
- const deterrentMode = config.deterrentMode ?? "passive";
1730
- const fnName = deriveIntegrityFnName(seed);
1731
- const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=f=>0;" : "";
1732
- return `(function ${fnName}(w){if(w){try{(w.queueMicrotask||w.requestIdleCallback||(f=>f()))(function f(a){var s=Function.prototype.toString,n=w.navigator||0,t=s.call(s).indexOf('[native code]')<0||/\\n/.test(s.call(${fnName}))||n.webdriver||/HeadlessChrome/.test(n.userAgent);if(t){w.__unpeek_tampered=!0,w.__unpeek_seed=((w.__unpeek_seed||${seed})^1)>>>0,String.prototype._u=14;try{${consoleSilence}w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}});}catch(e){}}})(typeof window!=='undefined'&&window);`;
2790
+ function hasForbiddenConstructs(fnNode) {
2791
+ let forbidden = false;
2792
+ walk5.full(fnNode, (node) => {
2793
+ if (forbidden) return;
2794
+ const type = node.type;
2795
+ if (type === "JSXElement" || type === "JSXFragment" || type === "Super" || type === "YieldExpression") {
2796
+ forbidden = true;
2797
+ return;
2798
+ }
2799
+ if (type === "Identifier" && node.name === "arguments") {
2800
+ forbidden = true;
2801
+ return;
2802
+ }
2803
+ if (type === "MetaProperty" && node.meta?.name === "new" && node.property?.name === "target") {
2804
+ forbidden = true;
2805
+ return;
2806
+ }
2807
+ });
2808
+ return forbidden;
2809
+ }
2810
+ function compileFunctionToBytecode(fnNode, opMap) {
2811
+ const bytecode = [];
2812
+ const consts = [];
2813
+ const localMap = /* @__PURE__ */ new Map();
2814
+ let localCount = 0;
2815
+ for (const param of fnNode.params) {
2816
+ if (param.type !== "Identifier") return null;
2817
+ localMap.set(param.name, localCount++);
2818
+ }
2819
+ const bodyNodes = fnNode.body.type === "BlockStatement" ? fnNode.body.body : [fnNode.body];
2820
+ for (const stmt of bodyNodes) {
2821
+ if (stmt.type === "VariableDeclaration") {
2822
+ for (const decl of stmt.declarations) {
2823
+ if (decl.id.type === "Identifier") {
2824
+ if (!localMap.has(decl.id.name)) {
2825
+ localMap.set(decl.id.name, localCount++);
2826
+ }
2827
+ } else {
2828
+ return null;
2829
+ }
2830
+ }
2831
+ }
2832
+ }
2833
+ function addConst(val) {
2834
+ for (let i = 0; i < consts.length; i++) {
2835
+ if (consts[i] === val) return i;
2836
+ }
2837
+ const idx = consts.length;
2838
+ consts.push(val);
2839
+ return idx;
2840
+ }
2841
+ function emit(op, ...args) {
2842
+ bytecode.push(opMap[op]);
2843
+ for (const a of args) bytecode.push(a);
2844
+ }
2845
+ function compileExpr(node) {
2846
+ if (!node) return false;
2847
+ switch (node.type) {
2848
+ case "Literal": {
2849
+ const idx = addConst(node.value);
2850
+ emit(OP_LDC, idx);
2851
+ return true;
2852
+ }
2853
+ case "Identifier": {
2854
+ if (node.name === "undefined") {
2855
+ const idx = addConst(void 0);
2856
+ emit(OP_LDC, idx);
2857
+ } else if (localMap.has(node.name)) {
2858
+ emit(OP_LDV, localMap.get(node.name));
2859
+ } else {
2860
+ const idx = addConst(node.name);
2861
+ emit(OP_LDG, idx);
2862
+ }
2863
+ return true;
2864
+ }
2865
+ case "BinaryExpression": {
2866
+ if (node.operator === ">") {
2867
+ if (!compileExpr(node.right)) return false;
2868
+ if (!compileExpr(node.left)) return false;
2869
+ emit(OP_LT);
2870
+ return true;
2871
+ }
2872
+ if (node.operator === "<=") {
2873
+ if (!compileExpr(node.right)) return false;
2874
+ if (!compileExpr(node.left)) return false;
2875
+ emit(OP_LT);
2876
+ emit(OP_NOT);
2877
+ return true;
2878
+ }
2879
+ if (node.operator === ">=") {
2880
+ if (!compileExpr(node.left)) return false;
2881
+ if (!compileExpr(node.right)) return false;
2882
+ emit(OP_LT);
2883
+ emit(OP_NOT);
2884
+ return true;
2885
+ }
2886
+ if (!compileExpr(node.left)) return false;
2887
+ if (!compileExpr(node.right)) return false;
2888
+ switch (node.operator) {
2889
+ case "+":
2890
+ emit(OP_ADD);
2891
+ break;
2892
+ case "-":
2893
+ emit(OP_SUB);
2894
+ break;
2895
+ case "*":
2896
+ emit(OP_MUL);
2897
+ break;
2898
+ case "^":
2899
+ emit(OP_XOR);
2900
+ break;
2901
+ case "&":
2902
+ emit(OP_AND);
2903
+ break;
2904
+ case "|":
2905
+ emit(OP_OR);
2906
+ break;
2907
+ case "==":
2908
+ case "===":
2909
+ emit(OP_SEQ);
2910
+ break;
2911
+ case "!=":
2912
+ case "!==":
2913
+ emit(OP_SEQ);
2914
+ emit(OP_NOT);
2915
+ break;
2916
+ case "<":
2917
+ emit(OP_LT);
2918
+ break;
2919
+ default:
2920
+ return false;
2921
+ }
2922
+ return true;
2923
+ }
2924
+ case "UnaryExpression": {
2925
+ if (!compileExpr(node.argument)) return false;
2926
+ switch (node.operator) {
2927
+ case "!":
2928
+ emit(OP_NOT);
2929
+ break;
2930
+ case "-": {
2931
+ const neg1Idx = addConst(-1);
2932
+ emit(OP_LDC, neg1Idx);
2933
+ emit(OP_MUL);
2934
+ break;
2935
+ }
2936
+ case "+": {
2937
+ const zeroIdx = addConst(0);
2938
+ emit(OP_LDC, zeroIdx);
2939
+ emit(OP_ADD);
2940
+ break;
2941
+ }
2942
+ case "~": {
2943
+ const neg1Idx = addConst(-1);
2944
+ emit(OP_LDC, neg1Idx);
2945
+ emit(OP_XOR);
2946
+ break;
2947
+ }
2948
+ case "void": {
2949
+ const undefIdx2 = addConst(void 0);
2950
+ emit(OP_LDC, undefIdx2);
2951
+ break;
2952
+ }
2953
+ default:
2954
+ return false;
2955
+ }
2956
+ return true;
2957
+ }
2958
+ case "MemberExpression": {
2959
+ if (!compileExpr(node.object)) return false;
2960
+ if (node.computed) {
2961
+ if (!compileExpr(node.property)) return false;
2962
+ } else {
2963
+ const idx = addConst(node.property.name);
2964
+ emit(OP_LDC, idx);
2965
+ }
2966
+ emit(OP_GETP);
2967
+ return true;
2968
+ }
2969
+ case "CallExpression": {
2970
+ if (node.callee.type === "MemberExpression") {
2971
+ if (!compileExpr(node.callee.object)) return false;
2972
+ if (node.callee.computed) {
2973
+ if (!compileExpr(node.callee.property)) return false;
2974
+ } else {
2975
+ const idx = addConst(node.callee.property.name);
2976
+ emit(OP_LDC, idx);
2977
+ }
2978
+ for (const arg of node.arguments) {
2979
+ if (!compileExpr(arg)) return false;
2980
+ }
2981
+ emit(OP_MCALL, node.arguments.length);
2982
+ } else {
2983
+ if (!compileExpr(node.callee)) return false;
2984
+ for (const arg of node.arguments) {
2985
+ if (!compileExpr(arg)) return false;
2986
+ }
2987
+ emit(OP_CALL, node.arguments.length);
2988
+ }
2989
+ return true;
2990
+ }
2991
+ case "AssignmentExpression": {
2992
+ if (node.operator !== "=") return false;
2993
+ if (node.left.type === "Identifier") {
2994
+ if (!localMap.has(node.left.name)) return false;
2995
+ if (!compileExpr(node.right)) return false;
2996
+ emit(OP_STV, localMap.get(node.left.name));
2997
+ return true;
2998
+ }
2999
+ if (node.left.type === "MemberExpression") {
3000
+ if (!compileExpr(node.left.object)) return false;
3001
+ if (node.left.computed) {
3002
+ if (!compileExpr(node.left.property)) return false;
3003
+ } else {
3004
+ const idx = addConst(node.left.property.name);
3005
+ emit(OP_LDC, idx);
3006
+ }
3007
+ if (!compileExpr(node.right)) return false;
3008
+ emit(OP_SETP);
3009
+ return true;
3010
+ }
3011
+ return false;
3012
+ }
3013
+ case "ObjectExpression": {
3014
+ for (const prop of node.properties) {
3015
+ if (prop.type !== "Property") return false;
3016
+ if (prop.computed) {
3017
+ if (!compileExpr(prop.key)) return false;
3018
+ } else {
3019
+ const keyName = prop.key.name ?? prop.key.value;
3020
+ const idx = addConst(keyName);
3021
+ emit(OP_LDC, idx);
3022
+ }
3023
+ if (!compileExpr(prop.value)) return false;
3024
+ }
3025
+ emit(OP_OBJ, node.properties.length);
3026
+ return true;
3027
+ }
3028
+ case "ArrayExpression": {
3029
+ for (const elem of node.elements) {
3030
+ if (!compileExpr(elem)) return false;
3031
+ }
3032
+ emit(OP_ARR, node.elements.length);
3033
+ return true;
3034
+ }
3035
+ case "AwaitExpression": {
3036
+ if (!compileExpr(node.argument)) return false;
3037
+ emit(OP_AWAIT);
3038
+ return true;
3039
+ }
3040
+ default:
3041
+ return false;
3042
+ }
3043
+ }
3044
+ function compileStmt(stmt) {
3045
+ if (!stmt) return false;
3046
+ switch (stmt.type) {
3047
+ case "ReturnStatement": {
3048
+ if (stmt.argument) {
3049
+ if (!compileExpr(stmt.argument)) return false;
3050
+ } else {
3051
+ const idx = addConst(void 0);
3052
+ emit(OP_LDC, idx);
3053
+ }
3054
+ emit(OP_RET);
3055
+ return true;
3056
+ }
3057
+ case "ExpressionStatement": {
3058
+ if (!compileExpr(stmt.expression)) return false;
3059
+ return true;
3060
+ }
3061
+ case "VariableDeclaration": {
3062
+ for (const decl of stmt.declarations) {
3063
+ if (decl.init) {
3064
+ if (!compileExpr(decl.init)) return false;
3065
+ emit(OP_STV, localMap.get(decl.id.name));
3066
+ }
3067
+ }
3068
+ return true;
3069
+ }
3070
+ case "IfStatement": {
3071
+ if (!compileExpr(stmt.test)) return false;
3072
+ const jzPos = bytecode.length;
3073
+ emit(OP_JZ, 0);
3074
+ if (!compileStmt(stmt.consequent)) return false;
3075
+ if (stmt.alternate) {
3076
+ const jmpPos = bytecode.length;
3077
+ emit(OP_JMP, 0);
3078
+ bytecode[jzPos + 1] = bytecode.length;
3079
+ if (!compileStmt(stmt.alternate)) return false;
3080
+ bytecode[jmpPos + 1] = bytecode.length;
3081
+ } else {
3082
+ bytecode[jzPos + 1] = bytecode.length;
3083
+ }
3084
+ return true;
3085
+ }
3086
+ case "BlockStatement": {
3087
+ for (const s of stmt.body) {
3088
+ if (!compileStmt(s)) return false;
3089
+ }
3090
+ return true;
3091
+ }
3092
+ default:
3093
+ return false;
3094
+ }
3095
+ }
3096
+ if (fnNode.body.type === "BlockStatement") {
3097
+ if (!compileStmt(fnNode.body)) return null;
3098
+ } else {
3099
+ if (!compileExpr(fnNode.body)) return null;
3100
+ emit(OP_RET);
3101
+ }
3102
+ const undefIdx = addConst(void 0);
3103
+ emit(OP_LDC, undefIdx);
3104
+ emit(OP_RET);
3105
+ return { bytecode, consts, localCount };
3106
+ }
3107
+ function isMicroVmAlreadyInjected(ast) {
3108
+ if (!ast || !Array.isArray(ast.body)) return false;
3109
+ return ast.body.some((stmt) => {
3110
+ if (stmt.type === "FunctionDeclaration" && typeof stmt.id?.name === "string" && stmt.id.name.startsWith("_uVm")) {
3111
+ return true;
3112
+ }
3113
+ return false;
3114
+ });
3115
+ }
3116
+ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769) {
3117
+ const suffix = computeFnv1aHash(`micro-vm:${seed}`, seed).toString(36);
3118
+ const vmHelperName = `_uVm${suffix}`;
3119
+ if (isMicroVmAlreadyInjected(ast)) {
3120
+ const existing = ast.body.find(
3121
+ (stmt) => stmt.type === "FunctionDeclaration" && typeof stmt.id?.name === "string" && stmt.id.name.startsWith("_uVm")
3122
+ );
3123
+ return {
3124
+ virtualizedCount: 0,
3125
+ vmHelperName: existing?.id?.name ?? vmHelperName
3126
+ };
3127
+ }
3128
+ const opMap = generateOpcodeMap(seed);
3129
+ const candidates = [];
3130
+ walk5.simple(ast, {
3131
+ FunctionDeclaration(node) {
3132
+ candidates.push(node);
3133
+ },
3134
+ FunctionExpression(node) {
3135
+ candidates.push(node);
3136
+ },
3137
+ ArrowFunctionExpression(node) {
3138
+ candidates.push(node);
3139
+ }
3140
+ });
3141
+ let virtualizedCount = 0;
3142
+ for (const fn of candidates) {
3143
+ if (virtualizedCount >= 10) break;
3144
+ if (coldFunctionNodes && !coldFunctionNodes.has(fn)) {
3145
+ continue;
3146
+ }
3147
+ if (serializedFunctionNodes && serializedFunctionNodes.has(fn)) {
3148
+ continue;
3149
+ }
3150
+ if (fn.generator) {
3151
+ continue;
3152
+ }
3153
+ if (hasForbiddenConstructs(fn)) {
3154
+ continue;
3155
+ }
3156
+ const nodeCount = countAstNodes(fn);
3157
+ if (nodeCount < 15 || nodeCount > 80) {
3158
+ continue;
3159
+ }
3160
+ const compiled = compileFunctionToBytecode(fn, opMap);
3161
+ if (!compiled) {
3162
+ continue;
3163
+ }
3164
+ const paramArgs = fn.params.map((p) => ({
3165
+ type: "Identifier",
3166
+ name: p.name
3167
+ }));
3168
+ const callExpr = {
3169
+ type: "CallExpression",
3170
+ callee: {
3171
+ type: "Identifier",
3172
+ name: vmHelperName
3173
+ },
3174
+ arguments: [
3175
+ {
3176
+ type: "ArrayExpression",
3177
+ elements: compiled.bytecode.map((b) => ({
3178
+ type: "Literal",
3179
+ value: b,
3180
+ raw: String(b)
3181
+ }))
3182
+ },
3183
+ {
3184
+ type: "ArrayExpression",
3185
+ elements: compiled.consts.map((c) => ({
3186
+ type: "Literal",
3187
+ value: c,
3188
+ raw: c === void 0 ? "void 0" : JSON.stringify(c)
3189
+ }))
3190
+ },
3191
+ {
3192
+ type: "ArrayExpression",
3193
+ elements: paramArgs
3194
+ },
3195
+ {
3196
+ type: "ThisExpression"
3197
+ }
3198
+ ],
3199
+ optional: false
3200
+ };
3201
+ if (fn.body.type === "BlockStatement") {
3202
+ fn.body.body = [
3203
+ {
3204
+ type: "ReturnStatement",
3205
+ argument: callExpr
3206
+ }
3207
+ ];
3208
+ } else {
3209
+ fn.body = callExpr;
3210
+ }
3211
+ virtualizedCount++;
3212
+ }
3213
+ if (virtualizedCount > 0) {
3214
+ const interpreterSource = createInterpreterSource(vmHelperName, opMap);
3215
+ const parsedHelper = acorn3.parse(interpreterSource, {
3216
+ ecmaVersion: "latest",
3217
+ sourceType: "script"
3218
+ });
3219
+ ast.body.unshift(...parsedHelper.body);
3220
+ }
3221
+ return {
3222
+ virtualizedCount,
3223
+ vmHelperName
3224
+ };
1733
3225
  }
1734
3226
 
1735
- // src/runtime/index.ts
1736
- function generateRuntimeShield(config) {
1737
- const preambleCode = createDeterrentSnippet(config);
1738
- const integrityCheckFnName = deriveIntegrityFnName(config.seed);
1739
- const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computeIntegrityHash(preambleCode, config.seed);
3227
+ // src/ast/wasm-vault.ts
3228
+ import * as acorn4 from "acorn";
3229
+ function encodeSignedLeb128(value) {
3230
+ const bytes = [];
3231
+ let val = value | 0;
3232
+ let more = true;
3233
+ while (more) {
3234
+ let byte = val & 127;
3235
+ val >>= 7;
3236
+ if (val === 0 && (byte & 64) === 0 || val === -1 && (byte & 64) !== 0) {
3237
+ more = false;
3238
+ } else {
3239
+ byte |= 128;
3240
+ }
3241
+ bytes.push(byte);
3242
+ }
3243
+ return bytes;
3244
+ }
3245
+ function encodeUnsignedLeb128(value) {
3246
+ const bytes = [];
3247
+ let val = value >>> 0;
3248
+ do {
3249
+ let byte = val & 127;
3250
+ val >>>= 7;
3251
+ if (val !== 0) {
3252
+ byte |= 128;
3253
+ }
3254
+ bytes.push(byte);
3255
+ } while (val !== 0);
3256
+ return bytes;
3257
+ }
3258
+ function generateWasmKdfBinary(seed) {
3259
+ const instructions = [
3260
+ 32,
3261
+ 0,
3262
+ // local.get 0
3263
+ 65,
3264
+ ...encodeSignedLeb128(seed),
3265
+ // i32.const seed
3266
+ 115,
3267
+ // i32.xor
3268
+ 65,
3269
+ ...encodeSignedLeb128(16777619),
3270
+ // i32.const 0x01000193
3271
+ 108,
3272
+ // i32.mul
3273
+ 32,
3274
+ 1,
3275
+ // local.get 1
3276
+ 32,
3277
+ 2,
3278
+ // local.get 2
3279
+ 106,
3280
+ // i32.add
3281
+ 65,
3282
+ ...encodeSignedLeb128(73244475),
3283
+ // i32.const 0x45d9f3b
3284
+ 108,
3285
+ // i32.mul
3286
+ 115,
3287
+ // i32.xor
3288
+ 11
3289
+ // end
3290
+ ];
3291
+ const funcBody = [0, ...instructions];
3292
+ const funcBodyWithLen = [...encodeUnsignedLeb128(funcBody.length), ...funcBody];
3293
+ const codeSectionPayload = [1, ...funcBodyWithLen];
3294
+ const codeSection = [
3295
+ 10,
3296
+ ...encodeUnsignedLeb128(codeSectionPayload.length),
3297
+ ...codeSectionPayload
3298
+ ];
3299
+ const typePayload = [
3300
+ 1,
3301
+ // 1 type
3302
+ 96,
3303
+ // func
3304
+ 3,
3305
+ 127,
3306
+ 127,
3307
+ 127,
3308
+ // 3 params of type i32
3309
+ 1,
3310
+ 127
3311
+ // 1 result of type i32
3312
+ ];
3313
+ const typeSection = [
3314
+ 1,
3315
+ ...encodeUnsignedLeb128(typePayload.length),
3316
+ ...typePayload
3317
+ ];
3318
+ const funcPayload = [
3319
+ 1,
3320
+ // 1 function
3321
+ 0
3322
+ // type index 0
3323
+ ];
3324
+ const funcSection = [
3325
+ 3,
3326
+ ...encodeUnsignedLeb128(funcPayload.length),
3327
+ ...funcPayload
3328
+ ];
3329
+ const exportName = [3, 107, 100, 102];
3330
+ const exportPayload = [
3331
+ 1,
3332
+ // 1 export
3333
+ ...exportName,
3334
+ 0,
3335
+ // function export
3336
+ 0
3337
+ // function index 0
3338
+ ];
3339
+ const exportSection = [
3340
+ 7,
3341
+ ...encodeUnsignedLeb128(exportPayload.length),
3342
+ ...exportPayload
3343
+ ];
3344
+ const header = [0, 97, 115, 109, 1, 0, 0, 0];
3345
+ return new Uint8Array([
3346
+ ...header,
3347
+ ...typeSection,
3348
+ ...funcSection,
3349
+ ...exportSection,
3350
+ ...codeSection
3351
+ ]);
3352
+ }
3353
+ function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
3354
+ return Math.imul(fnId ^ seed | 0, 16777619) ^ Math.imul(callSiteSalt + shieldHash | 0, 73244475) | 0;
3355
+ }
3356
+ function isWasmVaultAlreadyInjected(ast) {
3357
+ if (!ast || !Array.isArray(ast.body)) return false;
3358
+ return ast.body.some((stmt) => {
3359
+ if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3360
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
3361
+ )) {
3362
+ return true;
3363
+ }
3364
+ return false;
3365
+ });
3366
+ }
3367
+ function injectWasmVault(ast, seed = 2654435769) {
3368
+ const suffix = computeFnv1aHash(`wasm:${seed}`, seed).toString(36);
3369
+ const kdfFnName = `_wKdf${suffix}`;
3370
+ const wasmVarName = `_wb${suffix}`;
3371
+ if (isWasmVaultAlreadyInjected(ast)) {
3372
+ const existing = ast.body.find(
3373
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3374
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
3375
+ )
3376
+ );
3377
+ const id = existing?.declarations[0]?.id?.name ?? kdfFnName;
3378
+ return {
3379
+ kdfFnName: id,
3380
+ wasmBytes: generateWasmKdfBinary(seed),
3381
+ wasmVarName
3382
+ };
3383
+ }
3384
+ const wasmBytes = generateWasmKdfBinary(seed);
3385
+ const byteArrayLiteral = Array.from(wasmBytes).join(",");
3386
+ const helperSnippet = `var ${kdfFnName};
3387
+ try {
3388
+ var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
3389
+ var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
3390
+ var _wi${suffix} = new WebAssembly.Instance(_wm${suffix});
3391
+ ${kdfFnName} = _wi${suffix}.exports.kdf;
3392
+ } catch (e) {
3393
+ ${kdfFnName} = function(f, s, h) {
3394
+ return (Math.imul((f ^ ${seed | 0}) | 0, 16777619) ^ Math.imul(((s + h) | 0), 73244475)) | 0;
3395
+ };
3396
+ }`;
3397
+ const parsedHelper = acorn4.parse(helperSnippet, {
3398
+ ecmaVersion: "latest",
3399
+ sourceType: "script"
3400
+ });
3401
+ ast.body.unshift(...parsedHelper.body);
1740
3402
  return {
1741
- preambleCode,
1742
- integrityCheckFnName,
1743
- expectedHash
3403
+ kdfFnName,
3404
+ wasmBytes,
3405
+ wasmVarName
1744
3406
  };
1745
3407
  }
1746
3408
 
1747
- // src/ast/index.ts
1748
- function isAstAlreadyProtected(ast) {
3409
+ // src/ast/salted-vault.ts
3410
+ import * as acorn5 from "acorn";
3411
+ import * as walk6 from "acorn-walk";
3412
+ var DIRECTIVE_STRINGS2 = /* @__PURE__ */ new Set([
3413
+ "use strict",
3414
+ "use client",
3415
+ "use server",
3416
+ "use asm"
3417
+ ]);
3418
+ function encodeSaltedString(str, k) {
3419
+ let out = "";
3420
+ for (let j = 0; j < str.length; j++) {
3421
+ const code = str.charCodeAt(j);
3422
+ const mask = k >>> j % 24 & 127 | 1;
3423
+ out += String.fromCharCode(code ^ mask);
3424
+ }
3425
+ return out;
3426
+ }
3427
+ function isAstAlreadySalted(ast) {
1749
3428
  if (!ast || !Array.isArray(ast.body)) return false;
1750
3429
  return ast.body.some((stmt) => {
1751
3430
  if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1752
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
3431
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uP")
1753
3432
  )) {
1754
3433
  return true;
1755
3434
  }
1756
- 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$")) {
3435
+ return false;
3436
+ });
3437
+ }
3438
+ function replaceNodeInParent(parent, oldNode, newNode) {
3439
+ if (!parent) return false;
3440
+ for (const key of Object.keys(parent)) {
3441
+ const val = parent[key];
3442
+ if (val === oldNode) {
3443
+ parent[key] = newNode;
1757
3444
  return true;
1758
3445
  }
3446
+ if (Array.isArray(val)) {
3447
+ const idx = val.indexOf(oldNode);
3448
+ if (idx !== -1) {
3449
+ val[idx] = newNode;
3450
+ return true;
3451
+ }
3452
+ }
3453
+ }
3454
+ return false;
3455
+ }
3456
+ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
3457
+ if (isAstAlreadySalted(ast)) {
3458
+ return {
3459
+ encryptedStringsCount: 0,
3460
+ integrityToken: computeFnv1aHash("already-salted", seed),
3461
+ vaultVarName: "",
3462
+ decryptFnName: ""
3463
+ };
3464
+ }
3465
+ const targetsToReplace = [];
3466
+ const encryptedPayloads = [];
3467
+ walk6.ancestor(ast, {
3468
+ Literal(node, ancestors) {
3469
+ if (typeof node.value !== "string") return;
3470
+ if (node.value.length < minStringLength) return;
3471
+ if (DIRECTIVE_STRINGS2.has(node.value)) return;
3472
+ const parent = ancestors[ancestors.length - 2];
3473
+ if (!parent) return;
3474
+ if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration") && parent.source === node) {
3475
+ return;
3476
+ }
3477
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
3478
+ return;
3479
+ }
3480
+ if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
3481
+ return;
3482
+ }
3483
+ if (hotExemptNodes) {
3484
+ for (let i = ancestors.length - 1; i >= 0; i--) {
3485
+ if (hotExemptNodes.has(ancestors[i])) {
3486
+ return;
3487
+ }
3488
+ }
3489
+ }
3490
+ const callSiteIdx = targetsToReplace.length;
3491
+ const localSalt = computeFnv1aHash(`salt:${seed}:${callSiteIdx}`, seed) & 2147483647 | 1;
3492
+ targetsToReplace.push({
3493
+ node,
3494
+ parent,
3495
+ callSiteIdx,
3496
+ localSalt,
3497
+ rawString: node.value
3498
+ });
3499
+ }
3500
+ });
3501
+ if (targetsToReplace.length === 0) {
3502
+ return {
3503
+ encryptedStringsCount: 0,
3504
+ integrityToken: computeFnv1aHash("empty-salted", seed),
3505
+ vaultVarName: "",
3506
+ decryptFnName: ""
3507
+ };
3508
+ }
3509
+ const wasmResult = injectWasmVault(ast, seed);
3510
+ const kdfFnName = wasmResult.kdfFnName;
3511
+ const suffix = computeFnv1aHash(`salted:${seed}`, seed).toString(36);
3512
+ const vaultVarName = `_uP${suffix}`;
3513
+ const cacheVarName = `_uCache${suffix}`;
3514
+ const decryptFnName = `_uD${suffix}`;
3515
+ for (const target of targetsToReplace) {
3516
+ const k = fallbackKdf(target.callSiteIdx, target.localSalt, 0, seed);
3517
+ encryptedPayloads.push(encodeSaltedString(target.rawString, k));
3518
+ const callExpr = {
3519
+ type: "CallExpression",
3520
+ callee: {
3521
+ type: "Identifier",
3522
+ name: decryptFnName
3523
+ },
3524
+ arguments: [
3525
+ {
3526
+ type: "Literal",
3527
+ value: target.callSiteIdx,
3528
+ raw: String(target.callSiteIdx)
3529
+ },
3530
+ {
3531
+ type: "Literal",
3532
+ value: target.localSalt,
3533
+ raw: String(target.localSalt)
3534
+ }
3535
+ ],
3536
+ optional: false
3537
+ };
3538
+ replaceNodeInParent(target.parent, target.node, callExpr);
3539
+ }
3540
+ const serializedTable = JSON.stringify(encryptedPayloads);
3541
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
3542
+ const helperSnippet = `var ${vaultVarName} = ${serializedTable};
3543
+ var ${cacheVarName} = [];
3544
+ function ${decryptFnName}(i, s) {
3545
+ if (${cacheVarName}[i] !== void 0) return ${cacheVarName}[i];
3546
+ var d = typeof window !== 'undefined' && window.__unpeek_delta != null ? window.__unpeek_delta : 0;
3547
+ var k = ${kdfFnName}(i, s, d);
3548
+ var p = ${vaultVarName}[i], o = '';
3549
+ for (var j = 0; j < p.length; j++) {
3550
+ o += String.fromCharCode(p.charCodeAt(j) ^ (((k >>> (j % 24)) & 127) | 1));
3551
+ }
3552
+ return (${cacheVarName}[i] = o);
3553
+ }`;
3554
+ const parsedHelper = acorn5.parse(helperSnippet, {
3555
+ ecmaVersion: "latest",
3556
+ sourceType: "script"
3557
+ });
3558
+ ast.body.unshift(...parsedHelper.body);
3559
+ return {
3560
+ encryptedStringsCount: targetsToReplace.length,
3561
+ integrityToken,
3562
+ vaultVarName,
3563
+ decryptFnName
3564
+ };
3565
+ }
3566
+
3567
+ // src/ast/index.ts
3568
+ function isAstAlreadyProtected(ast) {
3569
+ if (!ast || !Array.isArray(ast.body)) return false;
3570
+ return ast.body.some((stmt) => {
3571
+ if (stmt.type === "VariableDeclaration" && Array.isArray(stmt.declarations)) {
3572
+ for (const d of stmt.declarations) {
3573
+ const name = d.id?.name;
3574
+ if (typeof name === "string") {
3575
+ if (name === "_d" || name.startsWith("_uC") || name.startsWith("_uD") || name.startsWith("_uS") || name.startsWith("_uVm") || name.startsWith("_wKdf") || name.startsWith("_m") || name.startsWith("_w") || name.startsWith("_k") || name.startsWith("_a") && d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f") {
3576
+ return true;
3577
+ }
3578
+ }
3579
+ }
3580
+ }
3581
+ if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression") {
3582
+ const callee = stmt.expression.callee;
3583
+ if (callee?.type === "FunctionExpression") {
3584
+ const name = callee.id?.name;
3585
+ if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b"))) {
3586
+ return true;
3587
+ }
3588
+ }
3589
+ }
1759
3590
  return false;
1760
3591
  });
1761
3592
  }
1762
3593
  function transformJavaScript(code, options = {}) {
1763
3594
  const seed = options.seed ?? 2654435769;
1764
3595
  const minStringLength = options.minStringLength ?? 4;
3596
+ const isAggressive = options.aggressive ?? false;
1765
3597
  if (!code || !code.trim()) {
1766
3598
  return {
1767
3599
  code,
@@ -1772,7 +3604,9 @@ function transformJavaScript(code, options = {}) {
1772
3604
  hotFunctionsSkipped: [],
1773
3605
  coldFunctionsProtected: []
1774
3606
  },
1775
- integrityToken: computeFnv1aHash("", seed)
3607
+ integrityToken: computeFnv1aHash("", seed),
3608
+ virtualizedFunctionsCount: 0,
3609
+ shaderBuffersCount: 0
1776
3610
  };
1777
3611
  }
1778
3612
  const ast = parseJavaScriptAst(code);
@@ -1786,23 +3620,59 @@ function transformJavaScript(code, options = {}) {
1786
3620
  hotFunctionsSkipped: [],
1787
3621
  coldFunctionsProtected: []
1788
3622
  },
1789
- integrityToken: computeFnv1aHash(code, seed)
3623
+ integrityToken: computeFnv1aHash(code, seed),
3624
+ virtualizedFunctionsCount: 0,
3625
+ shaderBuffersCount: 0
1790
3626
  };
1791
3627
  }
1792
3628
  const {
1793
3629
  report: hotPathReport,
1794
3630
  coldFunctionNodes,
1795
- hotExemptNodes
3631
+ hotFunctionNodes,
3632
+ hotExemptNodes,
3633
+ serializedFunctionNodes
1796
3634
  } = analyzeAstHotPaths(ast);
3635
+ let virtualizedFunctionsCount = 0;
3636
+ if (isAggressive) {
3637
+ const vmRes = applyMicroVm(
3638
+ ast,
3639
+ coldFunctionNodes,
3640
+ serializedFunctionNodes,
3641
+ seed
3642
+ );
3643
+ virtualizedFunctionsCount = vmRes.virtualizedCount;
3644
+ }
1797
3645
  applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
1798
- const mangledSymbolsCount = applyPolymorphicMangler(ast, seed);
1799
- const { encryptedStringsCount, integrityToken } = applyStringVault(
3646
+ const mangledSymbolsCount = applyPolymorphicMangler(
1800
3647
  ast,
1801
3648
  seed,
1802
- minStringLength,
1803
- hotExemptNodes
3649
+ serializedFunctionNodes
1804
3650
  );
1805
- const outputCode = generate(ast, { indent: "", lineEnd: "" });
3651
+ let encryptedStringsCount = 0;
3652
+ let integrityToken = 0;
3653
+ let shaderBuffersCount = 0;
3654
+ if (isAggressive) {
3655
+ injectWasmVault(ast, seed);
3656
+ const saltedRes = applySaltedStringVault(
3657
+ ast,
3658
+ seed,
3659
+ minStringLength,
3660
+ hotExemptNodes
3661
+ );
3662
+ encryptedStringsCount = saltedRes.encryptedStringsCount;
3663
+ integrityToken = saltedRes.integrityToken;
3664
+ } else {
3665
+ const vaultRes = applyStringVault(
3666
+ ast,
3667
+ seed,
3668
+ minStringLength,
3669
+ hotExemptNodes
3670
+ );
3671
+ encryptedStringsCount = vaultRes.encryptedStringsCount;
3672
+ integrityToken = vaultRes.integrityToken;
3673
+ shaderBuffersCount = vaultRes.shaderBuffersCount ?? 0;
3674
+ }
3675
+ const outputCode = generateCompactJs(ast);
1806
3676
  let finalCode = outputCode;
1807
3677
  if (options.injectRuntimeShield) {
1808
3678
  const shield = generateRuntimeShield({
@@ -1820,11 +3690,29 @@ ${finalCode}`;
1820
3690
  encryptedStringsCount,
1821
3691
  mangledSymbolsCount,
1822
3692
  hotPathReport,
1823
- integrityToken
3693
+ integrityToken,
3694
+ virtualizedFunctionsCount,
3695
+ shaderBuffersCount
1824
3696
  };
1825
3697
  }
1826
3698
 
1827
3699
  // src/cli/protect.ts
3700
+ var ENTRY_PATTERN = /^(?:main|index|turbopack|webpack|runtime|app\/layout|app\/page|pages\/_app|pages\/index)[-._/]/i;
3701
+ function isEntryChunk(relPath, index, allRelPaths) {
3702
+ const norm = relPath.replace(/\\/g, "/");
3703
+ const base2 = path4.basename(norm);
3704
+ if (ENTRY_PATTERN.test(norm) || ENTRY_PATTERN.test(base2)) {
3705
+ return true;
3706
+ }
3707
+ const hasAnyPatternMatch = allRelPaths.some((p) => {
3708
+ const n = p.replace(/\\/g, "/");
3709
+ return ENTRY_PATTERN.test(n) || ENTRY_PATTERN.test(path4.basename(n));
3710
+ });
3711
+ if (!hasAnyPatternMatch && index === 0) {
3712
+ return true;
3713
+ }
3714
+ return false;
3715
+ }
1828
3716
  async function protectProject(options = {}) {
1829
3717
  const startTime = performance.now();
1830
3718
  const cwd = path4.resolve(options.cwd ?? process.cwd());
@@ -1835,8 +3723,10 @@ async function protectProject(options = {}) {
1835
3723
  const deterrentMode = options.deterrentMode ?? "passive";
1836
3724
  const injectRuntimeShield = options.injectRuntimeShield ?? true;
1837
3725
  const minStringLength = options.minStringLength ?? 4;
3726
+ const aggressive = options.aggressive ?? false;
1838
3727
  const vaultResult = relocateSourceMaps(outDir, cwd, keepPrivateMaps, privateMapsDir, false);
1839
3728
  const clientFiles = scanClientBundles(outDir);
3729
+ const allRelPaths = clientFiles.map((f) => path4.relative(outDir, f).replace(/\\/g, "/"));
1840
3730
  let originalBytes = 0;
1841
3731
  let protectedBytes = 0;
1842
3732
  let totalHotFunctionsSkipped = 0;
@@ -1858,23 +3748,26 @@ async function protectProject(options = {}) {
1858
3748
  const origBuf = Buffer.from(codeToTransform, "utf8");
1859
3749
  originalBytes += origBuf.byteLength;
1860
3750
  allOrigBufs.push(origBuf);
1861
- const relPath = path4.relative(outDir, filePath).replace(/\\/g, "/");
3751
+ const relPath = allRelPaths[i];
3752
+ const isEntry = isEntryChunk(relPath, i, allRelPaths);
3753
+ const shouldInjectShield = injectRuntimeShield && isEntry;
1862
3754
  const fileSeed = computeFnv1aHash(`${relPath}:${i}`, seed);
1863
3755
  const result = transformJavaScript(codeToTransform, {
1864
3756
  seed: fileSeed,
1865
3757
  minStringLength,
1866
3758
  filename: path4.basename(filePath),
1867
- injectRuntimeShield,
1868
- deterrentMode
3759
+ injectRuntimeShield: shouldInjectShield,
3760
+ deterrentMode,
3761
+ aggressive
1869
3762
  });
1870
3763
  let finalCode = result.code;
1871
- if (injectRuntimeShield) {
3764
+ if (shouldInjectShield && !finalCode.includes("__unpeek_tampered")) {
1872
3765
  const shield = generateRuntimeShield({
1873
3766
  seed: fileSeed,
1874
3767
  deterrentMode,
1875
3768
  expectedIntegrityHash: result.integrityToken
1876
3769
  });
1877
- if (shield.preambleCode && !finalCode.includes("(function _u$") && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
3770
+ if (shield.preambleCode && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
1878
3771
  finalCode = `${shield.preambleCode}
1879
3772
  ${finalCode}`;
1880
3773
  }
@@ -1928,7 +3821,7 @@ ${finalCode}`;
1928
3821
  }
1929
3822
 
1930
3823
  // src/cli/index.ts
1931
- var VERSION = "1.7.2";
3824
+ var VERSION = "1.8.2";
1932
3825
  function getPackageVersion() {
1933
3826
  try {
1934
3827
  const pkgUrl = new URL("../../package.json", import.meta.url);
@@ -1983,6 +3876,7 @@ function printHelp() {
1983
3876
  " --min-string-length <num> minimum string length for the vault (default: 4)",
1984
3877
  " --private-maps-dir <dir> vault directory (default: .unpeek-maps)",
1985
3878
  " --no-shield skip the runtime anti-tamper shield",
3879
+ " --aggressive enable Layer 2 aggressive protection (Micro-VM & WASM KDF)",
1986
3880
  " -h, --help show help",
1987
3881
  " -v, --version show version"
1988
3882
  ].join("\n");
@@ -2107,6 +4001,8 @@ async function runCli(args) {
2107
4001
  options.privateMapsDir = args[++i];
2108
4002
  } else if (arg.startsWith("--private-maps-dir=")) {
2109
4003
  options.privateMapsDir = arg.slice("--private-maps-dir=".length);
4004
+ } else if (arg === "--aggressive") {
4005
+ options.aggressive = true;
2110
4006
  } else if (arg === "--no-shield") {
2111
4007
  options.injectRuntimeShield = false;
2112
4008
  } else if (arg === "--passive") {