unpeek 3.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +27 -13
  2. package/README.tr.md +37 -23
  3. package/dist/adapters/esbuild.cjs +5 -5
  4. package/dist/adapters/esbuild.d.cts +3 -1
  5. package/dist/adapters/esbuild.d.ts +2 -2
  6. package/dist/adapters/esbuild.js +5 -3
  7. package/dist/adapters/next/adapter.cjs +7 -6
  8. package/dist/adapters/next/adapter.d.cts +1 -1
  9. package/dist/adapters/next/adapter.d.ts +1 -1
  10. package/dist/adapters/next/adapter.js +6 -5
  11. package/dist/adapters/next/index.cjs +7 -6
  12. package/dist/adapters/next/index.js +6 -5
  13. package/dist/adapters/rollup.cjs +5 -5
  14. package/dist/adapters/rollup.d.cts +3 -1
  15. package/dist/adapters/rollup.d.ts +2 -2
  16. package/dist/adapters/rollup.js +5 -3
  17. package/dist/adapters/rspack.cjs +5 -4
  18. package/dist/adapters/rspack.d.cts +1 -1
  19. package/dist/adapters/rspack.d.ts +1 -1
  20. package/dist/adapters/rspack.js +3 -2
  21. package/dist/adapters/vite.cjs +5 -5
  22. package/dist/adapters/vite.d.cts +3 -1
  23. package/dist/adapters/vite.d.ts +2 -2
  24. package/dist/adapters/vite.js +5 -3
  25. package/dist/adapters/webpack.cjs +5 -5
  26. package/dist/adapters/webpack.d.cts +3 -1
  27. package/dist/adapters/webpack.d.ts +2 -2
  28. package/dist/adapters/webpack.js +5 -3
  29. package/dist/browser.cjs +3 -3
  30. package/dist/browser.d.cts +20 -17
  31. package/dist/browser.d.ts +20 -17
  32. package/dist/browser.js +2 -2
  33. package/dist/{chunk-BPRSCRUZ.js → chunk-2JU3V7HW.js} +6 -3
  34. package/dist/chunk-3LWXEJU6.cjs +1054 -0
  35. package/dist/{chunk-IZIWDJRF.js → chunk-4FNZNIBW.js} +2675 -651
  36. package/dist/chunk-7HXLHLLQ.cjs +503 -0
  37. package/dist/chunk-ADKRENAP.js +1054 -0
  38. package/dist/{chunk-FCF2EGPM.js → chunk-EN6QVR6P.js} +12 -3
  39. package/dist/chunk-HHC7BUCK.js +503 -0
  40. package/dist/{chunk-IAD5DV3D.cjs → chunk-KLYFNMKS.cjs} +2812 -788
  41. package/dist/{chunk-IEBVL5BT.cjs → chunk-URPPSTHZ.cjs} +12 -3
  42. package/dist/chunk-VG4Y26ZN.cjs +429 -0
  43. package/dist/{chunk-IICVBTR2.js → chunk-W77DAC3H.js} +22 -3
  44. package/dist/{chunk-ONM2CSTU.cjs → chunk-X6EETCO6.cjs} +64 -45
  45. package/dist/chunk-YCRMTXOE.js +429 -0
  46. package/dist/{chunk-6TDCSIRZ.cjs → chunk-ZG7BIAUI.cjs} +9 -6
  47. package/dist/cli/index.js +3693 -1141
  48. package/dist/{config-CfXY_iDD.d.ts → config-Y6JwVGwX.d.cts} +15 -1
  49. package/dist/{config-CfXY_iDD.d.cts → config-Y6JwVGwX.d.ts} +15 -1
  50. package/dist/config.cjs +3 -3
  51. package/dist/config.d.cts +1 -1
  52. package/dist/config.d.ts +1 -1
  53. package/dist/config.js +2 -2
  54. package/dist/{index-CjRTNPlj.d.cts → index-0O1WSfVP.d.ts} +7 -1
  55. package/dist/{index-Cm1IloVm.d.ts → index-COVHErnx.d.cts} +7 -1
  56. package/dist/index.cjs +65 -264
  57. package/dist/index.d.cts +4 -4
  58. package/dist/index.d.ts +4 -4
  59. package/dist/index.js +59 -258
  60. package/dist/plugins/unplugin.cjs +4 -3
  61. package/dist/plugins/unplugin.js +3 -2
  62. package/dist/{types-DYQIzGf6.d.cts → types-CMtZnV8C.d.ts} +3 -3
  63. package/dist/{types-ZHAFdOd3.d.ts → types-D93PuOOl.d.cts} +3 -3
  64. package/package.json +1 -1
  65. package/dist/chunk-APWMNVAZ.js +0 -764
  66. package/dist/chunk-DUK2SECY.js +0 -83
  67. package/dist/chunk-I6GXEHFR.cjs +0 -764
  68. package/dist/chunk-RXUY3MPH.cjs +0 -83
@@ -11,6 +11,51 @@ function computeFnv1aHash(input, seed = 2166136261) {
11
11
  }
12
12
  return hash >>> 0;
13
13
  }
14
+ function computeCallSiteSalt64(fnHash, callIndex, seed) {
15
+ const s = seed >>> 0;
16
+ const f = fnHash >>> 0;
17
+ const idx = callIndex + 1 >>> 0;
18
+ let lo = (f ^ s ^ Math.imul(idx, 2654435761)) >>> 0;
19
+ let hi = (s ^ Math.imul((f ^ 2246822507) >>> 0, 3266489909) ^ idx) >>> 0;
20
+ lo = Math.imul(lo ^ lo >>> 16, 2246822507) >>> 0;
21
+ hi = Math.imul(hi ^ hi >>> 15, 3266489909) >>> 0;
22
+ lo = (lo ^ Math.imul(hi ^ hi >>> 13, 668265263)) >>> 0;
23
+ hi = (hi ^ Math.imul(lo ^ lo >>> 16, 374761393)) >>> 0;
24
+ lo = Math.imul(lo ^ lo >>> 15, 73244475) >>> 0;
25
+ hi = Math.imul(hi ^ hi >>> 16, 73244475) >>> 0;
26
+ return [lo >>> 0, hi >>> 0];
27
+ }
28
+ function evalRivestPoly32(x, a0, a1Odd, a2Even, a3Even) {
29
+ const xv = x | 0;
30
+ const c0 = a0 | 0;
31
+ const c1 = a1Odd | 1;
32
+ const c2 = a2Even & ~1;
33
+ const c3 = a3Even & ~1;
34
+ const t2 = c2 + Math.imul(c3, xv) | 0;
35
+ const t1 = c1 + Math.imul(t2, xv) | 0;
36
+ return c0 + Math.imul(t1, xv) >>> 0;
37
+ }
38
+ function invertRivestPoly32(y, a0, a1Odd, a2Even, a3Even) {
39
+ const yv = y | 0;
40
+ const c0 = a0 | 0;
41
+ const c1 = a1Odd | 1;
42
+ const c2 = a2Even & ~1;
43
+ const c3 = a3Even & ~1;
44
+ const twoC2 = c2 << 1 | 0;
45
+ const threeC3 = Math.imul(3, c3);
46
+ let x = yv - c0 & 1 | 0;
47
+ for (let step = 0; step < 5; step++) {
48
+ const fx = c0 + Math.imul(x, c1 + Math.imul(x, c2 + Math.imul(c3, x) | 0) | 0) | 0;
49
+ const err = fx - yv | 0;
50
+ const dfx = c1 + Math.imul(x, twoC2 + Math.imul(threeC3, x) | 0) | 0;
51
+ let inv = 1;
52
+ for (let j = 0; j < 5; j++) {
53
+ inv = Math.imul(inv, 2 - Math.imul(dfx, inv) | 0);
54
+ }
55
+ x = x - Math.imul(err, inv) | 0;
56
+ }
57
+ return x >>> 0;
58
+ }
14
59
 
15
60
  // src/ast/hot-path-detector.ts
16
61
  import * as acorn from "acorn";
@@ -74,27 +119,40 @@ var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
74
119
  "FunctionExpression",
75
120
  "ArrowFunctionExpression"
76
121
  ]);
77
- function parseJavaScriptAst(code, comments) {
122
+ function parseJavaScriptAst(code, comments, opts) {
123
+ const locations = opts?.locations !== false;
124
+ const collectedComments = comments ?? [];
125
+ let ast = null;
78
126
  try {
79
- return acorn.parse(code, {
127
+ ast = acorn.parse(code, {
80
128
  ecmaVersion: "latest",
81
129
  sourceType: "module",
82
130
  allowReturnOutsideFunction: true,
83
- ...comments ? { onComment: comments } : {}
131
+ locations,
132
+ onComment: collectedComments
84
133
  });
85
134
  } catch {
86
- if (comments) comments.length = 0;
135
+ collectedComments.length = 0;
87
136
  try {
88
- return acorn.parse(code, {
137
+ ast = acorn.parse(code, {
89
138
  ecmaVersion: "latest",
90
139
  sourceType: "script",
91
140
  allowReturnOutsideFunction: true,
92
- ...comments ? { onComment: comments } : {}
141
+ locations,
142
+ onComment: collectedComments
93
143
  });
94
144
  } catch {
95
145
  return null;
96
146
  }
97
147
  }
148
+ if (ast) {
149
+ Object.defineProperty(ast, "__unpeekComments", {
150
+ value: collectedComments,
151
+ enumerable: false,
152
+ configurable: true
153
+ });
154
+ }
155
+ return ast;
98
156
  }
99
157
  function isHocCall(callNode, hocWrappers) {
100
158
  if (!callNode || callNode.type !== "CallExpression") return false;
@@ -245,6 +303,7 @@ function analyzeAstHotPaths(ast, config) {
245
303
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
246
304
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
247
305
  const serializedFunctionNodes = /* @__PURE__ */ new WeakSet();
306
+ const criticalFunctionNodes = /* @__PURE__ */ new WeakSet();
248
307
  const serializedWorkerNodes = /* @__PURE__ */ new Set();
249
308
  const trueHotNodes = /* @__PURE__ */ new Set();
250
309
  const shallowComponentNodes = /* @__PURE__ */ new Set();
@@ -357,9 +416,33 @@ function analyzeAstHotPaths(ast, config) {
357
416
  directHotNodes.add(node);
358
417
  hotExemptNodes.add(node);
359
418
  }
419
+ function computeFunctionAnchorStart(node, ancestors) {
420
+ let anchorStart = typeof node.start === "number" ? node.start : 0;
421
+ for (let i = ancestors.length - 2; i >= 0; i--) {
422
+ const anc = ancestors[i];
423
+ const child = ancestors[i + 1];
424
+ if (!anc || typeof anc.start !== "number") break;
425
+ if (anc.type === "VariableDeclarator" && anc.init === child) {
426
+ anchorStart = Math.min(anchorStart, anc.start);
427
+ } else if (anc.type === "VariableDeclaration" && anc.declarations?.[0] === child) {
428
+ anchorStart = Math.min(anchorStart, anc.start);
429
+ } else if ((anc.type === "ExportNamedDeclaration" || anc.type === "ExportDefaultDeclaration") && anc.declaration === child) {
430
+ anchorStart = Math.min(anchorStart, anc.start);
431
+ } else if ((anc.type === "Property" || anc.type === "MethodDefinition") && anc.value === child) {
432
+ anchorStart = Math.min(anchorStart, anc.start);
433
+ } else if (anc.type === "AssignmentExpression" && anc.right === child) {
434
+ anchorStart = Math.min(anchorStart, anc.start);
435
+ } else if (anc.type === "ExpressionStatement" && anc.expression === child) {
436
+ anchorStart = Math.min(anchorStart, anc.start);
437
+ } else {
438
+ break;
439
+ }
440
+ }
441
+ return anchorStart;
442
+ }
360
443
  function registerFunctionNode(node, ancestors) {
361
444
  const name = getFunctionLabel(node, ancestors, hocWrappers);
362
- allFunctions.push({ node, name });
445
+ allFunctions.push({ node, name, anchorStart: computeFunctionAnchorStart(node, ancestors) });
363
446
  fnByName.set(name, node);
364
447
  const paramSet = /* @__PURE__ */ new Set();
365
448
  for (const p of node.params || []) {
@@ -728,7 +811,7 @@ function analyzeAstHotPaths(ast, config) {
728
811
  }
729
812
  }
730
813
  for (const fn of allFunctions) {
731
- if (!trueHotNodes.has(fn.node) && !containsLoopOrAnimation(fn.node, animationCalls)) {
814
+ if (!serializedWorkerNodes.has(fn.node) && !trueHotNodes.has(fn.node) && !containsLoopOrAnimation(fn.node, animationCalls)) {
732
815
  if (!shallowComponentNodes.has(fn.node)) {
733
816
  if (fn.node.async === true || isEventHandlerName(fn.name, eventHandlerRegex)) {
734
817
  coldForcedNodes.add(fn.node);
@@ -740,12 +823,12 @@ function analyzeAstHotPaths(ast, config) {
740
823
  while (forwardChanged) {
741
824
  forwardChanged = false;
742
825
  for (const fn of allFunctions) {
743
- if (coldForcedNodes.has(fn.node)) continue;
744
826
  const chain = fnScopeChain.get(fn.node);
745
827
  if (!chain) continue;
746
828
  for (const anc of chain) {
747
829
  if (anc === fn.node) continue;
748
830
  if (serializedWorkerNodes.has(anc)) {
831
+ coldForcedNodes.delete(fn.node);
749
832
  if (!serializedWorkerNodes.has(fn.node)) {
750
833
  fn.node._unpeekSerialized = true;
751
834
  serializedWorkerNodes.add(fn.node);
@@ -756,6 +839,7 @@ function analyzeAstHotPaths(ast, config) {
756
839
  }
757
840
  break;
758
841
  }
842
+ if (coldForcedNodes.has(fn.node)) continue;
759
843
  const isModuleContainer = (fnScopeChain.get(anc)?.length ?? 0) <= 1;
760
844
  if (trueHotNodes.has(anc) && !shallowComponentNodes.has(anc) && !isModuleContainer) {
761
845
  if (!trueHotNodes.has(fn.node)) {
@@ -773,7 +857,8 @@ function analyzeAstHotPaths(ast, config) {
773
857
  if (!calleeNames) continue;
774
858
  for (const cName of calleeNames) {
775
859
  const targetNode = resolveCalleeNode(callerNode, cName);
776
- if (targetNode && !serializedWorkerNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
860
+ if (targetNode && !serializedWorkerNodes.has(targetNode)) {
861
+ coldForcedNodes.delete(targetNode);
777
862
  targetNode._unpeekSerialized = true;
778
863
  serializedWorkerNodes.add(targetNode);
779
864
  serializedFunctionNodes.add(targetNode);
@@ -838,6 +923,52 @@ function analyzeAstHotPaths(ast, config) {
838
923
  hotFunctionNodes.delete(node);
839
924
  hotExemptNodes.delete(node);
840
925
  }
926
+ const astComments = ast?.__unpeekComments ?? ast?.comments ?? [];
927
+ const criticalComments = astComments.filter(
928
+ (c) => typeof c?.value === "string" && c.value.includes("@unpeek-critical")
929
+ );
930
+ const criticalCommentNodes = /* @__PURE__ */ new Set();
931
+ if (criticalComments.length > 0 && allFunctions.length > 0) {
932
+ const stmtRanges = [];
933
+ walk.full(ast, (n) => {
934
+ if (n && typeof n.start === "number" && typeof n.end === "number" && n.type !== "Program" && n.type !== "BlockStatement" && (n.type.endsWith("Statement") || n.type === "VariableDeclaration" || n.type === "FunctionDeclaration" || n.type === "ClassDeclaration" || n.type === "ImportDeclaration" || n.type === "ExportNamedDeclaration" || n.type === "ExportDefaultDeclaration")) {
935
+ stmtRanges.push({ start: n.start, end: n.end });
936
+ }
937
+ });
938
+ const sortedFns = [...allFunctions].sort(
939
+ (a, b) => (a.node.start ?? 0) - (b.node.start ?? 0)
940
+ );
941
+ for (const c of criticalComments) {
942
+ const cEnd = typeof c.end === "number" ? c.end : 0;
943
+ const target = sortedFns.find(
944
+ (fn) => typeof fn.node.start === "number" && fn.node.start >= cEnd
945
+ );
946
+ if (!target) continue;
947
+ const fnStart = target.node.start;
948
+ const fnEnd = target.node.end;
949
+ const blockedByStmt = stmtRanges.some(
950
+ (s) => !(s.start <= fnStart && fnEnd <= s.end) && s.end > cEnd && s.end <= target.anchorStart
951
+ );
952
+ if (!blockedByStmt) {
953
+ criticalCommentNodes.add(target.node);
954
+ }
955
+ }
956
+ }
957
+ const rawCriticalInclude = config?.critical?.include;
958
+ const criticalIncludeList = Array.isArray(rawCriticalInclude) ? rawCriticalInclude : rawCriticalInclude !== void 0 ? [rawCriticalInclude] : [];
959
+ const criticalIncludeMatchers = [];
960
+ for (const pat of criticalIncludeList) {
961
+ if (pat instanceof RegExp) {
962
+ criticalIncludeMatchers.push((name) => pat.test(name));
963
+ } else if (typeof pat === "string" && pat.length > 0) {
964
+ try {
965
+ const re = new RegExp(pat);
966
+ criticalIncludeMatchers.push((name) => re.test(name));
967
+ } catch {
968
+ criticalIncludeMatchers.push((name) => name.includes(pat));
969
+ }
970
+ }
971
+ }
841
972
  const hotFunctionsSkipped = [];
842
973
  const coldFunctionsProtected = [];
843
974
  for (const fn of allFunctions) {
@@ -846,6 +977,9 @@ function analyzeAstHotPaths(ast, config) {
846
977
  } else {
847
978
  coldFunctionNodes.add(fn.node);
848
979
  coldFunctionsProtected.push(fn.name);
980
+ if (criticalCommentNodes.has(fn.node) || criticalIncludeMatchers.some((match) => match(fn.name))) {
981
+ criticalFunctionNodes.add(fn.node);
982
+ }
849
983
  }
850
984
  }
851
985
  return {
@@ -857,7 +991,8 @@ function analyzeAstHotPaths(ast, config) {
857
991
  hotFunctionNodes,
858
992
  coldFunctionNodes,
859
993
  hotExemptNodes,
860
- serializedFunctionNodes
994
+ serializedFunctionNodes,
995
+ criticalFunctionNodes
861
996
  };
862
997
  }
863
998
  function detectHotPaths(code, config) {
@@ -874,35 +1009,129 @@ function detectHotPaths(code, config) {
874
1009
 
875
1010
  // src/runtime/integrity-guard.ts
876
1011
  var FNV_OFFSET_BASIS = 2166136261;
1012
+ function normalizeIntegritySource(source) {
1013
+ return String(source).replace(/\s+/g, "");
1014
+ }
877
1015
  function computeIntegrityHash(source, seed = 0) {
878
1016
  return computeFnv1aHash(source, (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0);
879
1017
  }
880
- function verifyCodeIntegrity(fnOrSource, expectedHash, seed = 0) {
881
- const raw = typeof fnOrSource === "function" ? Function.prototype.toString.call(fnOrSource) : String(fnOrSource);
882
- return computeIntegrityHash(raw, seed) === expectedHash >>> 0;
1018
+ function computeNormalizedIntegrityHash(source, seed = 0) {
1019
+ return computeFnv1aHash(
1020
+ normalizeIntegritySource(source),
1021
+ (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0
1022
+ );
1023
+ }
1024
+ function isNativeDescriptorIntact() {
1025
+ if (typeof Reflect === "undefined" || typeof Reflect.apply !== "function") {
1026
+ return false;
1027
+ }
1028
+ try {
1029
+ Reflect.apply(Object.getOwnPropertyDescriptor, null, []);
1030
+ return false;
1031
+ } catch (err) {
1032
+ if (!(err instanceof TypeError)) {
1033
+ return false;
1034
+ }
1035
+ }
1036
+ const toStr = Function.prototype.toString;
1037
+ if (typeof toStr !== "function" || Reflect.has(toStr, "prototype") || toStr.name !== "toString" || toStr.length !== 0) {
1038
+ return false;
1039
+ }
1040
+ try {
1041
+ Reflect.apply(toStr, { toString() {
1042
+ } }, []);
1043
+ return false;
1044
+ } catch (err) {
1045
+ if (!(err instanceof TypeError)) {
1046
+ return false;
1047
+ }
1048
+ }
1049
+ return true;
1050
+ }
1051
+ function verifyCodeIntegrity(fnOrSource, expectedHash, seed = 0, normalized = false) {
1052
+ if (typeof fnOrSource !== "function" && typeof fnOrSource !== "string") {
1053
+ return false;
1054
+ }
1055
+ if (!isNativeDescriptorIntact()) {
1056
+ return false;
1057
+ }
1058
+ let raw;
1059
+ if (typeof fnOrSource === "function") {
1060
+ try {
1061
+ const toStr = Function.prototype.toString;
1062
+ const selfStr = Reflect.apply(toStr, toStr, []);
1063
+ if (typeof selfStr !== "string" || selfStr.indexOf("[native code]") < 0) {
1064
+ return false;
1065
+ }
1066
+ raw = Reflect.apply(toStr, fnOrSource, []);
1067
+ } catch {
1068
+ return false;
1069
+ }
1070
+ } else {
1071
+ raw = fnOrSource;
1072
+ }
1073
+ return (normalized ? computeNormalizedIntegrityHash(raw, seed) : computeIntegrityHash(raw, seed)) === expectedHash >>> 0;
883
1074
  }
884
1075
 
885
1076
  // src/ast/codegen.ts
886
1077
  import { generate, baseGenerator } from "astring";
1078
+ var IDENT_START_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
1079
+ var IDENT_CONT_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
1080
+ var DISALLOWED_IDENTS = /* @__PURE__ */ new Set([
1081
+ "as",
1082
+ "do",
1083
+ "if",
1084
+ "in",
1085
+ "of",
1086
+ "for",
1087
+ "int",
1088
+ "let",
1089
+ "new",
1090
+ "try",
1091
+ "var",
1092
+ "NaN",
1093
+ "Map",
1094
+ "Set",
1095
+ "URL",
1096
+ "top",
1097
+ "get",
1098
+ "set",
1099
+ "void",
1100
+ "case",
1101
+ "else",
1102
+ "enum",
1103
+ "null",
1104
+ "this",
1105
+ "true",
1106
+ "with",
1107
+ "Date",
1108
+ "JSON",
1109
+ "Math",
1110
+ "eval"
1111
+ ]);
887
1112
  function derivePolymorphicIdent(seed, role) {
888
1113
  let h = (2166136261 ^ seed >>> 0) >>> 0;
889
1114
  for (let i = 0; i < role.length; i++) {
890
1115
  h ^= role.charCodeAt(i);
891
1116
  h = Math.imul(h, 16777619) >>> 0;
892
1117
  }
893
- const rolePrefixes = {
894
- vault: "_a",
895
- shield: "$b",
896
- decoy: "_d",
897
- shader: "_s",
898
- vm: "_m",
899
- wasm: "_w",
900
- salted: "_k",
901
- windowKey: "_z"
902
- };
903
- const prefix = rolePrefixes[role] ?? `_${String.fromCharCode(97 + h % 26)}`;
904
- const suffix = ((h >>> 4) % 1296).toString(36).padStart(2, "0");
905
- return `${prefix}${suffix}`;
1118
+ h ^= h >>> 16;
1119
+ h = Math.imul(h, 2246822507) >>> 0;
1120
+ h ^= h >>> 13;
1121
+ h = Math.imul(h, 3266489909) >>> 0;
1122
+ h ^= h >>> 16;
1123
+ for (let attempt = 0; attempt < 32; attempt++) {
1124
+ const c0 = IDENT_START_CHARS[h % IDENT_START_CHARS.length];
1125
+ const c1 = IDENT_CONT_CHARS[(h >>> 6) % IDENT_CONT_CHARS.length];
1126
+ const c2 = IDENT_CONT_CHARS[(h >>> 12) % IDENT_CONT_CHARS.length];
1127
+ const c3 = IDENT_CONT_CHARS[(h >>> 18) % IDENT_CONT_CHARS.length];
1128
+ const ident = `${c0}${c1}${c2}${c3}`;
1129
+ if (!DISALLOWED_IDENTS.has(ident) && !ident.startsWith("__") && !ident.startsWith("_u") && !ident.startsWith("_0")) {
1130
+ return ident;
1131
+ }
1132
+ h = Math.imul(h ^ 2654435769 + attempt, 2246822507) >>> 0;
1133
+ }
1134
+ return `_${(h >>> 0).toString(36).slice(0, 3).padStart(3, "0")}`;
906
1135
  }
907
1136
  var OPERATOR_PRECEDENCE = {
908
1137
  "||": 2,
@@ -979,20 +1208,145 @@ function formatSequence(state, expressions) {
979
1208
  state.write("()");
980
1209
  }
981
1210
  }
982
- function expressionStartsWith(node, char) {
983
- if (!node) return false;
984
- if (node.type === "UnaryExpression" && node.prefix) {
985
- return node.operator === char;
1211
+ function getLeadingNode(state, node, parentNode, isRightHand = false) {
1212
+ let cur = node;
1213
+ let parent = parentNode;
1214
+ let right = isRightHand;
1215
+ for (let depth = 0; cur && depth < 32; depth++) {
1216
+ if (parent && state && expressionNeedsParenthesis(state, cur, parent, right)) {
1217
+ return null;
1218
+ }
1219
+ if (cur.type === "BinaryExpression") {
1220
+ if (cur.operator === "in") return null;
1221
+ parent = cur;
1222
+ cur = cur.left;
1223
+ right = false;
1224
+ } else if (cur.type === "LogicalExpression" || cur.type === "AssignmentExpression") {
1225
+ parent = cur;
1226
+ cur = cur.left;
1227
+ right = false;
1228
+ } else if (cur.type === "ConditionalExpression") {
1229
+ const prec = state?.expressionsPrecedence?.[cur.test?.type];
1230
+ if (prec === NEEDS_PARENTHESES || prec <= state?.expressionsPrecedence?.ConditionalExpression) {
1231
+ return null;
1232
+ }
1233
+ parent = cur;
1234
+ cur = cur.test;
1235
+ right = false;
1236
+ } else if (cur.type === "MemberExpression") {
1237
+ const prec = state?.expressionsPrecedence?.[cur.object?.type];
1238
+ if (prec === NEEDS_PARENTHESES || prec < state?.expressionsPrecedence?.MemberExpression) {
1239
+ return null;
1240
+ }
1241
+ parent = cur;
1242
+ cur = cur.object;
1243
+ right = false;
1244
+ } else if (cur.type === "CallExpression") {
1245
+ const prec = state?.expressionsPrecedence?.[cur.callee?.type];
1246
+ if (prec === NEEDS_PARENTHESES || prec < state?.expressionsPrecedence?.CallExpression) {
1247
+ return null;
1248
+ }
1249
+ parent = cur;
1250
+ cur = cur.callee;
1251
+ right = false;
1252
+ } else if (cur.type === "ChainExpression") {
1253
+ parent = cur;
1254
+ cur = cur.expression;
1255
+ right = false;
1256
+ } else if (cur.type === "TaggedTemplateExpression") {
1257
+ const prec = state?.expressionsPrecedence?.[cur.tag?.type];
1258
+ if (prec === NEEDS_PARENTHESES || prec < state?.expressionsPrecedence?.CallExpression) {
1259
+ return null;
1260
+ }
1261
+ parent = cur;
1262
+ cur = cur.tag;
1263
+ right = false;
1264
+ } else if (cur.type === "UpdateExpression" && !cur.prefix) {
1265
+ parent = cur;
1266
+ cur = cur.argument;
1267
+ right = false;
1268
+ } else {
1269
+ return cur;
1270
+ }
1271
+ }
1272
+ return cur;
1273
+ }
1274
+ function getTrailingNode(state, node, parentNode, isRightHand = false) {
1275
+ let cur = node;
1276
+ let parent = parentNode;
1277
+ let right = isRightHand;
1278
+ for (let depth = 0; cur && depth < 32; depth++) {
1279
+ if (parent && state && expressionNeedsParenthesis(state, cur, parent, right)) {
1280
+ return null;
1281
+ }
1282
+ if (cur.type === "BinaryExpression") {
1283
+ if (cur.operator === "in") return null;
1284
+ parent = cur;
1285
+ cur = cur.right;
1286
+ right = true;
1287
+ } else if (cur.type === "LogicalExpression" || cur.type === "AssignmentExpression") {
1288
+ parent = cur;
1289
+ cur = cur.right;
1290
+ right = true;
1291
+ } else if (cur.type === "ConditionalExpression") {
1292
+ parent = cur;
1293
+ cur = cur.alternate;
1294
+ right = true;
1295
+ } else if (cur.type === "ChainExpression") {
1296
+ parent = cur;
1297
+ cur = cur.expression;
1298
+ right = false;
1299
+ } else if (cur.type === "UnaryExpression" && cur.prefix) {
1300
+ parent = cur;
1301
+ cur = cur.argument;
1302
+ right = true;
1303
+ } else if (cur.type === "UpdateExpression" && cur.prefix) {
1304
+ parent = cur;
1305
+ cur = cur.argument;
1306
+ right = true;
1307
+ } else if (cur.type === "AwaitExpression") {
1308
+ parent = cur;
1309
+ cur = cur.argument;
1310
+ right = true;
1311
+ } else {
1312
+ return cur;
1313
+ }
1314
+ }
1315
+ return cur;
1316
+ }
1317
+ function expressionStartsWith(node, char, state, parentNode, isRightHand = false) {
1318
+ const leading = state ? getLeadingNode(state, node, parentNode, isRightHand) : node;
1319
+ if (!leading) return false;
1320
+ if (leading.type === "UnaryExpression" && leading.prefix) {
1321
+ return leading.operator === char;
1322
+ }
1323
+ if (leading.type === "UpdateExpression" && leading.prefix) {
1324
+ return leading.operator[0] === char;
986
1325
  }
987
- if (node.type === "UpdateExpression" && node.prefix) {
988
- return node.operator[0] === char;
1326
+ if (char === "-" && leading.type === "Literal" && typeof leading.value === "number" && leading.value < 0) {
1327
+ return true;
1328
+ }
1329
+ if (char === "/" && isRegExp(leading)) {
1330
+ return true;
989
1331
  }
990
1332
  return false;
991
1333
  }
992
- function expressionEndsWith(node, char) {
993
- if (!node) return false;
994
- if (node.type === "UpdateExpression" && !node.prefix) {
995
- return node.operator[0] === char;
1334
+ function leadingIsUnaryOrUpdate(state, node, parentNode, isRightHand = false) {
1335
+ const leading = getLeadingNode(state, node, parentNode, isRightHand);
1336
+ if (!leading) return false;
1337
+ if (leading.type === "UnaryExpression" && leading.prefix && "+-!~".includes(leading.operator)) {
1338
+ return true;
1339
+ }
1340
+ if (leading.type === "UpdateExpression" && leading.prefix) {
1341
+ return true;
1342
+ }
1343
+ return false;
1344
+ }
1345
+ function expressionEndsWith(node, char, state, parentNode, isRightHand = false) {
1346
+ const trailing = state ? getTrailingNode(state, node, parentNode, isRightHand) : node;
1347
+ if (!trailing) return false;
1348
+ if (trailing.type === "UpdateExpression" && !trailing.prefix) {
1349
+ return trailing.operator[0] === char;
996
1350
  }
997
1351
  return false;
998
1352
  }
@@ -1013,10 +1367,10 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1013
1367
  spaceBefore = true;
1014
1368
  spaceAfter = true;
1015
1369
  } else {
1016
- if ((op === "+" || op === "-") && expressionEndsWith(node.left, op) && !expressionNeedsParenthesis(state, node.left, node, false)) {
1370
+ if ((op === "+" || op === "-") && expressionEndsWith(node.left, op, state, node, false)) {
1017
1371
  spaceBefore = true;
1018
1372
  }
1019
- if ((op === "+" || op === "-") && expressionStartsWith(node.right, op) && !expressionNeedsParenthesis(state, node.right, node, true) || op === "/" && isRegExp(node.right)) {
1373
+ if ((op === "+" || op === "-") && (expressionStartsWith(node.right, op, state, node, true) || leadingIsUnaryOrUpdate(state, node.right, node, true)) || op === "/" && (isRegExp(node.right) || expressionStartsWith(node.right, "/", state, node, true))) {
1020
1374
  spaceAfter = true;
1021
1375
  }
1022
1376
  }
@@ -1028,6 +1382,43 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1028
1382
  state.write(")");
1029
1383
  }
1030
1384
  },
1385
+ UnaryExpression(node, state) {
1386
+ if (node.prefix) {
1387
+ const { operator, argument } = node;
1388
+ state.write(operator);
1389
+ const needsParentheses = expressionNeedsParenthesis(
1390
+ state,
1391
+ argument,
1392
+ node,
1393
+ true
1394
+ );
1395
+ if (needsParentheses) {
1396
+ state.write(operator.length > 1 ? " (" : "(");
1397
+ this[argument.type](argument, state);
1398
+ state.write(")");
1399
+ } else {
1400
+ if (operator.length > 1 || "+-!~".includes(operator) && leadingIsUnaryOrUpdate(state, argument, node, true)) {
1401
+ state.write(" ");
1402
+ }
1403
+ this[argument.type](argument, state);
1404
+ }
1405
+ } else {
1406
+ this[node.argument.type](node.argument, state);
1407
+ state.write(node.operator);
1408
+ }
1409
+ },
1410
+ UpdateExpression(node, state) {
1411
+ if (node.prefix) {
1412
+ state.write(node.operator);
1413
+ if (leadingIsUnaryOrUpdate(state, node.argument, node, true)) {
1414
+ state.write(" ");
1415
+ }
1416
+ this[node.argument.type](node.argument, state);
1417
+ } else {
1418
+ this[node.argument.type](node.argument, state);
1419
+ state.write(node.operator);
1420
+ }
1421
+ },
1031
1422
  LogicalExpression(node, state) {
1032
1423
  formatExpression(state, node.left, node, false);
1033
1424
  state.write(node.operator);
@@ -1036,7 +1427,7 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1036
1427
  AssignmentExpression(node, state) {
1037
1428
  this[node.left.type](node.left, state);
1038
1429
  const op = node.operator;
1039
- if (op.endsWith("+") && expressionStartsWith(node.right, "+") || op.endsWith("-") && expressionStartsWith(node.right, "-") || op.endsWith("/") && isRegExp(node.right)) {
1430
+ if (op.endsWith("+") && expressionStartsWith(node.right, "+", state, node, true) || op.endsWith("-") && expressionStartsWith(node.right, "-", state, node, true) || op.endsWith("/") && (isRegExp(node.right) || expressionStartsWith(node.right, "/", state, node, true))) {
1040
1431
  state.write(op + " ");
1041
1432
  } else {
1042
1433
  state.write(op);
@@ -1235,6 +1626,20 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1235
1626
  state.write(")");
1236
1627
  }
1237
1628
  });
1629
+ var VLQ_BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1630
+ function encodeVlq(value) {
1631
+ let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
1632
+ let encoded = "";
1633
+ do {
1634
+ let digit = vlq & 31;
1635
+ vlq >>>= 5;
1636
+ if (vlq > 0) {
1637
+ digit |= 32;
1638
+ }
1639
+ encoded += VLQ_BASE64_CHARS[digit];
1640
+ } while (vlq > 0);
1641
+ return encoded;
1642
+ }
1238
1643
  function generateCompactJs(ast) {
1239
1644
  return generate(ast, {
1240
1645
  generator: compactGenerator,
@@ -1242,6 +1647,107 @@ function generateCompactJs(ast) {
1242
1647
  lineEnd: ""
1243
1648
  });
1244
1649
  }
1650
+ function generateCompactJsWithMap(ast, fileName) {
1651
+ const sourceName = fileName || "input.js";
1652
+ const sources = [sourceName];
1653
+ const names = [];
1654
+ const nameToIndex = /* @__PURE__ */ new Map();
1655
+ const lines = [];
1656
+ const chunks = [];
1657
+ let curLine = 0;
1658
+ let curCol = 0;
1659
+ let prevWriteLine = 0;
1660
+ let prevWriteCol = 0;
1661
+ let lastMappedLine = -1;
1662
+ let lastMappedCol = -1;
1663
+ const outputStream = {
1664
+ write(chunk) {
1665
+ prevWriteLine = curLine;
1666
+ prevWriteCol = curCol;
1667
+ if (chunk.length > 0) {
1668
+ chunks.push(chunk);
1669
+ for (let i = 0; i < chunk.length; i++) {
1670
+ if (chunk.charCodeAt(i) === 10) {
1671
+ curLine++;
1672
+ curCol = 0;
1673
+ } else {
1674
+ curCol++;
1675
+ }
1676
+ }
1677
+ }
1678
+ }
1679
+ };
1680
+ const sourceMapSink = {
1681
+ file: sourceName,
1682
+ addMapping(mapping) {
1683
+ if (!mapping.original) return;
1684
+ const origLine = (mapping.original.line | 0) - 1;
1685
+ const origCol = mapping.original.column | 0;
1686
+ if (origLine < 0 || origCol < 0) return;
1687
+ const genLine = prevWriteLine;
1688
+ const genCol = prevWriteCol;
1689
+ if (genLine === lastMappedLine && genCol === lastMappedCol) {
1690
+ return;
1691
+ }
1692
+ lastMappedLine = genLine;
1693
+ lastMappedCol = genCol;
1694
+ while (lines.length <= genLine) {
1695
+ lines.push([]);
1696
+ }
1697
+ let nameIdx;
1698
+ if (typeof mapping.name === "string" && mapping.name.length > 0) {
1699
+ let existing = nameToIndex.get(mapping.name);
1700
+ if (existing === void 0) {
1701
+ existing = names.length;
1702
+ names.push(mapping.name);
1703
+ nameToIndex.set(mapping.name, existing);
1704
+ }
1705
+ nameIdx = existing;
1706
+ }
1707
+ lines[genLine].push({
1708
+ genCol,
1709
+ srcIdx: 0,
1710
+ origLine,
1711
+ origCol,
1712
+ nameIdx
1713
+ });
1714
+ }
1715
+ };
1716
+ generate(ast, {
1717
+ generator: compactGenerator,
1718
+ indent: "",
1719
+ lineEnd: "",
1720
+ output: outputStream,
1721
+ sourceMap: sourceMapSink
1722
+ });
1723
+ let prevSrcIdx = 0;
1724
+ let prevOrigLine = 0;
1725
+ let prevOrigCol = 0;
1726
+ let prevNameIdx = 0;
1727
+ const encodedLines = lines.map((segs) => {
1728
+ let prevGenCol = 0;
1729
+ const encodedSegs = [];
1730
+ for (const seg of segs) {
1731
+ let s = encodeVlq(seg.genCol - prevGenCol) + encodeVlq(seg.srcIdx - prevSrcIdx) + encodeVlq(seg.origLine - prevOrigLine) + encodeVlq(seg.origCol - prevOrigCol);
1732
+ prevGenCol = seg.genCol;
1733
+ prevSrcIdx = seg.srcIdx;
1734
+ prevOrigLine = seg.origLine;
1735
+ prevOrigCol = seg.origCol;
1736
+ if (seg.nameIdx !== void 0) {
1737
+ s += encodeVlq(seg.nameIdx - prevNameIdx);
1738
+ prevNameIdx = seg.nameIdx;
1739
+ }
1740
+ encodedSegs.push(s);
1741
+ }
1742
+ return encodedSegs.join(",");
1743
+ });
1744
+ return {
1745
+ code: chunks.join(""),
1746
+ mappings: encodedLines.join(";"),
1747
+ names,
1748
+ sources
1749
+ };
1750
+ }
1245
1751
 
1246
1752
  // src/runtime/devtools-deterrent.ts
1247
1753
  function deriveIntegrityFnName(seed) {
@@ -1258,9 +1764,11 @@ function createDeterrentSnippet(config) {
1258
1764
  const sym = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1259
1765
  const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=function(){return 0;};" : "";
1260
1766
  const symLit = JSON.stringify(sym);
1767
+ const stateLit = JSON.stringify(`${sym}_s`);
1261
1768
  const headlessDecl = detectHeadless ? ",n=w.navigator||0" : "";
1262
1769
  const headlessCond = detectHeadless ? "||n.webdriver||/HeadlessChrome/.test(n.userAgent)" : "";
1263
- return `(function ${fnName}(w){var G=typeof globalThis!=='undefined'?globalThis:w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,GP=O.getPrototypeOf,T=function(o,k){try{while(o){var r=P&&P(o,k);if(r&&(r.set||!r.writable))return 1;o=GP?GP(o):0;}}catch(e){return 1;}},S=function(o,k,v){try{o[k]=v;}catch(e){}},s=Function.prototype.toString${headlessDecl},src='',t=0;try{src=s.call(${fnName});if('prototype' in s||s.name!=='toString'||s.length!==0||s.call(s).indexOf('[native code]')<0||/\\n/.test(src)${headlessCond})t=1;}catch(e){t=1;}try{s.call(0);t=1;}catch(e){}if(T(w,${symLit})||T(G,${symLit})||T(G,'__unpeek_tampered')||T(w,'__unpeek_tampered')||T(String.prototype,'_u'))t=1;for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=h&0xffff;if(t){var pd=(d^(((h>>>16)^0x5a5b)||1))&0xffff;if(!T(G,${symLit}))S(G,${symLit},pd);if(!T(w,${symLit}))S(w,${symLit},pd);S(G,'__unpeek_delta',pd);S(w,'__unpeek_delta',pd);try{String.prototype._u=14;}catch(e){}var ns=((w.__unpeek_seed||${seed})^1)>>>0;S(G,'__unpeek_seed',ns);S(w,'__unpeek_seed',ns);S(G,'__unpeek_tampered',!0);S(w,'__unpeek_tampered',!0);try{${consoleSilence}if(w.dispatchEvent)w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else{S(G,${symLit},d);S(w,${symLit},d);}}})(typeof window!=='undefined'?window:(typeof self!=='undefined'?self:0));`;
1770
+ const k1Mul = (seed | 1) >>> 0;
1771
+ return `(function ${fnName}(w){var G=typeof globalThis<'u'?globalThis:w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,GP=O.getPrototypeOf,R=typeof Reflect<'u'&&Reflect.apply,SP=String.prototype,Q='__unpeek_',y=${symLit},z=${stateLit},U='__unpeek_tampered',T=function(o,k){try{while(o){var r=P&&P(o,k);if(r&&(r.set||!r.writable))return 1;o=GP?GP(o):0;}}catch(e){return 1;}},B=function(k,v,c){try{if(!c||!T(G,k))G[k]=v;}catch(e){}try{if(!c||!T(w,k))w[k]=v;}catch(e){}},s=Function.prototype.toString${headlessDecl},src='',t=0;if((G[z]||w[z]||0)[0]==2)t=1;try{if(typeof R!='function')t=1;else{var E=function(f,a,b){try{R(f,a,b);t=1;}catch(e){t|=!e||(!(e instanceof TypeError)&&e.name!='TypeError');}};E(P,null,[]);E(s,{toString(){}},[]);src=R(s,${fnName},[]);if(typeof s!='function'||'prototype'in s||s.name!='toString'||s.length!=0||R(s,s,[]).indexOf('[native code]')<0||/\\n/.test(src)${headlessCond})t=1;}}catch(e){t=1;}for(var j in K=[y,z,U])if(T(w,K[j])||T(G,K[j]))t=1;if(T(SP,'_u'))t=1;for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=h&65535,k0=(h^${seed})>>>0,k1=(h^${k1Mul})>>>0,nc=(d^(h>>>16))>>>0;B(z,[t?2:1,k0^t,k1^t,1,nc],t);if(t){var pd=(d^((h>>>16^0x5a5b)||1))&65535;B(y,pd,1);B(y+'_t',!0);B(Q+'delta',pd);try{SP._u=14;}catch(e){}B(Q+'seed',((w.__unpeek_seed||${seed})^1)>>>0);B(U,!0);try{${consoleSilence}w.dispatchEvent&&w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else B(y,d);}})(typeof window!=='undefined'?window:typeof self<'u'?self:typeof globalThis<'u'?globalThis:0);`;
1264
1772
  }
1265
1773
 
1266
1774
  // src/runtime/index.ts
@@ -1284,7 +1792,8 @@ function generateRuntimeShield(config) {
1284
1792
  integrityCheckFnName,
1285
1793
  expectedHash,
1286
1794
  windowKeySymbol,
1287
- expectedDelta
1795
+ expectedDelta,
1796
+ stateKeySymbol: `${windowKeySymbol}_s`
1288
1797
  };
1289
1798
  return payload;
1290
1799
  }
@@ -1344,6 +1853,20 @@ function deriveKdfParams(seed) {
1344
1853
  const r2 = (seed >>> 5) % 17 + 5;
1345
1854
  return { sVal, c1, c2, k0, r1, r2 };
1346
1855
  }
1856
+ function deriveWasmHostParams(seed) {
1857
+ const gArr = [
1858
+ computeFnv1aHash("wasm-g0", seed) | 0,
1859
+ computeFnv1aHash("wasm-g1", seed) | 0,
1860
+ computeFnv1aHash("wasm-g2", seed) | 0,
1861
+ computeFnv1aHash("wasm-g3", seed) | 0
1862
+ ];
1863
+ const sOff = computeFnv1aHash("wasm-sbox", seed) & 255;
1864
+ const rA0 = computeFnv1aHash("wasm-ra0", seed) | 0;
1865
+ const rA1 = computeFnv1aHash("wasm-ra1", seed) | 1;
1866
+ const rA2 = computeFnv1aHash("wasm-ra2", seed) & ~1;
1867
+ const rA3 = computeFnv1aHash("wasm-ra3", seed) & ~1;
1868
+ return { gArr, sOff, rA0, rA1, rA2, rA3 };
1869
+ }
1347
1870
  function generateWasmKdfBinary(seed) {
1348
1871
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
1349
1872
  const memBase = (seed >>> 0 & 127) * 4;
@@ -1359,7 +1882,7 @@ function generateWasmKdfBinary(seed) {
1359
1882
  const w2 = c1 ^ (w0 + w1 | 0) | 0;
1360
1883
  const w3 = c2 - Math.imul(w1 | 1, w2 | 1) | 0;
1361
1884
  const w4 = k0 ^ rotl32(w2, 11) ^ w3 | 0;
1362
- const instructions = [
1885
+ const kdfInstructions = [
1363
1886
  65,
1364
1887
  ...encodeSignedLeb128(memA),
1365
1888
  // i32.const memA
@@ -1493,7 +2016,7 @@ function generateWasmKdfBinary(seed) {
1493
2016
  33,
1494
2017
  10,
1495
2018
  // local.set 10 (k0)
1496
- // x = f ^ sVal ^ k0
2019
+ // x = f ^ sVal ^ k0 ^ env.g(0)
1497
2020
  32,
1498
2021
  0,
1499
2022
  // local.get 0 (fnId)
@@ -1507,6 +2030,14 @@ function generateWasmKdfBinary(seed) {
1507
2030
  // local.get 10 (k0)
1508
2031
  115,
1509
2032
  // i32.xor
2033
+ 65,
2034
+ 0,
2035
+ // i32.const 0
2036
+ 16,
2037
+ 0,
2038
+ // call 0 (env.g(0))
2039
+ 115,
2040
+ // i32.xor
1510
2041
  34,
1511
2042
  11,
1512
2043
  // local.tee 11 (x)
@@ -1538,7 +2069,14 @@ function generateWasmKdfBinary(seed) {
1538
2069
  // i32.const r1
1539
2070
  119,
1540
2071
  // i32.rotl
1541
- // x = imul(x ^ h ^ sVal, c2)
2072
+ // x = env.m(x, shieldHash)
2073
+ 32,
2074
+ 2,
2075
+ // local.get 2 (shieldHash)
2076
+ 16,
2077
+ 1,
2078
+ // call 1 (env.m(x, shieldHash))
2079
+ // x = imul(x ^ h ^ sVal ^ env.g(1), c2)
1542
2080
  32,
1543
2081
  2,
1544
2082
  // local.get 2 (shieldHash)
@@ -1549,6 +2087,14 @@ function generateWasmKdfBinary(seed) {
1549
2087
  // local.get 8 (sVal)
1550
2088
  115,
1551
2089
  // i32.xor
2090
+ 65,
2091
+ 1,
2092
+ // i32.const 1
2093
+ 16,
2094
+ 0,
2095
+ // call 0 (env.g(1))
2096
+ 115,
2097
+ // i32.xor
1552
2098
  32,
1553
2099
  7,
1554
2100
  // local.get 7 (w3)
@@ -1627,60 +2173,221 @@ function generateWasmKdfBinary(seed) {
1627
2173
  11
1628
2174
  // end
1629
2175
  ];
1630
- const funcBody = [1, 9, 127, ...instructions];
1631
- const funcBodyWithLen = [...encodeUnsignedLeb128(funcBody.length), ...funcBody];
1632
- const codeSectionPayload = [1, ...funcBodyWithLen];
1633
- const codeSection = [
1634
- 10,
1635
- ...encodeUnsignedLeb128(codeSectionPayload.length),
1636
- ...codeSectionPayload
2176
+ const bulkMixInstructions = [
2177
+ 2,
2178
+ 64,
2179
+ // block void
2180
+ 3,
2181
+ 64,
2182
+ // loop void
2183
+ 32,
2184
+ 3,
2185
+ // local.get 3 (i)
2186
+ 32,
2187
+ 1,
2188
+ // local.get 1 (wordLen)
2189
+ 79,
2190
+ // i32.ge_u
2191
+ 13,
2192
+ 1,
2193
+ // br_if 1 (break)
2194
+ 32,
2195
+ 0,
2196
+ // local.get 0 (ptr)
2197
+ 32,
2198
+ 3,
2199
+ // local.get 3 (i)
2200
+ 65,
2201
+ 2,
2202
+ // i32.const 2
2203
+ 116,
2204
+ // i32.shl
2205
+ 106,
2206
+ // i32.add
2207
+ 33,
2208
+ 4,
2209
+ // local.set 4 (addr)
2210
+ 32,
2211
+ 2,
2212
+ // local.get 2 (key)
2213
+ 32,
2214
+ 3,
2215
+ // local.get 3 (i)
2216
+ 115,
2217
+ // i32.xor
2218
+ 32,
2219
+ 2,
2220
+ // local.get 2 (key)
2221
+ 32,
2222
+ 3,
2223
+ // local.get 3 (i)
2224
+ 65,
2225
+ 3,
2226
+ // i32.const 3
2227
+ 113,
2228
+ // i32.and
2229
+ 16,
2230
+ 0,
2231
+ // call 0 (env.g)
2232
+ 106,
2233
+ // i32.add
2234
+ 16,
2235
+ 1,
2236
+ // call 1 (env.m)
2237
+ 33,
2238
+ 2,
2239
+ // local.set 2 (key)
2240
+ 32,
2241
+ 4,
2242
+ // local.get 4 (addr)
2243
+ 32,
2244
+ 4,
2245
+ // local.get 4 (addr)
2246
+ 40,
2247
+ 2,
2248
+ 0,
2249
+ // i32.load align=2 offset=0
2250
+ 32,
2251
+ 2,
2252
+ // local.get 2 (key)
2253
+ 115,
2254
+ // i32.xor
2255
+ 54,
2256
+ 2,
2257
+ 0,
2258
+ // i32.store align=2 offset=0
2259
+ 32,
2260
+ 3,
2261
+ // local.get 3 (i)
2262
+ 65,
2263
+ 1,
2264
+ // i32.const 1
2265
+ 106,
2266
+ // i32.add
2267
+ 33,
2268
+ 3,
2269
+ // local.set 3 (i)
2270
+ 12,
2271
+ 0,
2272
+ // br 0
2273
+ 11,
2274
+ // end loop
2275
+ 11,
2276
+ // end block
2277
+ 32,
2278
+ 2,
2279
+ // local.get 2 (key)
2280
+ 11
2281
+ // end func
1637
2282
  ];
2283
+ const kdfBody = [1, 9, 127, ...kdfInstructions];
2284
+ const kdfBodyWithLen = [...encodeUnsignedLeb128(kdfBody.length), ...kdfBody];
2285
+ const bulkBody = [1, 2, 127, ...bulkMixInstructions];
2286
+ const bulkBodyWithLen = [...encodeUnsignedLeb128(bulkBody.length), ...bulkBody];
1638
2287
  const typePayload = [
2288
+ 3,
2289
+ // 3 types
2290
+ 96,
2291
+ 1,
2292
+ 127,
1639
2293
  1,
1640
- // 1 type
2294
+ 127,
2295
+ // type 0: (i32) -> i32
2296
+ 96,
2297
+ 2,
2298
+ 127,
2299
+ 127,
2300
+ 1,
2301
+ 127,
2302
+ // type 1: (i32, i32) -> i32
1641
2303
  96,
1642
- // func
1643
2304
  3,
1644
2305
  127,
1645
2306
  127,
1646
2307
  127,
1647
- // 3 params of type i32
1648
2308
  1,
1649
2309
  127
1650
- // 1 result of type i32
2310
+ // type 2: (i32, i32, i32) -> i32
1651
2311
  ];
1652
2312
  const typeSection = [
1653
2313
  1,
1654
2314
  ...encodeUnsignedLeb128(typePayload.length),
1655
2315
  ...typePayload
1656
2316
  ];
1657
- const funcPayload = [
2317
+ const importPayload = [
2318
+ 2,
2319
+ // 2 imports
2320
+ 3,
2321
+ 101,
2322
+ 110,
2323
+ 118,
1658
2324
  1,
1659
- // 1 function
1660
- 0
1661
- // type index 0
1662
- ];
1663
- const funcSection = [
2325
+ 103,
2326
+ 0,
2327
+ 0,
2328
+ // env.g: func type 0
1664
2329
  3,
1665
- ...encodeUnsignedLeb128(funcPayload.length),
2330
+ 101,
2331
+ 110,
2332
+ 118,
2333
+ 1,
2334
+ 109,
2335
+ 0,
2336
+ 1
2337
+ // env.m: func type 1
2338
+ ];
2339
+ const importSection = [
2340
+ 2,
2341
+ ...encodeUnsignedLeb128(importPayload.length),
2342
+ ...importPayload
2343
+ ];
2344
+ const funcPayload = [2, 2, 2];
2345
+ const funcSection = [
2346
+ 3,
2347
+ ...encodeUnsignedLeb128(funcPayload.length),
1666
2348
  ...funcPayload
1667
2349
  ];
1668
2350
  const memSection = [5, 3, 1, 0, 1];
1669
- const exportName = [3, 107, 100, 102];
1670
2351
  const exportPayload = [
1671
- 1,
1672
- // 1 export
1673
- ...exportName,
2352
+ 3,
2353
+ // 3 exports
2354
+ 3,
2355
+ 107,
2356
+ 100,
2357
+ 102,
2358
+ 0,
2359
+ 2,
2360
+ // "kdf" -> func 2
2361
+ 7,
2362
+ 98,
2363
+ 117,
2364
+ 108,
2365
+ 107,
2366
+ 77,
2367
+ 105,
2368
+ 120,
1674
2369
  0,
1675
- // function export
2370
+ 3,
2371
+ // "bulkMix" -> func 3
2372
+ 3,
2373
+ 109,
2374
+ 101,
2375
+ 109,
2376
+ 2,
1676
2377
  0
1677
- // function index 0
2378
+ // "mem" -> memory 0
1678
2379
  ];
1679
2380
  const exportSection = [
1680
2381
  7,
1681
2382
  ...encodeUnsignedLeb128(exportPayload.length),
1682
2383
  ...exportPayload
1683
2384
  ];
2385
+ const codeSectionPayload = [2, ...kdfBodyWithLen, ...bulkBodyWithLen];
2386
+ const codeSection = [
2387
+ 10,
2388
+ ...encodeUnsignedLeb128(codeSectionPayload.length),
2389
+ ...codeSectionPayload
2390
+ ];
1684
2391
  const dataWords = [
1685
2392
  ...writeI32LE(w0),
1686
2393
  ...writeI32LE(w1),
@@ -1709,6 +2416,7 @@ function generateWasmKdfBinary(seed) {
1709
2416
  return new Uint8Array([
1710
2417
  ...header,
1711
2418
  ...typeSection,
2419
+ ...importSection,
1712
2420
  ...funcSection,
1713
2421
  ...memSection,
1714
2422
  ...exportSection,
@@ -1718,11 +2426,20 @@ function generateWasmKdfBinary(seed) {
1718
2426
  }
1719
2427
  function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
1720
2428
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
1721
- let x = fnId ^ sVal ^ k0 | 0;
2429
+ const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
2430
+ const envM = (acc, pc) => {
2431
+ const sb0 = Math.imul(167, acc & 255) + sOff & 255;
2432
+ const sb1 = Math.imul(167, acc >>> 8 & 255) + sOff & 255;
2433
+ const sb = sb0 ^ sb1 << 8;
2434
+ const riv = evalRivestPoly32(acc ^ sb ^ pc | 0, rA0, rA1, rA2, rA3) | 0;
2435
+ return riv ^ gArr[2] | 0;
2436
+ };
2437
+ let x = fnId ^ sVal ^ k0 ^ gArr[0] | 0;
1722
2438
  x = x ^ x >>> 16 | 0;
1723
2439
  x = Math.imul(x, c1);
1724
2440
  x = rotl32(x ^ callSiteSalt | 0, r1);
1725
- x = Math.imul(x ^ shieldHash ^ sVal | 0, c2);
2441
+ x = envM(x, shieldHash | 0);
2442
+ x = Math.imul(x ^ shieldHash ^ sVal ^ gArr[1] | 0, c2);
1726
2443
  x = x ^ x >>> 15 | 0;
1727
2444
  x = x + rotl32(callSiteSalt ^ k0 | 0, r2) | 0;
1728
2445
  x = Math.imul(x, c1);
@@ -1754,43 +2471,54 @@ function injectWasmVault(ast, seed = 2654435769) {
1754
2471
  return {
1755
2472
  kdfFnName: id,
1756
2473
  wasmBytes: generateWasmKdfBinary(seed),
1757
- wasmVarName
2474
+ wasmVarName,
2475
+ kdfParityVerified: true
1758
2476
  };
1759
2477
  }
1760
2478
  const wasmBytes = generateWasmKdfBinary(seed);
1761
2479
  const byteArrayLiteral = Array.from(wasmBytes).join(",");
1762
2480
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
2481
+ const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
1763
2482
  const targets = [c1, c2, sVal, k0, r1, r2];
1764
- const aArr = [];
1765
- const bArr = [];
1766
- const mArr = [];
1767
- for (let i = 0; i < targets.length; i++) {
1768
- const aVal = computeFnv1aHash(`mba-a:${i}`, seed) | 0;
1769
- const mVal = computeFnv1aHash(`mba-m:${i}`, seed) | 0;
1770
- const bVal = (targets[i] ^ mVal) - aVal | 0;
1771
- aArr.push(aVal);
1772
- bArr.push(bVal);
1773
- mArr.push(mVal);
1774
- }
2483
+ const rivEncodedTargets = targets.map(
2484
+ (t, j) => invertRivestPoly32((t ^ gArr[j & 3]) >>> 0, rA0, rA1, rA2, rA3) | 0
2485
+ );
1775
2486
  const strKey = seed & 127 ^ 61 | 0;
1776
2487
  const mChars = [105 ^ strKey, 109 ^ strKey, 117 ^ strKey, 108 ^ strKey].join(",");
1777
2488
  const helperSnippet = `var ${kdfFnName};
1778
- try {
1779
- var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
1780
- var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
1781
- var _wi${suffix} = new WebAssembly.Instance(_wm${suffix});
1782
- ${kdfFnName} = _wi${suffix}.exports.kdf;
1783
- } catch (e) {
1784
- ${kdfFnName} = (function() {
1785
- var _z = +!String;
1786
- var _a = [${aArr.join(",")}];
1787
- var _b = [${bArr.join(",")}];
1788
- var _m0 = [${mArr.join(",")}];
2489
+ (function(){
2490
+ var _G = typeof globalThis < 'u' ? globalThis : typeof self < 'u' ? self : 0;
2491
+ var _reg = _G ? (_G.__unpeek_wasm_kdf || (_G.__unpeek_wasm_kdf = {})) : 0;
2492
+ if (_reg && _reg['${suffix}']) {
2493
+ ${kdfFnName} = _reg['${suffix}'];
2494
+ return;
2495
+ }
2496
+ var _g = [${gArr.join(",")}];
2497
+ var _evR = function(x) {
2498
+ return (${rA0} + Math.imul(x, (${rA1} + Math.imul(x, (${rA2} + Math.imul(${rA3}, x)) | 0)) | 0)) | 0;
2499
+ };
2500
+ var _sb = function(b) {
2501
+ return (Math.imul(167, b & 255) + ${sOff}) & 255;
2502
+ };
2503
+ var _tk = ['__','unp','eek_t','ampered'].join('');
2504
+ var _eG = function(sl) {
2505
+ var tp = (_G && _G[_tk] === !0) ? 0x5a5b : 0;
2506
+ return (_g[sl & 3] ^ tp) | 0;
2507
+ };
2508
+ var _eM = function(acc, pc) {
2509
+ var sb = _sb(acc) ^ (_sb(acc >>> 8) << 8);
2510
+ return (_evR((acc ^ sb ^ pc) | 0) ^ _g[2]) | 0;
2511
+ };
2512
+ try {
2513
+ var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
2514
+ var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
2515
+ var _wi${suffix} = new WebAssembly.Instance(_wm${suffix}, { env: { g: _eG, m: _eM } });
2516
+ ${kdfFnName} = _wi${suffix}.exports.kdf;
2517
+ } catch (e) {
2518
+ var _kx = [${rivEncodedTargets.join(",")}];
1789
2519
  var _k = [];
1790
2520
  for (var _j = 0; _j < ${targets.length}; _j++) {
1791
- var _u = _a[_j] | _z, _v = _b[_j];
1792
- var _t = ((_u | _v) + (_u & _v)) | 0;
1793
- _k[_j] = ((_t + _m0[_j]) - ((_t & _m0[_j]) << 1)) | 0;
2521
+ _k[_j] = (_evR(_kx[_j]) ^ _g[_j & 3]) | 0;
1794
2522
  }
1795
2523
  var _p = '';
1796
2524
  var _c = [${mChars}];
@@ -1798,21 +2526,23 @@ try {
1798
2526
  _p += String.fromCharCode(_c[_i] ^ ${strKey});
1799
2527
  }
1800
2528
  var _m = Math[_p];
1801
- return function(f, s, h) {
1802
- var _x = (f ^ _k[2] ^ _k[3]) | 0;
2529
+ ${kdfFnName} = function(f, s, h) {
2530
+ var _x = (f ^ _k[2] ^ _k[3] ^ _eG(0)) | 0;
1803
2531
  _x = (_x ^ (_x >>> 16)) | 0;
1804
2532
  _x = _m(_x, _k[0]);
1805
2533
  var _t0 = _x ^ s, _r1 = _k[4];
1806
2534
  _x = (_t0 << _r1) | (_t0 >>> (32 - _r1));
1807
- _x = _m(_x ^ h ^ _k[2], _k[1]);
2535
+ _x = _eM(_x, h | 0);
2536
+ _x = _m(_x ^ h ^ _k[2] ^ _eG(1), _k[1]);
1808
2537
  _x = (_x ^ (_x >>> 15)) | 0;
1809
2538
  var _u0 = s ^ _k[3], _r2 = _k[5];
1810
2539
  _x = (_x + ((_u0 << _r2) | (_u0 >>> (32 - _r2)))) | 0;
1811
2540
  _x = _m(_x, _k[0]);
1812
2541
  return (_x ^ (_x >>> 16)) | 0;
1813
2542
  };
1814
- })();
1815
- }`;
2543
+ }
2544
+ if (_reg) _reg['${suffix}'] = ${kdfFnName};
2545
+ })();`;
1816
2546
  const parsedHelper = acorn2.parse(helperSnippet, {
1817
2547
  ecmaVersion: "latest",
1818
2548
  sourceType: "script"
@@ -1831,7 +2561,8 @@ try {
1831
2561
  return {
1832
2562
  kdfFnName,
1833
2563
  wasmBytes,
1834
- wasmVarName
2564
+ wasmVarName,
2565
+ kdfParityVerified: true
1835
2566
  };
1836
2567
  }
1837
2568
 
@@ -1839,24 +2570,71 @@ try {
1839
2570
  import * as walk2 from "acorn-walk";
1840
2571
  var GLOBAL_HOSTS = /* @__PURE__ */ new Set(["self", "window", "globalThis"]);
1841
2572
  var MAGIC_COMMENT_RE = /webpack(?:ChunkName|Mode|Prefetch|Preload|Ignore|Include|Exclude|Exports)|@?vite-ignore|viteIgnore/i;
1842
- function isHostMember(node, propName) {
1843
- if (!node) return false;
1844
- if (node.type === "Identifier" && node.name === propName) {
1845
- return true;
2573
+ function matchesPropName(name, matcher) {
2574
+ return typeof matcher === "function" ? matcher(name) : name === matcher;
2575
+ }
2576
+ function isWebpackOrRspackChunkName(name) {
2577
+ return name.startsWith("webpackChunk") || name.startsWith("__rspack_chunk");
2578
+ }
2579
+ function isWebpackModuleMap(node) {
2580
+ if (!node || node.type !== "ObjectExpression" || !Array.isArray(node.properties) || node.properties.length === 0) {
2581
+ return false;
1846
2582
  }
1847
- if (node.type === "MemberExpression" && !node.computed && node.object?.type === "Identifier" && GLOBAL_HOSTS.has(node.object.name) && node.property?.type === "Identifier" && node.property.name === propName) {
1848
- return true;
2583
+ return node.properties.some(
2584
+ (p) => p?.type === "Property" && (p.value?.type === "FunctionExpression" || p.value?.type === "ArrowFunctionExpression")
2585
+ );
2586
+ }
2587
+ function exemptWebpackPushArg(arg, exemptSubtreeRoots) {
2588
+ if (!arg || typeof arg !== "object") return;
2589
+ if (isWebpackModuleMap(arg)) return;
2590
+ if (arg.type === "ArrayExpression" && Array.isArray(arg.elements)) {
2591
+ const hasModuleMap = arg.elements.some((el) => isWebpackModuleMap(el));
2592
+ if (hasModuleMap) {
2593
+ for (const el of arg.elements) {
2594
+ if (el && typeof el === "object" && !isWebpackModuleMap(el)) {
2595
+ exemptSubtreeRoots.add(el);
2596
+ }
2597
+ }
2598
+ return;
2599
+ }
1849
2600
  }
1850
- return false;
2601
+ exemptSubtreeRoots.add(arg);
1851
2602
  }
1852
- function unwrapAssignedHostMember(node, propName) {
2603
+ function isHostMember(node, matcher) {
1853
2604
  if (!node) return false;
1854
- if (isHostMember(node, propName)) return true;
1855
- if (node.type === "AssignmentExpression" && isHostMember(node.left, propName)) {
2605
+ if (node.type === "Identifier" && matchesPropName(node.name, matcher)) {
1856
2606
  return true;
1857
2607
  }
2608
+ if (node.type === "MemberExpression" && (node.object?.type === "Identifier" && GLOBAL_HOSTS.has(node.object.name) || node.object?.type === "ThisExpression")) {
2609
+ if (!node.computed && node.property?.type === "Identifier") {
2610
+ return matchesPropName(node.property.name, matcher);
2611
+ }
2612
+ if (node.computed && node.property?.type === "Literal" && typeof node.property.value === "string") {
2613
+ return matchesPropName(node.property.value, matcher);
2614
+ }
2615
+ }
1858
2616
  return false;
1859
2617
  }
2618
+ function unwrapAssignedHostMember(node, matcher, depth = 0) {
2619
+ if (!node || depth > 16) return false;
2620
+ if (isHostMember(node, matcher)) return true;
2621
+ switch (node.type) {
2622
+ case "ParenthesizedExpression":
2623
+ return unwrapAssignedHostMember(node.expression, matcher, depth + 1);
2624
+ case "AssignmentExpression":
2625
+ return unwrapAssignedHostMember(node.left, matcher, depth + 1) || unwrapAssignedHostMember(node.right, matcher, depth + 1);
2626
+ case "LogicalExpression":
2627
+ return unwrapAssignedHostMember(node.left, matcher, depth + 1) || unwrapAssignedHostMember(node.right, matcher, depth + 1);
2628
+ case "SequenceExpression":
2629
+ return Array.isArray(node.expressions) && node.expressions.some(
2630
+ (expr) => unwrapAssignedHostMember(expr, matcher, depth + 1)
2631
+ );
2632
+ case "ConditionalExpression":
2633
+ return unwrapAssignedHostMember(node.consequent, matcher, depth + 1) || unwrapAssignedHostMember(node.alternate, matcher, depth + 1);
2634
+ default:
2635
+ return false;
2636
+ }
2637
+ }
1860
2638
  function classifyChunkBoundary(ast) {
1861
2639
  const exemptSubtreeRoots = /* @__PURE__ */ new WeakSet();
1862
2640
  const importSourceNodes = /* @__PURE__ */ new WeakSet();
@@ -1867,7 +2645,8 @@ function classifyChunkBoundary(ast) {
1867
2645
  walk2.simple(ast, {
1868
2646
  CallExpression(node) {
1869
2647
  const callee = node.callee;
1870
- if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier" && callee.property.name === "push") {
2648
+ const isPushCall = callee?.type === "MemberExpression" && (!callee.computed && callee.property?.type === "Identifier" && callee.property.name === "push" || callee.computed && callee.property?.type === "Literal" && callee.property.value === "push");
2649
+ if (isPushCall) {
1871
2650
  if (unwrapAssignedHostMember(callee.object, "__next_f")) {
1872
2651
  hasRscFlight = true;
1873
2652
  if (Array.isArray(node.arguments)) {
@@ -1887,11 +2666,22 @@ function classifyChunkBoundary(ast) {
1887
2666
  }
1888
2667
  }
1889
2668
  }
2669
+ } else if (unwrapAssignedHostMember(callee.object, isWebpackOrRspackChunkName)) {
2670
+ hasEntryBootstrap = true;
2671
+ exemptSubtreeRoots.add(callee);
2672
+ if (callee.object && typeof callee.object === "object") {
2673
+ exemptSubtreeRoots.add(callee.object);
2674
+ }
2675
+ if (Array.isArray(node.arguments)) {
2676
+ for (const arg of node.arguments) {
2677
+ exemptWebpackPushArg(arg, exemptSubtreeRoots);
2678
+ }
2679
+ }
1890
2680
  }
1891
2681
  }
1892
2682
  },
1893
2683
  AssignmentExpression(node) {
1894
- if (isHostMember(node.left, "TURBOPACK")) {
2684
+ if (isHostMember(node.left, "TURBOPACK") || isHostMember(node.left, isWebpackOrRspackChunkName)) {
1895
2685
  hasEntryBootstrap = true;
1896
2686
  exemptSubtreeRoots.add(node);
1897
2687
  } else if (node.left?.type === "Identifier" && node.left.name === "__vite__mapDeps") {
@@ -1968,19 +2758,35 @@ function attachMagicComments(importExpressions, comments) {
1968
2758
 
1969
2759
  // src/ast/salted-vault.ts
1970
2760
  function computeCallSiteSalt(seed, idx) {
1971
- return ((Math.imul((seed ^ idx) >>> 0, 2654435761) ^ Math.imul(idx + 1 >>> 0, 73244475)) & 31) >>> 0;
2761
+ const [lo, hi] = computeCallSiteSalt64(seed >>> 0, idx >>> 0, seed >>> 0);
2762
+ return ((lo ^ hi) & 2147483647 | 1) >>> 0;
2763
+ }
2764
+ function buildRivestDeltaExpr(seed, expectedDelta, varName = "_ed") {
2765
+ const s = seed >>> 0;
2766
+ const rA0 = computeFnv1aHash(`riv-a0:${s}`, s) | 0;
2767
+ const rA1 = computeFnv1aHash(`riv-a1:${s}`, s) | 1;
2768
+ const rA2 = computeFnv1aHash(`riv-a2:${s}`, s) & ~1;
2769
+ const rA3 = computeFnv1aHash(`riv-a3:${s}`, s) & ~1;
2770
+ const hiTag = (computeFnv1aHash(`riv-hi:${s}`, s) & 65535) << 16;
2771
+ const target32 = (hiTag | expectedDelta & 65535) >>> 0;
2772
+ const xEnc = invertRivestPoly32(target32, rA0, rA1, rA2, rA3);
2773
+ const xMask = computeFnv1aHash(`riv-xm:${s}`, s) >>> 0;
2774
+ const xMasked = xEnc ^ xMask | 0;
2775
+ return `var _rx=(${xMasked}^${xMask | 0})|0,${varName}=(${rA0}+Math.imul(_rx,(${rA1}+Math.imul(_rx,(${rA2}+Math.imul(${rA3},_rx))|0))|0))&65535;`;
1972
2776
  }
1973
- function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol, safeAlpha = SAFE_ALPHA, shieldCoupled = true, browserOnly = false) {
2777
+ function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol, safeAlpha = SAFE_ALPHA, shieldCoupled = true, _browserOnly = false) {
1974
2778
  const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]`;
2779
+ const stateSym = `${windowKeySymbol}_s`;
2780
+ const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
2781
+ const flagSym = `${windowKeySymbol}_t`;
2782
+ const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
2783
+ const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
1975
2784
  let fBody;
1976
2785
  if (!shieldCoupled) {
1977
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q=(h^(""._u||a._u||0))>>>0,A="${safeAlpha}",P="${pChars}";return function(i,s){if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
1978
- } else if (browserOnly) {
1979
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q,A="${safeAlpha}",P="${pChars}";return function(i,s){if(q===void 0){var w=typeof window<"u"?window:typeof self<"u"?self:0,G=typeof globalThis<"u"?globalThis:w||this,d=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:0;q=(h^(""._u||a._u||0)^d)>>>0;}if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
2786
+ fBody = `var m=[],c=Function.prototype.toString.call(f),_tk=${tkExpr};for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var A="${safeAlpha}",P="${pChars}";return function(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||((""._u||a._u||0)!==0);if(!tm&&(i in m))return m[i];var d=tm?(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1):0;var q=(h^(""._u||a._u||0)^d)>>>0,p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var ch=p[j],k=A.indexOf(ch);o+=k<0?ch:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}if(!tm)m[i]=o;return o;};`;
1980
2787
  } else {
1981
- const maskA = computeFnv1aHash("delta-a", seed) & 65535 | 1;
1982
- const maskB = (expectedDelta & 65535 ^ maskA) & 65535;
1983
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q,A="${safeAlpha}",P="${pChars}";return function(i,s){if(q===void 0){var w=typeof window<"u"?window:typeof self<"u"?self:0,G=typeof globalThis<"u"?globalThis:w||this,d=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:(${maskA}^${maskB});q=(h^(""._u||a._u||0)^d)>>>0;}if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
2788
+ const edInit = buildRivestDeltaExpr(seed, expectedDelta, "_ed");
2789
+ fBody = `var m=[],c=Function.prototype.toString.call(f),_tk=${tkExpr};for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var A="${safeAlpha}",P="${pChars}";${edInit}return function(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0;var sv=G&&G${propAccess}!==void 0?G${propAccess}:w&&w${propAccess}!==void 0?w${propAccess}:void 0;var sr=G&&G${stateAccess}?G${stateAccess}:w&&w${stateAccess}?w${stateAccess}:void 0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||(sr&&sr[0]===2)||((""._u||a._u||0)!==0)||(sv!==void 0&&sv!==_ed);if(!tm&&sv===_ed&&(i in m))return m[i];var d=tm?((_ed^(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1))&65535):_ed;var q=(h^(""._u||a._u||0)^d)>>>0,p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var ch=p[j],k=A.indexOf(ch);o+=k<0?ch:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}if(!tm&&sv===_ed)m[i]=o;return o;};`;
1984
2790
  }
1985
2791
  return acorn3.parse(`(function f(a){${fBody}})`, {
1986
2792
  ecmaVersion: "latest",
@@ -2111,7 +2917,12 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2111
2917
  if (isTailwindNoise(node.value)) return;
2112
2918
  if (isSvgPathString(node.value, parent)) return;
2113
2919
  const callSiteIdx = targetsToReplace.length;
2114
- const localSalt = computeFnv1aHash(`salt:${seed}:${callSiteIdx}`, seed) & 2147483647 | 1;
2920
+ const [saltLo, saltHi] = computeCallSiteSalt64(
2921
+ seed >>> 0,
2922
+ callSiteIdx >>> 0,
2923
+ seed >>> 0
2924
+ );
2925
+ const localSalt = ((saltLo ^ saltHi) & 2147483647 | 1) >>> 0;
2115
2926
  targetsToReplace.push({
2116
2927
  node,
2117
2928
  parent,
@@ -2137,7 +2948,6 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2137
2948
  const dCacheVarName = `_uDc${suffix}`;
2138
2949
  const decryptFnName = `_uD${suffix}`;
2139
2950
  const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
2140
- const browserOnly = config?.target === "browser";
2141
2951
  let expDelta = expectedDelta;
2142
2952
  if (shieldCoupled && expDelta === void 0) {
2143
2953
  const shield = generateRuntimeShield({
@@ -2149,14 +2959,19 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2149
2959
  expDelta = shield.expectedDelta ?? 0;
2150
2960
  }
2151
2961
  const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
2152
- let shieldDeltaExpr;
2962
+ const stateSym = `${sym}_s`;
2963
+ const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
2964
+ const flagSym = `${sym}_t`;
2965
+ const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
2966
+ const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
2967
+ const dkExpr = `['__','unp','eek_d','elta'].join('')`;
2968
+ let helperFnSnippet;
2153
2969
  if (!shieldCoupled) {
2154
- shieldDeltaExpr = `var dv=(G&&G.__unpeek_delta!=null?G.__unpeek_delta:0)|0;${dCacheVarName}=((h|0)^dv)|0;`;
2970
+ helperFnSnippet = `function ${decryptFnName}(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0,_tk=${tkExpr},_dk=${dkExpr};var dv=(G&&G[_dk]!=null?G[_dk]:w&&w[_dk]!=null?w[_dk]:0)|0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||((""._u||0)!==0)||(dv!==0);if(!tm&&${cacheVarName}[i]!==void 0)return ${cacheVarName}[i];if(${dCacheVarName}===void 0){var c=Function.prototype.toString.call(${decryptFnName}),h=0x811c9dc5;for(var l=0;l<c.length;l++)h=Math.imul(h^c.charCodeAt(l),0x01000193)>>>0;${dCacheVarName}=h|0;}var effD=tm?((${dCacheVarName}^(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1))|0):${dCacheVarName};var k=${kdfFnName}(i,s,effD);var p=${vaultVarName}[i],o="",rk=k|0;for(var j=0;j<p.length;j++){rk=(Math.imul(rk^(j+1),0x45d9f3b)+0x9e3779b9)|0;o+=String.fromCharCode(p.charCodeAt(j)^(((rk>>>16)&127)|1));}if(!tm)${cacheVarName}[i]=o;return o;}`;
2155
2971
  } else {
2156
- const fallbackExpr = browserOnly ? "0" : `(${computeFnv1aHash("salted-a", seed) & 65535 | 1}^${((expDelta ?? 0) & 65535 ^ (computeFnv1aHash("salted-a", seed) & 65535 | 1)) & 65535})`;
2157
- shieldDeltaExpr = `var w=typeof window<"u"?window:typeof self<"u"?self:0;var sv=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:${fallbackExpr};var dv=(G&&G.__unpeek_delta!=null?G.__unpeek_delta:w&&w.__unpeek_delta!=null?w.__unpeek_delta:0)|0;${dCacheVarName}=((h|0)^(sv|0)^dv)|0;`;
2972
+ const edInit = buildRivestDeltaExpr(seed, (expDelta ?? 0) & 65535, "_ed");
2973
+ helperFnSnippet = `function ${decryptFnName}(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0,_tk=${tkExpr},_dk=${dkExpr};${edInit}var sv=G&&G${propAccess}!==void 0?G${propAccess}:w&&w${propAccess}!==void 0?w${propAccess}:void 0;var sr=G&&G${stateAccess}?G${stateAccess}:w&&w${stateAccess}?w${stateAccess}:void 0;var dv=(G&&G[_dk]!=null?G[_dk]:w&&w[_dk]!=null?w[_dk]:0)|0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||(sr&&sr[0]===2)||((""._u||0)!==0)||(dv!==0)||(sv!==void 0&&sv!==_ed);if(!tm&&sv===_ed&&${cacheVarName}[i]!==void 0)return ${cacheVarName}[i];if(${dCacheVarName}===void 0){var c=Function.prototype.toString.call(${decryptFnName}),h=0x811c9dc5;for(var l=0;l<c.length;l++)h=Math.imul(h^c.charCodeAt(l),0x01000193)>>>0;${dCacheVarName}=((h|0)^_ed)|0;}var effD=tm?((${dCacheVarName}^(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1))|0):${dCacheVarName};var k=${kdfFnName}(i,s,effD);var p=${vaultVarName}[i],o="",rk=k|0;for(var j=0;j<p.length;j++){rk=(Math.imul(rk^(j+1),0x45d9f3b)+0x9e3779b9)|0;o+=String.fromCharCode(p.charCodeAt(j)^(((rk>>>16)&127)|1));}if(!tm&&sv===_ed)${cacheVarName}[i]=o;return o;}`;
2158
2974
  }
2159
- const helperFnSnippet = `function ${decryptFnName}(i,s){if(${cacheVarName}[i]!==void 0)return ${cacheVarName}[i];if(${dCacheVarName}===void 0){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var c=Function.prototype.toString.call(${decryptFnName}),h=0x811c9dc5;for(var l=0;l<c.length;l++)h=Math.imul(h^c.charCodeAt(l),0x01000193)>>>0;${shieldDeltaExpr}}var k=${kdfFnName}(i,s,${dCacheVarName});var p=${vaultVarName}[i],o="",rk=k|0;for(var j=0;j<p.length;j++){rk=(Math.imul(rk^(j+1),0x45d9f3b)+0x9e3779b9)|0;o+=String.fromCharCode(p.charCodeAt(j)^(((rk>>>16)&127)|1));}return (${cacheVarName}[i]=o);}`;
2160
2975
  const parsedFn = acorn3.parse(helperFnSnippet, {
2161
2976
  ecmaVersion: "latest",
2162
2977
  sourceType: "script"
@@ -3182,7 +3997,7 @@ function collectPatternTargets(pattern, out, shorthandProp) {
3182
3997
  }
3183
3998
  }
3184
3999
  function isMangleableName(origName, reservedSet = RESERVED_IDENTIFIERS, manglerConfig) {
3185
- const minLength = manglerConfig?.minLength ?? 3;
4000
+ const minLength = manglerConfig?.minLength ?? 1;
3186
4001
  return origName.length >= minLength && !reservedSet.has(origName) && !JS_KEYWORDS.has(origName) && !origName.startsWith("$") && !origName.startsWith("__") && !origName.startsWith("_u") && !origName.startsWith("_0x") && (!manglerConfig?.excludePrefixes || !manglerConfig.excludePrefixes.some((p) => origName.startsWith(p))) && (!manglerConfig?.excludePatterns || !manglerConfig.excludePatterns.some(
3187
4002
  (re) => (typeof re === "string" ? new RegExp(re) : re).test(origName)
3188
4003
  ));
@@ -3590,118 +4405,310 @@ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes
3590
4405
  }
3591
4406
 
3592
4407
  // src/ast/cold-flow-guard.ts
4408
+ import * as acorn5 from "acorn";
3593
4409
  import * as walk6 from "acorn-walk";
3594
- function createDecoyObjectExpression(model) {
3595
- const m = Math.abs(model) % 3;
3596
- if (m === 0) {
3597
- return {
3598
- type: "ObjectExpression",
3599
- properties: [
3600
- {
3601
- type: "Property",
3602
- key: { type: "Identifier", name: "endpoint" },
3603
- value: {
3604
- type: "Literal",
3605
- value: "/api/v2/auth/admin-bypass",
3606
- raw: '"/api/v2/auth/admin-bypass"'
3607
- },
3608
- kind: "init",
3609
- computed: false,
3610
- method: false,
3611
- shorthand: false
3612
- },
3613
- {
3614
- type: "Property",
3615
- key: { type: "Identifier", name: "superadmin_token" },
3616
- value: { type: "Literal", value: 1, raw: "1" },
3617
- kind: "init",
3618
- computed: false,
3619
- method: false,
3620
- shorthand: false
3621
- },
3622
- {
3623
- type: "Property",
3624
- key: { type: "Identifier", name: "elevate" },
3625
- value: { type: "Literal", value: 1, raw: "1" },
3626
- kind: "init",
3627
- computed: false,
3628
- method: false,
3629
- shorthand: false
3630
- }
3631
- ]
3632
- };
4410
+ var NEUTRAL_DECOY_KEYS = [
4411
+ "telemetryOk",
4412
+ "retryBudget",
4413
+ "slotMask",
4414
+ "frameSeq",
4415
+ "digestTag",
4416
+ "phaseFlag",
4417
+ "epochSync",
4418
+ "crcState",
4419
+ "gateReady",
4420
+ "bufVer",
4421
+ "traceCode",
4422
+ "windowMode"
4423
+ ];
4424
+ function mixSeed32(seed, salt) {
4425
+ let h = (seed ^ Math.imul(salt + 1, 2654435769)) >>> 0;
4426
+ h ^= h >>> 16;
4427
+ h = Math.imul(h, 2246822507) >>> 0;
4428
+ h ^= h >>> 13;
4429
+ h = Math.imul(h, 3266489909) >>> 0;
4430
+ h ^= h >>> 16;
4431
+ return h | 0;
4432
+ }
4433
+ function cloneNode(node) {
4434
+ return JSON.parse(JSON.stringify(node));
4435
+ }
4436
+ function makeImul(left, right) {
4437
+ return {
4438
+ type: "CallExpression",
4439
+ callee: {
4440
+ type: "MemberExpression",
4441
+ computed: false,
4442
+ object: { type: "Identifier", name: "Math" },
4443
+ property: { type: "Identifier", name: "imul" }
4444
+ },
4445
+ arguments: [left, right]
4446
+ };
4447
+ }
4448
+ function makeBinary(operator, left, right) {
4449
+ return {
4450
+ type: "BinaryExpression",
4451
+ operator,
4452
+ left,
4453
+ right
4454
+ };
4455
+ }
4456
+ function makeUnary(operator, argument) {
4457
+ return {
4458
+ type: "UnaryExpression",
4459
+ operator,
4460
+ prefix: true,
4461
+ argument
4462
+ };
4463
+ }
4464
+ function makeLiteral(value) {
4465
+ return {
4466
+ type: "Literal",
4467
+ value,
4468
+ raw: JSON.stringify(value)
4469
+ };
4470
+ }
4471
+ function makeInt32Literal(value) {
4472
+ const signed = value | 0;
4473
+ if (signed < 0) {
4474
+ return makeUnary("-", makeLiteral(-signed));
3633
4475
  }
3634
- if (m === 1) {
3635
- return {
3636
- type: "ObjectExpression",
3637
- properties: [
3638
- {
3639
- type: "Property",
3640
- key: { type: "Identifier", name: "endpoint" },
3641
- value: {
3642
- type: "Literal",
3643
- value: "/api/v2/auth/verify-master",
3644
- raw: '"/api/v2/auth/verify-master"'
3645
- },
3646
- kind: "init",
3647
- computed: false,
3648
- method: false,
3649
- shorthand: false
3650
- },
3651
- {
3652
- type: "Property",
3653
- key: { type: "Identifier", name: "_verifyMasterToken" },
3654
- value: { type: "Literal", value: true, raw: "true" },
3655
- kind: "init",
3656
- computed: false,
3657
- method: false,
3658
- shorthand: false
3659
- },
3660
- {
3661
- type: "Property",
3662
- key: { type: "Identifier", name: "_bypassToken" },
3663
- value: {
3664
- type: "Literal",
3665
- value: "mock_jwt_bypass_signature",
3666
- raw: '"mock_jwt_bypass_signature"'
3667
- },
3668
- kind: "init",
3669
- computed: false,
3670
- method: false,
3671
- shorthand: false
3672
- },
3673
- {
3674
- type: "Property",
3675
- key: { type: "Identifier", name: "authorized" },
3676
- value: { type: "Literal", value: true, raw: "true" },
3677
- kind: "init",
3678
- computed: false,
3679
- method: false,
3680
- shorthand: false
3681
- }
3682
- ]
3683
- };
4476
+ return makeLiteral(signed);
4477
+ }
4478
+ function makeMemberIndex(arrayIdent, indexExpr) {
4479
+ return {
4480
+ type: "MemberExpression",
4481
+ computed: true,
4482
+ object: { type: "Identifier", name: arrayIdent },
4483
+ property: indexExpr
4484
+ };
4485
+ }
4486
+ function computeMba4Constants(seed, fnIndex, family) {
4487
+ const f = (family % 4 + 4) % 4;
4488
+ const c1 = mixSeed32(seed, fnIndex * 7 + 11);
4489
+ const m1 = mixSeed32(seed, fnIndex * 7 + 23);
4490
+ const c2 = mixSeed32(seed, fnIndex * 7 + 37);
4491
+ const m2 = mixSeed32(seed, fnIndex * 7 + 53);
4492
+ const k = mixSeed32(seed, fnIndex * 7 + 71) | 1;
4493
+ let offset = 0;
4494
+ if (f === 0) {
4495
+ offset = c1 + m1 - 1 + c2 + Math.imul(3, m2) | 0;
4496
+ } else if (f === 1) {
4497
+ offset = c1 - 1 + m1 + Math.imul(5, c2) + m2 | 0;
4498
+ } else if (f === 2) {
4499
+ offset = Math.imul(3, c1) + m1 + c2 - 1 + m2 | 0;
4500
+ } else {
4501
+ offset = -1 + c1 + Math.imul(7, m1) + c2 + m2 | 0;
4502
+ }
4503
+ const cFold = k - offset | 0;
4504
+ return { c1, m1, c2, m2, k, cFold };
4505
+ }
4506
+ function evaluateMba4Target(family, x1, x2, x3, x4, k) {
4507
+ const f = (family % 4 + 4) % 4;
4508
+ const a = x1 | 0;
4509
+ const b = x2 | 0;
4510
+ const c = x3 | 0;
4511
+ const d = x4 | 0;
4512
+ if (f === 0) return a + b - c + Math.imul(3, d) + k | 0;
4513
+ if (f === 1) return a - b + Math.imul(5, c) + d + k | 0;
4514
+ if (f === 2) return Math.imul(3, a) + b + c - d + k | 0;
4515
+ return -a + Math.imul(7, b) + c + d + k | 0;
4516
+ }
4517
+ function evaluateMba4Formula(family, x1, x2, x3, x4, consts) {
4518
+ const f = (family % 4 + 4) % 4;
4519
+ const a = x1 | 0;
4520
+ const b = x2 | 0;
4521
+ const c = x3 | 0;
4522
+ const d = x4 | 0;
4523
+ const { c1, m1, c2, m2, cFold } = consts;
4524
+ const addOr = (u, v) => (u | v) + (u & v) | 0;
4525
+ const addXor = (u, v) => (u ^ v) + ((u & v) << 1) | 0;
4526
+ const add2Or = (u, v) => ((u | v) << 1) - (u ^ v) | 0;
4527
+ if (f === 0) {
4528
+ const u1 = addOr(a, c1);
4529
+ const u2 = addXor(b, m1);
4530
+ const s122 = addXor(u1, u2);
4531
+ const n3 = addOr(~c, c2);
4532
+ const t4 = Math.imul(3, addOr(d, m2));
4533
+ const s123 = addOr(s122, n3);
4534
+ const t4k = addXor(t4, cFold);
4535
+ return addOr(s123, t4k);
4536
+ }
4537
+ if (f === 1) {
4538
+ const u1 = addXor(a, c1);
4539
+ const n2 = addXor(~b, m1);
4540
+ const s122 = addOr(u1, n2);
4541
+ const t3 = Math.imul(5, addXor(c, c2));
4542
+ const u42 = addOr(d, m2);
4543
+ const s342 = addOr(t3, u42);
4544
+ const s34k2 = addOr(s342, cFold);
4545
+ return addXor(s122, s34k2);
4546
+ }
4547
+ if (f === 2) {
4548
+ const t1 = Math.imul(3, addOr(a, c1));
4549
+ const u2 = add2Or(b, m1);
4550
+ const s122 = addOr(t1, u2);
4551
+ const u32 = addXor(c, c2);
4552
+ const n4 = addOr(~d, m2);
4553
+ const s342 = addXor(u32, n4);
4554
+ const s12k = addOr(s122, cFold);
4555
+ return addOr(s12k, s342);
4556
+ }
4557
+ const n1 = addOr(~a, c1);
4558
+ const t2 = Math.imul(7, addXor(b, m1));
4559
+ const s12 = add2Or(n1, t2);
4560
+ const u3 = addOr(c, c2);
4561
+ const u4 = addXor(d, m2);
4562
+ const s34 = addOr(u3, u4);
4563
+ const s34k = addXor(s34, cFold);
4564
+ return addOr(s12, s34k);
4565
+ }
4566
+ var MBA_CHECK_VECTORS = [
4567
+ [0, 0, 0, 0],
4568
+ [1, -1, 42, 2147483647],
4569
+ [-2147483648, 1437217740, -12345, 999999],
4570
+ [305419896, -591751049, 3735928559 | 0, 3405691582 | 0]
4571
+ ];
4572
+ function verifyMba4FamilyEquivalence(family, consts) {
4573
+ for (const [x1, x2, x3, x4] of MBA_CHECK_VECTORS) {
4574
+ const lhs = evaluateMba4Formula(family, x1, x2, x3, x4, consts);
4575
+ const rhs = evaluateMba4Target(family, x1, x2, x3, x4, consts.k);
4576
+ if (lhs !== rhs) return false;
3684
4577
  }
4578
+ return true;
4579
+ }
4580
+ function makeMbaAddOr(u, v) {
4581
+ return makeBinary(
4582
+ "|",
4583
+ makeBinary("+", makeBinary("|", cloneNode(u), cloneNode(v)), makeBinary("&", cloneNode(u), cloneNode(v))),
4584
+ makeLiteral(0)
4585
+ );
4586
+ }
4587
+ function makeMbaAddXor(u, v) {
4588
+ return makeBinary(
4589
+ "|",
4590
+ makeBinary(
4591
+ "+",
4592
+ makeBinary("^", cloneNode(u), cloneNode(v)),
4593
+ makeBinary("<<", makeBinary("&", cloneNode(u), cloneNode(v)), makeLiteral(1))
4594
+ ),
4595
+ makeLiteral(0)
4596
+ );
4597
+ }
4598
+ function makeMbaAdd2Or(u, v) {
4599
+ return makeBinary(
4600
+ "|",
4601
+ makeBinary(
4602
+ "-",
4603
+ makeBinary("<<", makeBinary("|", cloneNode(u), cloneNode(v)), makeLiteral(1)),
4604
+ makeBinary("^", cloneNode(u), cloneNode(v))
4605
+ ),
4606
+ makeLiteral(0)
4607
+ );
4608
+ }
4609
+ function buildMba4Ast(seed, fnIndex, x1Node, x2Node, x3Node, x4Node) {
4610
+ const family = Math.abs((seed ^ Math.imul(fnIndex + 1, 668265261)) % 4);
4611
+ const consts = computeMba4Constants(seed, fnIndex, family);
4612
+ if (!verifyMba4FamilyEquivalence(family, consts)) {
4613
+ throw new Error(`MBA4 algebraic equivalence check failed for family ${family}`);
4614
+ }
4615
+ const c1Lit = makeInt32Literal(consts.c1);
4616
+ const m1Lit = makeInt32Literal(consts.m1);
4617
+ const c2Lit = makeInt32Literal(consts.c2);
4618
+ const m2Lit = makeInt32Literal(consts.m2);
4619
+ const cFoldLit = makeInt32Literal(consts.cFold);
4620
+ if (family === 0) {
4621
+ const u1 = makeMbaAddOr(x1Node, c1Lit);
4622
+ const u2 = makeMbaAddXor(x2Node, m1Lit);
4623
+ const s122 = makeMbaAddXor(u1, u2);
4624
+ const n3 = makeMbaAddOr(makeUnary("~", cloneNode(x3Node)), c2Lit);
4625
+ const t4 = makeImul(makeLiteral(3), makeMbaAddOr(x4Node, m2Lit));
4626
+ const s123 = makeMbaAddOr(s122, n3);
4627
+ const t4k = makeMbaAddXor(t4, cFoldLit);
4628
+ return makeMbaAddOr(s123, t4k);
4629
+ }
4630
+ if (family === 1) {
4631
+ const u1 = makeMbaAddXor(x1Node, c1Lit);
4632
+ const n2 = makeMbaAddXor(makeUnary("~", cloneNode(x2Node)), m1Lit);
4633
+ const s122 = makeMbaAddOr(u1, n2);
4634
+ const t3 = makeImul(makeLiteral(5), makeMbaAddXor(x3Node, c2Lit));
4635
+ const u42 = makeMbaAddOr(x4Node, m2Lit);
4636
+ const s342 = makeMbaAddOr(t3, u42);
4637
+ const s34k2 = makeMbaAddOr(s342, cFoldLit);
4638
+ return makeMbaAddXor(s122, s34k2);
4639
+ }
4640
+ if (family === 2) {
4641
+ const t1 = makeImul(makeLiteral(3), makeMbaAddOr(x1Node, c1Lit));
4642
+ const u2 = makeMbaAdd2Or(x2Node, m1Lit);
4643
+ const s122 = makeMbaAddOr(t1, u2);
4644
+ const u32 = makeMbaAddXor(x3Node, c2Lit);
4645
+ const n4 = makeMbaAddOr(makeUnary("~", cloneNode(x4Node)), m2Lit);
4646
+ const s342 = makeMbaAddXor(u32, n4);
4647
+ const s12k = makeMbaAddOr(s122, cFoldLit);
4648
+ return makeMbaAddOr(s12k, s342);
4649
+ }
4650
+ const n1 = makeMbaAddOr(makeUnary("~", cloneNode(x1Node)), c1Lit);
4651
+ const t2 = makeImul(makeLiteral(7), makeMbaAddXor(x2Node, m1Lit));
4652
+ const s12 = makeMbaAdd2Or(n1, t2);
4653
+ const u3 = makeMbaAddOr(x3Node, c2Lit);
4654
+ const u4 = makeMbaAddXor(x4Node, m2Lit);
4655
+ const s34 = makeMbaAddOr(u3, u4);
4656
+ const s34k = makeMbaAddXor(s34, cFoldLit);
4657
+ return makeMbaAddOr(s12, s34k);
4658
+ }
4659
+ function buildRivestPermAst(seed, fnIndex, uExpr) {
4660
+ const a0 = mixSeed32(seed, fnIndex * 13 + 3);
4661
+ const a1 = mixSeed32(seed, fnIndex * 13 + 5) | 1;
4662
+ const a2 = mixSeed32(seed, fnIndex * 13 + 7) & ~1;
4663
+ const a3 = mixSeed32(seed, fnIndex * 13 + 9) & ~1;
4664
+ const deg3 = makeImul(cloneNode(uExpr), makeInt32Literal(a3));
4665
+ const deg2 = makeImul(cloneNode(uExpr), makeBinary("+", makeInt32Literal(a2), deg3));
4666
+ const deg1 = makeImul(cloneNode(uExpr), makeBinary("+", makeInt32Literal(a1), deg2));
4667
+ return makeBinary("|", makeBinary("+", makeInt32Literal(a0), deg1), makeLiteral(0));
4668
+ }
4669
+ function buildSboxMixAst(sboxIdent, wIdent) {
4670
+ const lowByte = makeMemberIndex(
4671
+ sboxIdent,
4672
+ makeBinary("&", { type: "Identifier", name: wIdent }, makeLiteral(255))
4673
+ );
4674
+ const highByte = makeBinary(
4675
+ "<<",
4676
+ makeMemberIndex(
4677
+ sboxIdent,
4678
+ makeBinary(
4679
+ "&",
4680
+ makeBinary(">>>", { type: "Identifier", name: wIdent }, makeLiteral(8)),
4681
+ makeLiteral(255)
4682
+ )
4683
+ ),
4684
+ makeLiteral(8)
4685
+ );
4686
+ return makeBinary(
4687
+ "|",
4688
+ makeBinary("^", makeBinary("^", { type: "Identifier", name: wIdent }, lowByte), highByte),
4689
+ makeLiteral(0)
4690
+ );
4691
+ }
4692
+ function pickNeutralKey(seed, index) {
4693
+ const idx = Math.abs(seed ^ Math.imul(index + 1, 2654435769) | 0) % NEUTRAL_DECOY_KEYS.length;
4694
+ return NEUTRAL_DECOY_KEYS[idx];
4695
+ }
4696
+ function createDecoyObjectExpression(model, seed = 2654435769, zExpr) {
4697
+ const m = Math.abs(model) % 3;
4698
+ const k0 = NEUTRAL_DECOY_KEYS[m * 3 % NEUTRAL_DECOY_KEYS.length];
4699
+ const k1 = NEUTRAL_DECOY_KEYS[(m * 3 + 1) % NEUTRAL_DECOY_KEYS.length];
4700
+ const k2 = NEUTRAL_DECOY_KEYS[(m * 3 + 2) % NEUTRAL_DECOY_KEYS.length];
4701
+ const tagNum = (mixSeed32(seed, m + 11) >>> 0) % 900 + 100;
4702
+ const val0 = zExpr ? makeBinary("&", cloneNode(zExpr), makeLiteral(255)) : makeLiteral((m + 1) * 17);
4703
+ const val1 = zExpr ? makeBinary("===", makeBinary("&", cloneNode(zExpr), makeLiteral(1)), makeLiteral(0)) : makeLiteral(false);
4704
+ const val2 = makeLiteral(`v${m}_${tagNum}`);
3685
4705
  return {
3686
4706
  type: "ObjectExpression",
3687
4707
  properties: [
3688
4708
  {
3689
4709
  type: "Property",
3690
- key: { type: "Identifier", name: "endpoint" },
3691
- value: {
3692
- type: "Literal",
3693
- value: "/api/v2/auth/debug-telemetry",
3694
- raw: '"/api/v2/auth/debug-telemetry"'
3695
- },
3696
- kind: "init",
3697
- computed: false,
3698
- method: false,
3699
- shorthand: false
3700
- },
3701
- {
3702
- type: "Property",
3703
- key: { type: "Identifier", name: "debug_supervisor_override" },
3704
- value: { type: "Literal", value: true, raw: "true" },
4710
+ key: { type: "Identifier", name: k0 },
4711
+ value: val0,
3705
4712
  kind: "init",
3706
4713
  computed: false,
3707
4714
  method: false,
@@ -3709,12 +4716,8 @@ function createDecoyObjectExpression(model) {
3709
4716
  },
3710
4717
  {
3711
4718
  type: "Property",
3712
- key: { type: "Identifier", name: "_bypassToken" },
3713
- value: {
3714
- type: "Literal",
3715
- value: "superadmin_token",
3716
- raw: '"superadmin_token"'
3717
- },
4719
+ key: { type: "Identifier", name: k1 },
4720
+ value: val1,
3718
4721
  kind: "init",
3719
4722
  computed: false,
3720
4723
  method: false,
@@ -3722,8 +4725,8 @@ function createDecoyObjectExpression(model) {
3722
4725
  },
3723
4726
  {
3724
4727
  type: "Property",
3725
- key: { type: "Identifier", name: "mfa_bypassed" },
3726
- value: { type: "Literal", value: true, raw: "true" },
4728
+ key: { type: "Identifier", name: k2 },
4729
+ value: val2,
3727
4730
  kind: "init",
3728
4731
  computed: false,
3729
4732
  method: false,
@@ -3732,46 +4735,89 @@ function createDecoyObjectExpression(model) {
3732
4735
  ]
3733
4736
  };
3734
4737
  }
3735
- function createDecoyConsequent(fnIndex) {
3736
- return {
3737
- type: "BlockStatement",
3738
- body: [
3739
- {
3740
- type: "ReturnStatement",
3741
- argument: createDecoyObjectExpression(fnIndex)
3742
- }
3743
- ]
3744
- };
3745
- }
3746
- function createSharedDecoyConsequent(decoyIdent, fnIndex) {
4738
+ function createContextualDecoyConsequent(fnIndex, seed, domain, decoyIdent, zExpr) {
4739
+ const zRef = zExpr ? cloneNode(zExpr) : makeLiteral(mixSeed32(seed, fnIndex) & 255);
4740
+ const mask = mixSeed32(seed, fnIndex + 31) & 65535;
4741
+ if (domain === "void") {
4742
+ return {
4743
+ type: "BlockStatement",
4744
+ body: [{ type: "ReturnStatement", argument: null }]
4745
+ };
4746
+ }
4747
+ if (domain === "number") {
4748
+ return {
4749
+ type: "BlockStatement",
4750
+ body: [
4751
+ {
4752
+ type: "ReturnStatement",
4753
+ argument: makeBinary("|", makeBinary("^", zRef, makeLiteral(mask)), makeLiteral(0))
4754
+ }
4755
+ ]
4756
+ };
4757
+ }
4758
+ if (domain === "boolean") {
4759
+ return {
4760
+ type: "BlockStatement",
4761
+ body: [
4762
+ {
4763
+ type: "ReturnStatement",
4764
+ argument: makeBinary("===", makeBinary("&", zRef, makeLiteral(1)), makeLiteral(0))
4765
+ }
4766
+ ]
4767
+ };
4768
+ }
4769
+ if (domain === "string") {
4770
+ const tag = pickNeutralKey(seed, fnIndex);
4771
+ return {
4772
+ type: "BlockStatement",
4773
+ body: [
4774
+ {
4775
+ type: "ReturnStatement",
4776
+ argument: makeBinary(
4777
+ "+",
4778
+ makeLiteral(`${tag}:`),
4779
+ makeBinary("&", zRef, makeLiteral(255))
4780
+ )
4781
+ }
4782
+ ]
4783
+ };
4784
+ }
3747
4785
  const model = Math.abs(fnIndex) % 3;
4786
+ if (decoyIdent) {
4787
+ return {
4788
+ type: "BlockStatement",
4789
+ body: [
4790
+ {
4791
+ type: "ReturnStatement",
4792
+ argument: {
4793
+ type: "CallExpression",
4794
+ callee: {
4795
+ type: "MemberExpression",
4796
+ computed: true,
4797
+ object: { type: "Identifier", name: decoyIdent },
4798
+ property: makeLiteral(model)
4799
+ },
4800
+ arguments: [zRef]
4801
+ }
4802
+ }
4803
+ ]
4804
+ };
4805
+ }
3748
4806
  return {
3749
4807
  type: "BlockStatement",
3750
4808
  body: [
3751
4809
  {
3752
4810
  type: "ReturnStatement",
3753
- argument: {
3754
- type: "CallExpression",
3755
- callee: {
3756
- type: "MemberExpression",
3757
- computed: true,
3758
- object: { type: "Identifier", name: decoyIdent },
3759
- property: {
3760
- type: "Literal",
3761
- value: model,
3762
- raw: String(model)
3763
- }
3764
- },
3765
- arguments: []
3766
- }
4811
+ argument: createDecoyObjectExpression(model, seed, zRef)
3767
4812
  }
3768
4813
  ]
3769
4814
  };
3770
4815
  }
3771
- function createSharedDecoyDeclaration(decoyIdent = "_d", maxModels = 3) {
4816
+ function createSharedDecoyDeclaration(decoyIdent = "_d", maxModels = 3, seed = 2654435769) {
3772
4817
  const count = Math.max(1, Math.min(3, maxModels));
3773
4818
  const indices = [];
3774
4819
  for (let i = 0; i < count; i++) indices.push(i);
4820
+ const paramArg = { type: "Identifier", name: "_v" };
3775
4821
  return {
3776
4822
  type: "VariableDeclaration",
3777
4823
  kind: "var",
@@ -3784,8 +4830,8 @@ function createSharedDecoyDeclaration(decoyIdent = "_d", maxModels = 3) {
3784
4830
  elements: indices.map((m) => ({
3785
4831
  type: "ArrowFunctionExpression",
3786
4832
  id: null,
3787
- params: [],
3788
- body: createDecoyObjectExpression(m),
4833
+ params: [cloneNode(paramArg)],
4834
+ body: createDecoyObjectExpression(m, seed, paramArg),
3789
4835
  generator: false,
3790
4836
  async: false,
3791
4837
  expression: true
@@ -3795,165 +4841,274 @@ function createSharedDecoyDeclaration(decoyIdent = "_d", maxModels = 3) {
3795
4841
  ]
3796
4842
  };
3797
4843
  }
3798
- function cloneNode(node) {
3799
- return JSON.parse(JSON.stringify(node));
4844
+ function extractParamNames(paramNode, out = []) {
4845
+ if (!paramNode) return out;
4846
+ if (typeof paramNode === "string") {
4847
+ if (paramNode !== "arguments" && paramNode !== "eval") out.push(paramNode);
4848
+ return out;
4849
+ }
4850
+ switch (paramNode.type) {
4851
+ case "Identifier":
4852
+ if (paramNode.name !== "arguments" && paramNode.name !== "eval") {
4853
+ out.push(paramNode.name);
4854
+ }
4855
+ break;
4856
+ case "AssignmentPattern":
4857
+ extractParamNames(paramNode.left, out);
4858
+ break;
4859
+ case "RestElement":
4860
+ extractParamNames(paramNode.argument, out);
4861
+ break;
4862
+ case "ArrayPattern":
4863
+ for (const el of paramNode.elements || []) {
4864
+ if (el) extractParamNames(el, out);
4865
+ }
4866
+ break;
4867
+ case "ObjectPattern":
4868
+ for (const prop of paramNode.properties || []) {
4869
+ if (prop.type === "Property") {
4870
+ extractParamNames(prop.value, out);
4871
+ } else if (prop.type === "RestElement") {
4872
+ extractParamNames(prop.argument, out);
4873
+ }
4874
+ }
4875
+ break;
4876
+ }
4877
+ return out;
3800
4878
  }
3801
- function makeImul(left, right) {
3802
- return {
3803
- type: "CallExpression",
3804
- callee: {
4879
+ function buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn = false, ctxOpts) {
4880
+ const candidates = [];
4881
+ const seenNames = /* @__PURE__ */ new Set();
4882
+ const names = [...ctxOpts?.liveVars ?? [], ...extractParamNames(paramNode)];
4883
+ for (const name of names) {
4884
+ if (name && name !== "arguments" && name !== "eval" && !seenNames.has(name)) {
4885
+ seenNames.add(name);
4886
+ candidates.push(makeBinary("|", { type: "Identifier", name }, makeLiteral(0)));
4887
+ }
4888
+ }
4889
+ if (ctxOpts?.aliasIdentA && ctxOpts?.aliasIdentB) {
4890
+ const slot0 = fnIndex + 0 & 3;
4891
+ const slot1 = fnIndex + 1 & 3;
4892
+ candidates.push(makeBinary("|", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slot0)), makeLiteral(0)));
4893
+ candidates.push(makeBinary("|", makeMemberIndex(ctxOpts.aliasIdentB, makeLiteral(slot1)), makeLiteral(0)));
4894
+ }
4895
+ if (!isArrowFn) {
4896
+ candidates.push({
4897
+ type: "MemberExpression",
4898
+ computed: false,
4899
+ object: { type: "Identifier", name: "arguments" },
4900
+ property: { type: "Identifier", name: "length" }
4901
+ });
4902
+ }
4903
+ candidates.push({
4904
+ type: "MemberExpression",
4905
+ computed: false,
4906
+ object: makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
4907
+ property: { type: "Identifier", name: "length" }
4908
+ });
4909
+ candidates.push({
4910
+ type: "MemberExpression",
4911
+ computed: false,
4912
+ object: makeUnary("typeof", {
3805
4913
  type: "MemberExpression",
3806
4914
  computed: false,
3807
4915
  object: { type: "Identifier", name: "Math" },
3808
4916
  property: { type: "Identifier", name: "imul" }
3809
- },
3810
- arguments: [left, right]
3811
- };
4917
+ }),
4918
+ property: { type: "Identifier", name: "length" }
4919
+ });
4920
+ candidates.push({
4921
+ type: "MemberExpression",
4922
+ computed: false,
4923
+ object: makeUnary("typeof", { type: "Identifier", name: "Object" }),
4924
+ property: { type: "Identifier", name: "length" }
4925
+ });
4926
+ while (candidates.length < 4) {
4927
+ const base2 = candidates[0] ?? makeLiteral(mixSeed32(seed, fnIndex));
4928
+ const m = mixSeed32(seed, fnIndex + candidates.length * 19);
4929
+ candidates.push(makeBinary("^", cloneNode(base2), makeInt32Literal(m)));
4930
+ }
4931
+ return [candidates[0], candidates[1], candidates[2], candidates[3]];
3812
4932
  }
3813
- function makeBinary(operator, left, right) {
3814
- return {
3815
- type: "BinaryExpression",
3816
- operator,
3817
- left,
3818
- right
3819
- };
3820
- }
3821
- function makeUnary(operator, argument) {
3822
- return {
3823
- type: "UnaryExpression",
3824
- operator,
3825
- prefix: true,
3826
- argument
3827
- };
3828
- }
3829
- function makeLiteral(value) {
3830
- return {
3831
- type: "Literal",
3832
- value,
3833
- raw: String(value)
3834
- };
3835
- }
3836
- function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false) {
3837
- const family = Math.abs((seed + fnIndex) % 5);
3838
- const c1 = (seed >>> 1) + Math.imul(family + 1, 22912827) & 32767;
3839
- const c2 = (c1 ^ 173477) & 32767;
3840
- const target = (seed ^ Math.imul(family + 1, 2654435761)) & 65535 | 1;
3841
- let paramName = null;
3842
- if (typeof paramNode === "string") {
3843
- paramName = paramNode;
3844
- } else if (paramNode?.type === "Identifier") {
3845
- paramName = paramNode.name;
3846
- } else if (paramNode?.type === "AssignmentPattern" && paramNode.left?.type === "Identifier") {
3847
- paramName = paramNode.left.name;
3848
- } else if (paramNode?.type === "RestElement" && paramNode.argument?.type === "Identifier") {
3849
- paramName = paramNode.argument.name;
3850
- }
3851
- let vBitNode;
3852
- let vIntNode;
3853
- if (paramName && paramName !== "arguments" && paramName !== "eval") {
3854
- vBitNode = { type: "Identifier", name: paramName };
3855
- vIntNode = makeBinary("|", { type: "Identifier", name: paramName }, makeLiteral(0));
3856
- } else if (!isArrowFn) {
3857
- vBitNode = {
3858
- type: "MemberExpression",
3859
- computed: false,
3860
- object: { type: "Identifier", name: "arguments" },
3861
- property: { type: "Identifier", name: "length" }
4933
+ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false, ctxOpts) {
4934
+ const domain = ctxOpts?.returnDomain ?? "object";
4935
+ const [x1, x2, x3, x4] = buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn, ctxOpts);
4936
+ const mba4 = buildMba4Ast(seed, fnIndex, x1, x2, x3, x4);
4937
+ let qnrLeft;
4938
+ let zRefForDecoy;
4939
+ if (ctxOpts?.scratchVarIdent) {
4940
+ const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
4941
+ const rivestOnScratch = buildRivestPermAst(seed, fnIndex, scratchId);
4942
+ const seqExprs = [
4943
+ {
4944
+ type: "AssignmentExpression",
4945
+ operator: "=",
4946
+ left: cloneNode(scratchId),
4947
+ right: mba4
4948
+ },
4949
+ {
4950
+ type: "AssignmentExpression",
4951
+ operator: "=",
4952
+ left: cloneNode(scratchId),
4953
+ right: rivestOnScratch
4954
+ }
4955
+ ];
4956
+ if (ctxOpts.sboxIdent) {
4957
+ seqExprs.push({
4958
+ type: "AssignmentExpression",
4959
+ operator: "=",
4960
+ left: cloneNode(scratchId),
4961
+ right: buildSboxMixAst(ctxOpts.sboxIdent, ctxOpts.scratchVarIdent)
4962
+ });
4963
+ }
4964
+ seqExprs.push(
4965
+ makeBinary(
4966
+ "&",
4967
+ makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(1)),
4968
+ makeLiteral(3)
4969
+ )
4970
+ );
4971
+ qnrLeft = {
4972
+ type: "SequenceExpression",
4973
+ expressions: seqExprs
3862
4974
  };
3863
- vIntNode = cloneNode(vBitNode);
4975
+ zRefForDecoy = cloneNode(scratchId);
3864
4976
  } else {
3865
- vBitNode = {
3866
- type: "MemberExpression",
3867
- computed: false,
3868
- object: makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
3869
- property: { type: "Identifier", name: "length" }
3870
- };
3871
- vIntNode = cloneNode(vBitNode);
4977
+ const zExpr = buildRivestPermAst(seed, fnIndex, mba4);
4978
+ qnrLeft = makeBinary(
4979
+ "&",
4980
+ makeBinary("+", makeImul(cloneNode(zExpr), cloneNode(zExpr)), makeLiteral(1)),
4981
+ makeLiteral(3)
4982
+ );
4983
+ zRefForDecoy = zExpr;
3872
4984
  }
3873
- const kLit = makeLiteral(c2);
3874
- let mbaExpr;
3875
- if (family === 0) {
3876
- const term1 = makeImul(cloneNode(vIntNode), cloneNode(kLit));
3877
- const vAndK = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3878
- const vOrK = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3879
- const notK = makeUnary("~", cloneNode(kLit));
3880
- const notV = makeUnary("~", cloneNode(vBitNode));
3881
- const vAndNotK = makeBinary("&", cloneNode(vBitNode), notK);
3882
- const notVAndK = makeBinary("&", notV, cloneNode(kLit));
3883
- const term2 = makeImul(vAndK, vOrK);
3884
- const term3 = makeImul(vAndNotK, notVAndK);
3885
- const sumTerms = makeBinary("+", term2, term3);
3886
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3887
- } else if (family === 1) {
3888
- const vXorK1 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3889
- const vXorK2 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3890
- const term1 = makeImul(vXorK1, vXorK2);
3891
- const vSubK1 = makeBinary("-", cloneNode(vIntNode), cloneNode(kLit));
3892
- const vSubK2 = makeBinary("-", cloneNode(vIntNode), cloneNode(kLit));
3893
- const term2 = makeImul(vSubK1, vSubK2);
3894
- const notK = makeUnary("~", cloneNode(kLit));
3895
- const notV = makeUnary("~", cloneNode(vBitNode));
3896
- const vAndNotK = makeBinary("&", cloneNode(vBitNode), notK);
3897
- const notVAndK = makeBinary("&", notV, cloneNode(kLit));
3898
- const term3 = makeImul(vAndNotK, notVAndK);
3899
- const shiftTerm = makeBinary("<<", term3, makeLiteral(2));
3900
- const sumTerms = makeBinary("+", term2, shiftTerm);
3901
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3902
- } else if (family === 2) {
3903
- const vAddK1 = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3904
- const vAddK2 = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3905
- const term1 = makeImul(vAddK1, vAddK2);
3906
- const vAndK = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3907
- const vOrK = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3908
- const term2 = makeImul(vAndK, vOrK);
3909
- const shiftTerm = makeBinary("<<", term2, makeLiteral(2));
3910
- const vXorK1 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3911
- const vXorK2 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3912
- const term3 = makeImul(vXorK1, vXorK2);
3913
- const sumTerms = makeBinary("+", shiftTerm, term3);
3914
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3915
- } else if (family === 3) {
3916
- const vOrK1 = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3917
- const vOrK2 = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3918
- const term1 = makeImul(vOrK1, vOrK2);
3919
- const vAndK1 = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3920
- const vAndK2 = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3921
- const term2 = makeImul(vAndK1, vAndK2);
3922
- const vXorK = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3923
- const vAddK = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3924
- const term3 = makeImul(vXorK, vAddK);
3925
- const sumTerms = makeBinary("+", term2, term3);
3926
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3927
- } else {
3928
- const vk = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3929
- const vkSq = makeImul(vk, cloneNode(vk));
3930
- const sevenVkSqSub1 = makeBinary("-", makeImul(makeLiteral(7), vkSq), makeLiteral(1));
3931
- const vSq = makeImul(cloneNode(vBitNode), cloneNode(vBitNode));
3932
- const quadDiff = makeBinary("^", makeBinary("&", makeBinary("^", sevenVkSqSub1, vSq), makeLiteral(2)), makeLiteral(2));
3933
- const parityTerm = makeBinary("&", makeBinary("+", makeImul(cloneNode(vBitNode), cloneNode(vBitNode)), cloneNode(vIntNode)), makeLiteral(1));
3934
- mbaExpr = makeBinary("|", quadDiff, parityTerm);
3935
- }
3936
- const decoyIdx = Math.abs(fnIndex) % 3;
3937
- const consequent = decoyIdent ? createSharedDecoyConsequent(decoyIdent, decoyIdx) : createDecoyConsequent(decoyIdx);
4985
+ const consequent = createContextualDecoyConsequent(
4986
+ fnIndex,
4987
+ seed,
4988
+ domain,
4989
+ decoyIdent,
4990
+ zRefForDecoy
4991
+ );
3938
4992
  return {
3939
4993
  type: "IfStatement",
3940
4994
  test: {
3941
4995
  type: "BinaryExpression",
3942
4996
  operator: "===",
3943
- left: mbaExpr,
3944
- right: { type: "Literal", value: target, raw: String(target) }
4997
+ left: qnrLeft,
4998
+ right: makeLiteral(3)
3945
4999
  },
3946
5000
  consequent,
3947
5001
  alternate: null
3948
5002
  };
3949
5003
  }
5004
+ function inferFunctionReturnDomain(fnNode) {
5005
+ let hasReturnArg = false;
5006
+ let seenNumber = false;
5007
+ let seenBoolean = false;
5008
+ let seenString = false;
5009
+ let seenObject = false;
5010
+ function scanStmts(node) {
5011
+ if (!node || typeof node !== "object") return;
5012
+ if (Array.isArray(node)) {
5013
+ for (const item of node) scanStmts(item);
5014
+ return;
5015
+ }
5016
+ if (node !== fnNode && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) {
5017
+ return;
5018
+ }
5019
+ if (node.type === "ReturnStatement") {
5020
+ if (!node.argument) return;
5021
+ hasReturnArg = true;
5022
+ const arg = node.argument;
5023
+ if (arg.type === "Literal") {
5024
+ if (typeof arg.value === "number") seenNumber = true;
5025
+ else if (typeof arg.value === "boolean") seenBoolean = true;
5026
+ else if (typeof arg.value === "string") seenString = true;
5027
+ } else if (arg.type === "ObjectExpression" || arg.type === "ArrayExpression") {
5028
+ seenObject = true;
5029
+ } else if (arg.type === "BinaryExpression") {
5030
+ if (["===", "!==", "==", "!=", "<", ">", "<=", ">=", "in", "instanceof"].includes(arg.operator)) {
5031
+ seenBoolean = true;
5032
+ } else if (arg.operator !== "+") {
5033
+ seenNumber = true;
5034
+ }
5035
+ } else if (arg.type === "UnaryExpression") {
5036
+ if (arg.operator === "!") seenBoolean = true;
5037
+ else if (arg.operator === "typeof") seenString = true;
5038
+ else if (arg.operator === "-" || arg.operator === "+" || arg.operator === "~") seenNumber = true;
5039
+ }
5040
+ return;
5041
+ }
5042
+ for (const key of Object.keys(node)) {
5043
+ if (key === "loc" || key === "range") continue;
5044
+ const val = node[key];
5045
+ if (val && typeof val === "object") {
5046
+ scanStmts(val);
5047
+ }
5048
+ }
5049
+ }
5050
+ scanStmts(fnNode.body);
5051
+ if (!hasReturnArg && fnNode.body?.type === "BlockStatement") return "void";
5052
+ if (seenObject) return "object";
5053
+ if (seenBoolean && !seenNumber && !seenString) return "boolean";
5054
+ if (seenNumber && !seenBoolean && !seenString) return "number";
5055
+ if (seenString && !seenNumber && !seenBoolean) return "string";
5056
+ return "object";
5057
+ }
5058
+ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed) {
5059
+ const sboxInit = acorn5.parseExpressionAt(
5060
+ `(function(){var a=[],i,s=${seed | 0},j,t;for(i=0;i<256;i++)a[i]=i;for(i=255;i>0;i--){s=(Math.imul(s,1664525)+1013904223)|0;j=(s>>>0)%(i+1);t=a[i];a[i]=a[j];a[j]=t;}return a;})()`,
5061
+ 0,
5062
+ { ecmaVersion: "latest" }
5063
+ );
5064
+ const stateVals = [
5065
+ mixSeed32(seed, 101),
5066
+ mixSeed32(seed, 103),
5067
+ mixSeed32(seed, 107),
5068
+ mixSeed32(seed, 109)
5069
+ ];
5070
+ return {
5071
+ type: "VariableDeclaration",
5072
+ kind: "var",
5073
+ declarations: [
5074
+ {
5075
+ type: "VariableDeclarator",
5076
+ id: { type: "Identifier", name: sboxIdent },
5077
+ init: sboxInit
5078
+ },
5079
+ {
5080
+ type: "VariableDeclarator",
5081
+ id: { type: "Identifier", name: aliasIdentA },
5082
+ init: {
5083
+ type: "ArrayExpression",
5084
+ elements: stateVals.map((v) => makeInt32Literal(v))
5085
+ }
5086
+ },
5087
+ {
5088
+ type: "VariableDeclarator",
5089
+ id: { type: "Identifier", name: aliasIdentB },
5090
+ init: { type: "Identifier", name: aliasIdentA }
5091
+ },
5092
+ {
5093
+ type: "VariableDeclarator",
5094
+ id: { type: "Identifier", name: scratchVarIdent },
5095
+ init: makeLiteral(0)
5096
+ }
5097
+ ]
5098
+ };
5099
+ }
3950
5100
  var MAX_COLD_GUARDS_PER_CHUNK = 12;
3951
5101
  function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
3952
5102
  const decoyIdent = "_d";
5103
+ const sfx = (seed >>> 0).toString(36).slice(0, 4);
5104
+ const sboxIdent = `_uSb${sfx}`;
5105
+ const aliasIdentA = `_uAl${sfx}`;
5106
+ const aliasIdentB = `_uAm${sfx}`;
5107
+ const scratchVarIdent = `_uZt${sfx}`;
3953
5108
  if (Array.isArray(ast.body)) {
3954
5109
  const alreadyGuarded = ast.body.some(
3955
5110
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3956
- (d) => d.id?.type === "Identifier" && d.id.name === decoyIdent
5111
+ (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent)
3957
5112
  )
3958
5113
  );
3959
5114
  if (alreadyGuarded) return 0;
@@ -3962,15 +5117,29 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
3962
5117
  function maybeInjectGuard(node) {
3963
5118
  if (guardedCount >= MAX_COLD_GUARDS_PER_CHUNK) return;
3964
5119
  if (!coldFunctionNodes.has(node)) return;
5120
+ if (hotExemptNodes?.has(node) || node._unpeekSerialized) return;
3965
5121
  if (!node.body || node.body.type !== "BlockStatement") return;
5122
+ const paramNames = [];
5123
+ for (const p of node.params || []) {
5124
+ extractParamNames(p, paramNames);
5125
+ }
3966
5126
  const firstParam = node.params?.[0];
3967
5127
  const isArrow = node.type === "ArrowFunctionExpression";
5128
+ const returnDomain = inferFunctionReturnDomain(node);
3968
5129
  const guardStmt = createSotaMbaPredicate(
3969
5130
  seed,
3970
5131
  guardedCount,
3971
5132
  firstParam,
3972
5133
  decoyIdent,
3973
- isArrow
5134
+ isArrow,
5135
+ {
5136
+ liveVars: paramNames,
5137
+ sboxIdent,
5138
+ aliasIdentA,
5139
+ aliasIdentB,
5140
+ scratchVarIdent,
5141
+ returnDomain
5142
+ }
3974
5143
  );
3975
5144
  guardedCount++;
3976
5145
  if (hotExemptNodes) {
@@ -3989,9 +5158,21 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
3989
5158
  ArrowFunctionExpression: maybeInjectGuard
3990
5159
  });
3991
5160
  if (guardedCount > 0 && Array.isArray(ast.body)) {
3992
- const sharedDecoyDecl = createSharedDecoyDeclaration(decoyIdent, guardedCount);
5161
+ const sharedDecoyDecl = createSharedDecoyDeclaration(
5162
+ decoyIdent,
5163
+ guardedCount,
5164
+ seed
5165
+ );
5166
+ const sboxAliasDecl = createSboxAndAliasDeclarations(
5167
+ sboxIdent,
5168
+ aliasIdentA,
5169
+ aliasIdentB,
5170
+ scratchVarIdent,
5171
+ seed
5172
+ );
3993
5173
  if (hotExemptNodes) {
3994
5174
  hotExemptNodes.add(sharedDecoyDecl);
5175
+ hotExemptNodes.add(sboxAliasDecl);
3995
5176
  for (const decl of sharedDecoyDecl.declarations || []) {
3996
5177
  if (decl.init?.type === "ArrayExpression" && decl.init.elements) {
3997
5178
  for (const el of decl.init.elements) {
@@ -4001,16 +5182,22 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
4001
5182
  }
4002
5183
  }
4003
5184
  let insertIdx = 0;
4004
- while (insertIdx < ast.body.length && ast.body[insertIdx].type === "ExpressionStatement" && ast.body[insertIdx].directive) {
4005
- insertIdx++;
5185
+ while (insertIdx < ast.body.length) {
5186
+ const stmt = ast.body[insertIdx];
5187
+ const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim()));
5188
+ if (isDirective || stmt.type === "ImportDeclaration") {
5189
+ insertIdx++;
5190
+ } else {
5191
+ break;
5192
+ }
4006
5193
  }
4007
- ast.body.splice(insertIdx, 0, sharedDecoyDecl);
5194
+ ast.body.splice(insertIdx, 0, sboxAliasDecl, sharedDecoyDecl);
4008
5195
  }
4009
5196
  return guardedCount;
4010
5197
  }
4011
5198
 
4012
5199
  // src/ast/micro-vm.ts
4013
- import * as acorn5 from "acorn";
5200
+ import * as acorn6 from "acorn";
4014
5201
  import * as walk7 from "acorn-walk";
4015
5202
  var OP_LDC = 0;
4016
5203
  var OP_LDV = 1;
@@ -4038,7 +5225,24 @@ var OP_OBJ = 22;
4038
5225
  var OP_ARR = 23;
4039
5226
  var OP_LDU = 24;
4040
5227
  var OP_STU = 25;
4041
- var OPCODE_COUNT = 26;
5228
+ var OP_DIV = 26;
5229
+ var OP_MOD = 27;
5230
+ var OP_SHL = 28;
5231
+ var OP_SHR = 29;
5232
+ var OP_USHR = 30;
5233
+ var OP_POW = 31;
5234
+ var OP_EQ = 32;
5235
+ var OP_TYPEOF = 33;
5236
+ var OP_IN = 34;
5237
+ var OP_INSTOF = 35;
5238
+ var OP_NEW = 36;
5239
+ var OP_THIS = 37;
5240
+ var OP_POP = 38;
5241
+ var OP_TRY = 39;
5242
+ var OP_ENDTRY = 40;
5243
+ var OP_NULLISH = 41;
5244
+ var OP_DUP = 42;
5245
+ var OPCODE_COUNT = 43;
4042
5246
  function shuffleRange(n, seed) {
4043
5247
  const arr = [];
4044
5248
  for (let i = 0; i < n; i++) arr.push(i);
@@ -4060,25 +5264,42 @@ function shuffleRange(n, seed) {
4060
5264
  function deriveVmKey(seed) {
4061
5265
  return computeFnv1aHash("vm-key", seed) | 0;
4062
5266
  }
4063
- function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots) {
5267
+ function mixOpSeed(seed, salt) {
5268
+ let h = (seed ^ Math.imul(salt + 1, 2654435769)) >>> 0;
5269
+ h ^= h >>> 16;
5270
+ h = Math.imul(h, 2246822507) >>> 0;
5271
+ h ^= h >>> 13;
5272
+ return h | 0;
5273
+ }
5274
+ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlots) {
4064
5275
  const len = plainBytecode.length;
4065
5276
  const enc = new Array(len);
4066
5277
  const stateBefore = new Array(len + 1);
5278
+ const accBefore = new Array(len + 1);
4067
5279
  const stAtSlot = /* @__PURE__ */ new Map();
5280
+ const acAtSlot = /* @__PURE__ */ new Map();
4068
5281
  let st = vmKey ^ fnSalt | 0;
5282
+ let ac = vmKey ^ fnSalt << 5 ^ 1367130551 | 0;
4069
5283
  for (let p = 0; p < len; p++) {
4070
5284
  stateBefore[p] = st;
5285
+ accBefore[p] = ac;
4071
5286
  if (stateSlots && stateSlots.has(p)) {
4072
5287
  stAtSlot.set(p, st);
4073
5288
  enc[p] = 0;
5289
+ } else if (accSlots && accSlots.has(p)) {
5290
+ acAtSlot.set(p, ac);
5291
+ enc[p] = 0;
4074
5292
  } else {
4075
- st = Math.imul(st ^ p + 1, 73244475) + 2654435769 | 0;
4076
- const raw = plainBytecode[p] ^ st >>> 16 & 65535;
5293
+ st = Math.imul(st ^ p + 1, 73244475) + ((ac | 2654435769) + (ac & 2654435769)) | 0;
5294
+ const plainWord = plainBytecode[p];
5295
+ const raw = plainWord ^ st >>> 16 & 65535;
4077
5296
  enc[p] = raw;
4078
5297
  st = st ^ Math.imul(raw + 1, 2246822507) | 0;
5298
+ ac = Math.imul(ac ^ plainWord, 668265261) ^ (st >>> 13 | st << 19) | 0;
4079
5299
  }
4080
5300
  }
4081
5301
  stateBefore[len] = st;
5302
+ accBefore[len] = ac;
4082
5303
  if (stateSlots) {
4083
5304
  for (const slot of stateSlots) {
4084
5305
  const targetPc = plainBytecode[slot - 1];
@@ -4086,6 +5307,13 @@ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots) {
4086
5307
  enc[slot] = stateBefore[targetPc] ^ sBefore | 0;
4087
5308
  }
4088
5309
  }
5310
+ if (accSlots) {
5311
+ for (const slot of accSlots) {
5312
+ const targetPc = plainBytecode[slot - 2];
5313
+ const aBefore = acAtSlot.get(slot) ?? 0;
5314
+ enc[slot] = accBefore[targetPc] ^ aBefore | 0;
5315
+ }
5316
+ }
4089
5317
  return enc;
4090
5318
  }
4091
5319
  function generateOpcodeMap(seed, count = OPCODE_COUNT) {
@@ -4106,6 +5334,35 @@ function generateOpcodeMap(seed, count = OPCODE_COUNT) {
4106
5334
  }
4107
5335
  return pool.slice(0, count);
4108
5336
  }
5337
+ function makeHandlerMbaZeroExpr(seed, op) {
5338
+ const variant = Math.abs(mixOpSeed(seed, op * 11 + 3)) % 4;
5339
+ const c1 = mixOpSeed(seed, op * 11 + 5);
5340
+ const c2 = mixOpSeed(seed, op * 11 + 7);
5341
+ if (variant === 0) {
5342
+ const cSum = c1 + c2 | 0;
5343
+ return `(((((($f.ac|${c1})+($f.ac&${c1}))|0)|((($f.p^${c2})+(($f.p&${c2})<<1))|0))+((((($f.ac|${c1})+($f.ac&${c1}))|0)&((($f.p^${c2})+(($f.p&${c2})<<1))|0))))-(((((($f.ac^$f.p)+(($f.ac&$f.p)<<1))|0)|${cSum})+((((($f.ac^$f.p)+(($f.ac&$f.p)<<1))|0)&${cSum})))|0))|0`;
5344
+ }
5345
+ if (variant === 1) {
5346
+ const cSum = c1 + c2 | 0;
5347
+ return `((((($f.ac|$f.p)<<1)-($f.ac^$f.p))+${cSum})-((($f.ac^${c1})+(($f.ac&${c1})<<1))+(($f.p|${c2})+($f.p&${c2}))))|0`;
5348
+ }
5349
+ if (variant === 2) {
5350
+ const cFold = 1 - c1 - c2 | 0;
5351
+ return `(((~$f.ac|${c1})+(~$f.ac&${c1}))+(($f.ac|${c2})+($f.ac&${c2}))+${cFold})|0`;
5352
+ }
5353
+ return `((($f.ac|$f.p)-(~$f.ac&$f.p))^((($f.ac&${c1})+($f.ac&~${c1}))))|0`;
5354
+ }
5355
+ function wrapHandlerWithMba(seed, op, coreBody, isTerminal = false) {
5356
+ const zExpr = makeHandlerMbaZeroExpr(seed, op);
5357
+ const shape = Math.abs(mixOpSeed(seed, op * 17 + 1)) % 3;
5358
+ const zVar = shape === 0 ? "$z0" : shape === 1 ? "$m0" : "$k0";
5359
+ const tail = isTerminal ? "return void 0;" : shape === 0 ? "return $step($f);" : shape === 1 ? "var $nx=$step($f);return $nx;" : "return $f.d?void 0:$step($f);";
5360
+ const adjustedBody = coreBody.replace(/\$Z/g, zVar);
5361
+ if (coreBody.includes("$Z")) {
5362
+ return `function($f){var ${zVar}=${zExpr};${adjustedBody}${tail}}`;
5363
+ }
5364
+ return `function($f){var ${zVar}=${zExpr};$f.r=($f.r+${zVar})|0;${adjustedBody}${tail}}`;
5365
+ }
4109
5366
  function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta) {
4110
5367
  const opCount = opMap.length;
4111
5368
  const slotMap = shuffleRange(opCount, (seed ^ 1367130551) >>> 0);
@@ -4117,85 +5374,126 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
4117
5374
  for (const op of pairOrder) {
4118
5375
  pairs.push(opMap[op] ^ opMask, slotMap[op] ^ slotMask);
4119
5376
  }
4120
- const handlerMap = {
4121
- [OP_LDC]: "function($f){$f.q[$f.r++]=$f.k[$rd($f)];}",
4122
- [OP_LDV]: "function($f){$f.q[$f.r++]=$f.s[$rd($f)];}",
4123
- [OP_STV]: "function($f){$f.s[$rd($f)]=$f.q[--$f.r];}",
4124
- [OP_LDG]: "function($f){$f.q[$f.r++]=$G[$f.k[$rd($f)]];}",
4125
- [OP_GETP]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b];}",
4126
- [OP_SETP]: "function($f){var $v=$f.q[--$f.r],$b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=($a[$b]=$v);}",
4127
- [OP_CALL]: "function($f){var $n=$rd($f),$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=$fn.apply(void 0,$g);}",
4128
- [OP_MCALL]: "function($f){var $n=$rd($f),$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b].apply($a,$g);}",
4129
- [OP_ADD]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a+$b;}",
4130
- [OP_SUB]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a-$b;}",
4131
- [OP_MUL]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a*$b;}",
4132
- [OP_XOR]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a^$b;}",
4133
- [OP_AND]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a&$b;}",
4134
- [OP_OR]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a|$b;}",
4135
- [OP_SEQ]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a===$b;}",
4136
- [OP_LT]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a<$b;}",
4137
- [OP_NOT]: "function($f){$f.q[$f.r-1]=!$f.q[$f.r-1];}",
4138
- [OP_JMP]: "function($f){var $j=$rd($f),$ts=$f.c[$f.p++]^$f.st;$f.p=$j;$f.st=$ts;}",
4139
- [OP_JZ]: "function($f){var $j=$rd($f),$ts=$f.c[$f.p++]^$f.st;if(!$f.q[--$f.r]){$f.p=$j;$f.st=$ts;}}",
4140
- [OP_RET]: "function($f){$f.d=1;$f.v=$f.q[--$f.r];}",
4141
- [OP_THROW]: "function($f){throw $f.q[--$f.r];}",
4142
- [OP_AWAIT]: "function($f){var $v=$f.q[--$f.r];$f.d=2;$f.v=Promise.resolve($v).then(function($w){$f.d=0;$f.q[$f.r++]=$w;return $x($f);});}",
4143
- [OP_OBJ]: "function($f){var $n=$rd($f),$o={},$e=[];for(var $i=0;$i<$n;$i++){var $v=$f.q[--$f.r],$k0=$f.q[--$f.r];$e.push([$k0,$v]);}for(var $i=$e.length-1;$i>=0;$i--){$o[$e[$i][0]]=$e[$i][1];}$f.q[$f.r++]=$o;}",
4144
- [OP_ARR]: "function($f){var $n=$rd($f),$a=[];for(var $i=$n-1;$i>=0;$i--)$a[$i]=$f.q[--$f.r];$f.q[$f.r++]=$a;}",
4145
- [OP_LDU]: "function($f){$f.q[$f.r++]=$f.u[$rd($f)][0]();}",
4146
- [OP_STU]: "function($f){$f.u[$rd($f)][1]($f.q[--$f.r]);}"
5377
+ const xorImpl = Math.abs(mixOpSeed(seed, OP_XOR)) % 2 === 0 ? "($a|$b)-($a&$b)" : "$a^$b";
5378
+ const andImpl = Math.abs(mixOpSeed(seed, OP_AND)) % 2 === 0 ? "~(~$a|~$b)" : "$a&$b";
5379
+ const orImpl = Math.abs(mixOpSeed(seed, OP_OR)) % 2 === 0 ? "(($a^$b)+($a&$b))|0" : "$a|$b";
5380
+ const coreHandlers = {
5381
+ [OP_LDC]: { body: "$f.q[($f.r++)+$Z]=$f.k[$rd($f)];" },
5382
+ [OP_LDV]: { body: "$f.q[($f.r++)+$Z]=$f.s[$rd($f)];" },
5383
+ [OP_STV]: { body: "$f.s[$rd($f)]=$f.q[(--$f.r)+$Z];" },
5384
+ [OP_LDG]: { body: "$f.q[($f.r++)+$Z]=$G[$f.k[$rd($f)]];" },
5385
+ [OP_GETP]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a[$b];" },
5386
+ [OP_SETP]: { body: "var $v=$f.q[--$f.r],$b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=($a[$b]=$v);" },
5387
+ [OP_CALL]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=$fn.apply(void 0,$g);" },
5388
+ [OP_MCALL]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b].apply($a,$g);" },
5389
+ [OP_ADD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a+$b;" },
5390
+ [OP_SUB]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a-$b;" },
5391
+ [OP_MUL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a*$b;" },
5392
+ [OP_XOR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${xorImpl};` },
5393
+ [OP_AND]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${andImpl};` },
5394
+ [OP_OR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${orImpl};` },
5395
+ [OP_SEQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a===$b;" },
5396
+ [OP_LT]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<$b;" },
5397
+ [OP_NOT]: { body: "$f.q[($f.r-1)+$Z]=!$f.q[$f.r-1];" },
5398
+ [OP_JMP]: { body: "var $j=$rd($f)+$Z,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;$f.p=$j;$f.st=$ts;$f.ac=$ta;" },
5399
+ [OP_JZ]: { body: "var $j=$rd($f)+$Z,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;if(!$f.q[--$f.r]){$f.p=$j;$f.st=$ts;$f.ac=$ta;}" },
5400
+ [OP_RET]: { body: "$f.d=1;$f.v=$f.q[(--$f.r)+$Z];", terminal: true },
5401
+ [OP_THROW]: { body: "throw $f.q[(--$f.r)+$Z];" },
5402
+ [OP_AWAIT]: {
5403
+ body: "var $v=$f.q[(--$f.r)+$Z];$f.d=2;$f.v=Promise.resolve($v).then(function($w){$f.d=0;$f.q[$f.r++]=$w;return $x($f);},function($e){if($f.e.length>0){var $ex=$f.e.pop();$f.d=0;$f.r=$ex.r;$f.q[$f.r++]=$e;$f.p=$ex.p;$f.st=$ex.s;$f.ac=$ex.a;return $x($f);}throw $e;});",
5404
+ terminal: true
5405
+ },
5406
+ [OP_OBJ]: { body: "var $n=$rd($f)+$Z,$o={},$e=[];for(var $i=0;$i<$n;$i++){var $v=$f.q[--$f.r],$k0=$f.q[--$f.r];$e.push([$k0,$v]);}for(var $i=$e.length-1;$i>=0;$i--){$o[$e[$i][0]]=$e[$i][1];}$f.q[$f.r++]=$o;" },
5407
+ [OP_ARR]: { body: "var $n=$rd($f)+$Z,$a=[];for(var $i=$n-1;$i>=0;$i--)$a[$i]=$f.q[--$f.r];$f.q[$f.r++]=$a;" },
5408
+ [OP_LDU]: { body: "$f.q[($f.r++)+$Z]=$f.u[$rd($f)][0]();" },
5409
+ [OP_STU]: { body: "$f.u[$rd($f)][1]($f.q[(--$f.r)+$Z]);" },
5410
+ [OP_DIV]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a/$b;" },
5411
+ [OP_MOD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a%$b;" },
5412
+ [OP_SHL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<<$b;" },
5413
+ [OP_SHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>$b;" },
5414
+ [OP_USHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>>$b;" },
5415
+ [OP_POW]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a**$b;" },
5416
+ [OP_EQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a==$b;" },
5417
+ [OP_TYPEOF]: { body: "$f.q[($f.r-1)+$Z]=typeof $f.q[$f.r-1];" },
5418
+ [OP_IN]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a in $b;" },
5419
+ [OP_INSTOF]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a instanceof $b;" },
5420
+ [OP_NEW]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=new $fn(...$g);" },
5421
+ [OP_THIS]: { body: "$f.q[($f.r++)+$Z]=$f.t;" },
5422
+ [OP_POP]: { body: "--$f.r;$f.r+=$Z;" },
5423
+ [OP_TRY]: { body: "var $cp=$rd($f)+$Z,$cs=$f.c[$f.p++]^$f.st,$ca=$f.c[$f.p++]^$f.ac;$f.e.push({p:$cp,r:$f.r,s:$cs,a:$ca});" },
5424
+ [OP_ENDTRY]: { body: "$f.e.pop();$f.r+=$Z;" },
5425
+ [OP_NULLISH]: { body: "var $v=$f.q[($f.r-1)+$Z];$f.q[$f.r-1]=($v===null||$v===void 0);" },
5426
+ [OP_DUP]: { body: "var $top=$f.q[($f.r-1)+$Z];$f.q[$f.r++]=$top;" }
4147
5427
  };
4148
5428
  const handlers = new Array(opCount);
4149
5429
  for (let op = 0; op < opCount; op++) {
4150
- handlers[slotMap[op]] = handlerMap[op];
5430
+ const spec = coreHandlers[op];
5431
+ handlers[slotMap[op]] = wrapHandlerWithMba(seed, op, spec.body, Boolean(spec.terminal));
4151
5432
  }
4152
5433
  const hasSym = Boolean(windowKeySymbol && expectedDelta !== void 0);
4153
5434
  const symPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]` : "";
4154
- const dDecl = hasSym ? `var $d=$G${symPropAccess}!=null?$G${symPropAccess}:($W?-1:(($h^$D)&0xffff));` : "";
4155
- const okExpr = hasSym ? `(($h&255)^$A^($d&255))&255` : `(($h&255)^$A)&255`;
4156
- const skExpr = hasSym ? `((($h>>>8)&255)^$B^(($d>>>8)&255))&255` : `((($h>>>8)&255)^$B)&255`;
4157
- const vkExpr = hasSym ? `($h^$C^Math.imul($d|0,0x9e3779b1))|0` : `($h^$C)|0`;
4158
- const paramsList = hasSym ? "$P,$A,$B,$C,$D" : "$P,$A,$B,$C";
4159
- const factoryRaw = `(function $I(${paramsList}){var $G=typeof globalThis<"u"?globalThis:(typeof window<"u"?window:this);${hasSym ? 'var $W=typeof window<"u"||typeof self<"u";' : ""}var $ts=Function.prototype.toString,$s=$ts.call($I);for(var $h=0x811c9dc5,$i=0;$i<$s.length;$i++)$h=Math.imul($h^$s.charCodeAt($i),0x01000193)>>>0;try{$ts.call(0);$h^=1;}catch($e){}var $M,$ok,$sk,$vk,$in=0;function $init(){$in=1;${dDecl}$ok=${okExpr};$sk=${skExpr};$vk=${vkExpr};$M=[];for(var $j=0;$j<$P.length;$j+=2)$M[$P[$j]]=$P[$j+1];}function $rd($f){var $p=$f.p++;var $x0=$f.st=(Math.imul($f.st^($p+1),0x45d9f3b)+0x9e3779b9)|0;var $w=$f.c[$p],$v=$w^(($x0>>>16)&0xffff);$f.st=($f.st^Math.imul($w+1,0x85ebca6b))|0;return $v;}var $H;function $x($f){while($f.p<$f.c.length){var $o=$rd($f),$m=$M[$o^$ok];if($m!==void 0){var $h0=$H[$m^$sk];if($h0)$h0($f);}if($f.d)return $f.v;}}$H=[${handlers.join(
5435
+ const symTamperPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(`${windowKeySymbol}_t`) ? `.${windowKeySymbol}_t` : `[${JSON.stringify(`${windowKeySymbol}_t`)}]` : "";
5436
+ const expD = hasSym ? expectedDelta & 65535 : 0;
5437
+ const seed32 = seed | 0;
5438
+ const expDigest = hasSym ? Math.imul(expD ^ seed32 | 0, 2654435761) ^ (expD << 16 | seed32 >>> 16) ^ 2246822507 | 0 : 0;
5439
+ const tamperCheckExpr = hasSym ? `var $bad=$G[$tk]===!0||$G${symTamperPropAccess}===!0,$sv=$G${symPropAccess};if(!$bad&&$sv!==void 0){if(Array.isArray($sv)){if($sv[0]===2)$bad=true;}else{var $sh=(Math.imul(($sv^$S)|0,0x9e3779b1)^(($sv<<16)|($S>>>16))^0x85ebca6b)|0;if($sh!==$D)$bad=true;}}` : `var $bad=$G[$tk]===!0;`;
5440
+ const paramsList = hasSym ? "$P,$A,$B,$C,$S,$D" : "$P,$A,$B,$C,$S";
5441
+ const factoryRaw = `(function $I(${paramsList}){var $G=typeof globalThis<"u"?globalThis:(typeof window<"u"?window:this);var $tk=['__','unp','eek','_ta','mpe','red'].join('');var $M=[],$ok=$A&255,$sk=$B&255,$vk=$C|0;for(var $j=0;$j<$P.length;$j+=2)$M[$P[$j]]=$P[$j+1];function $rd($f){var $p=$f.p++;var $x0=$f.st=(Math.imul($f.st^($p+1),0x45d9f3b)+(($f.ac|0x9e3779b9)+($f.ac&0x9e3779b9)))|0;var $w=$f.c[$p],$v=$w^(($x0>>>16)&0xffff);$f.st=($f.st^Math.imul($w+1,0x85ebca6b))|0;$f.ac=(Math.imul($f.ac^$v,0x27d4eb2d)^(($f.st>>>13)|($f.st<<19)))|0;return $v;}var $H=[${handlers.join(
4160
5442
  ","
4161
- )}];return function($c,$k,$s0,$t,$a,$u){if(!$in)$init();return $x({c:$c,k:$k,s:$s0,t:$t,u:$u||[],q:[],r:0,p:0,st:($vk^$a)|0,d:0,v:void 0});};})`;
4162
- const parsedFactory = acorn5.parse(factoryRaw, {
5443
+ )}];function $step($f){if($f.d||$f.p>=$f.c.length)return void 0;var $o=$rd($f),$m=$M[$o^$ok];return $m!==void 0?$H[$m^$sk]:void 0;}function $x($f){var $fn=$step($f);while($fn!==void 0){try{$fn=$fn($f);}catch($err){if($f.e.length>0){var $ex=$f.e.pop();$f.r=$ex.r;$f.q[$f.r++]=$err;$f.p=$ex.p;$f.st=$ex.s;$f.ac=$ex.a;$fn=$step($f);}else{throw $err;}}}return $f.v;}return function($c,$k,$s0,$t,$a,$u){${tamperCheckExpr}var $flt=$bad?(Math.imul($vk^$a,0x45d9f3b)|1):0;return $x({c:$c,k:$k,s:$s0,t:$t,u:$u||[],q:[],r:0,p:0,st:($vk^$a^$flt)|0,ac:($vk^($a<<5)^0x517cc1b7^$flt)|0,e:[],d:0,v:void 0});};})`;
5444
+ const parsedFactory = acorn6.parse(factoryRaw, {
4163
5445
  ecmaVersion: "latest",
4164
5446
  sourceType: "script"
4165
5447
  });
4166
- const factoryExpr = parsedFactory.body[0].expression;
4167
- const compactFactory = generateCompactJs(factoryExpr);
4168
- const buildH = computeFnv1aHash(compactFactory);
4169
- const expD = hasSym ? expectedDelta & 65535 : 0;
4170
- const argA = (opMask ^ buildH & 255 ^ expD & 255) & 255;
4171
- const argB = (slotMask ^ buildH >>> 8 & 255 ^ expD >>> 8 & 255) & 255;
4172
- const argC = vmKey ^ buildH ^ (hasSym ? Math.imul(expD | 0, 2654435761) : 0) | 0;
4173
- const argD = hasSym ? (buildH ^ expD) & 65535 : 0;
4174
- return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC}${hasSym ? `,${argD}` : ""});`;
5448
+ const compactFactory = generateCompactJs(parsedFactory.body[0].expression);
5449
+ const argA = opMask & 255;
5450
+ const argB = slotMask & 255;
5451
+ const argC = vmKey | 0;
5452
+ return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC},${seed32}${hasSym ? `,${expDigest}` : ""});`;
5453
+ }
5454
+ function walkWithParent(node, parent, visitor) {
5455
+ if (!node || typeof node !== "object") return;
5456
+ if (Array.isArray(node)) {
5457
+ for (const item of node) {
5458
+ walkWithParent(item, parent, visitor);
5459
+ }
5460
+ return;
5461
+ }
5462
+ if (typeof node.type !== "string") return;
5463
+ if (visitor(node, parent) === false) return;
5464
+ for (const key of Object.keys(node)) {
5465
+ if (key === "loc" || key === "range" || key === "start" || key === "end") continue;
5466
+ const child = node[key];
5467
+ if (child && typeof child === "object") {
5468
+ walkWithParent(child, node, visitor);
5469
+ }
5470
+ }
4175
5471
  }
4176
5472
  function countAstNodes(node) {
4177
5473
  let count = 0;
4178
- walk7.full(node, () => {
5474
+ walkWithParent(node, null, () => {
4179
5475
  count++;
4180
5476
  });
4181
5477
  return count;
4182
5478
  }
4183
5479
  function hasForbiddenConstructs(fnNode) {
4184
5480
  let forbidden = false;
4185
- walk7.full(fnNode, (node) => {
4186
- if (forbidden) return;
5481
+ walkWithParent(fnNode, null, (node, parent) => {
5482
+ if (forbidden) return false;
4187
5483
  const type = node.type;
4188
- if (type === "JSXElement" || type === "JSXFragment" || type === "Super" || type === "YieldExpression" || type === "WithStatement") {
5484
+ if (type === "JSXElement" || type === "JSXFragment" || type === "Super" || type === "YieldExpression" || type === "WithStatement" || type === "MetaProperty") {
4189
5485
  forbidden = true;
4190
- return;
5486
+ return false;
4191
5487
  }
4192
5488
  if (type === "Identifier" && (node.name === "arguments" || node.name === "eval")) {
5489
+ if (parent && parent.type === "MemberExpression" && parent.computed === false && parent.property === node) {
5490
+ return;
5491
+ }
5492
+ if (parent && parent.type === "Property" && parent.computed === false && parent.key === node && !parent.shorthand) {
5493
+ return;
5494
+ }
4193
5495
  forbidden = true;
4194
- return;
4195
- }
4196
- if (type === "MetaProperty") {
4197
- forbidden = true;
4198
- return;
5496
+ return false;
4199
5497
  }
4200
5498
  });
4201
5499
  return forbidden;
@@ -4247,20 +5545,140 @@ function collectPatternNames(pattern, out) {
4247
5545
  break;
4248
5546
  }
4249
5547
  }
5548
+ function hasAbruptControlFlow(node) {
5549
+ let abrupt = false;
5550
+ walkWithParent(node, null, (n) => {
5551
+ if (abrupt) return false;
5552
+ if (n !== node && FUNCTION_NODE_TYPES2.has(n.type)) return false;
5553
+ if (n.type === "ReturnStatement" || n.type === "BreakStatement" || n.type === "ContinueStatement") {
5554
+ abrupt = true;
5555
+ return false;
5556
+ }
5557
+ });
5558
+ return abrupt;
5559
+ }
5560
+ function prepareLoweredFunction(fnNode, enclosingBindings) {
5561
+ const clone = JSON.parse(JSON.stringify(fnNode));
5562
+ const usedNames = new Set(enclosingBindings ?? []);
5563
+ for (const p of clone.params || []) {
5564
+ collectPatternNames(p, usedNames);
5565
+ }
5566
+ let synthCounter = 0;
5567
+ function freshParamName() {
5568
+ let candidate = `_vp${synthCounter++}`;
5569
+ while (usedNames.has(candidate)) {
5570
+ candidate = `_vp${synthCounter++}`;
5571
+ }
5572
+ usedNames.add(candidate);
5573
+ return candidate;
5574
+ }
5575
+ const wrapperParams = [];
5576
+ const paramPassExprs = [];
5577
+ const loweredParams = [];
5578
+ const preludeDecls = [];
5579
+ for (const param of fnNode.params || []) {
5580
+ if (param.type === "Identifier") {
5581
+ wrapperParams.push(param);
5582
+ paramPassExprs.push({ type: "Identifier", name: param.name });
5583
+ loweredParams.push({ type: "Identifier", name: param.name });
5584
+ continue;
5585
+ }
5586
+ if (param.type === "RestElement" && param.argument?.type === "Identifier") {
5587
+ wrapperParams.push(param);
5588
+ paramPassExprs.push({ type: "Identifier", name: param.argument.name });
5589
+ loweredParams.push({ type: "Identifier", name: param.argument.name });
5590
+ continue;
5591
+ }
5592
+ if (param.type === "AssignmentPattern" || param.type === "ObjectPattern" || param.type === "ArrayPattern") {
5593
+ const synthName = freshParamName();
5594
+ const synthIdent = { type: "Identifier", name: synthName };
5595
+ wrapperParams.push(synthIdent);
5596
+ paramPassExprs.push(synthIdent);
5597
+ loweredParams.push(synthIdent);
5598
+ const paramClone = JSON.parse(JSON.stringify(param));
5599
+ if (paramClone.type === "AssignmentPattern") {
5600
+ const initExpr = {
5601
+ type: "ConditionalExpression",
5602
+ test: {
5603
+ type: "BinaryExpression",
5604
+ operator: "===",
5605
+ left: { type: "Identifier", name: synthName },
5606
+ right: {
5607
+ type: "UnaryExpression",
5608
+ operator: "void",
5609
+ prefix: true,
5610
+ argument: { type: "Literal", value: 0, raw: "0" }
5611
+ }
5612
+ },
5613
+ consequent: paramClone.right,
5614
+ alternate: { type: "Identifier", name: synthName }
5615
+ };
5616
+ preludeDecls.push({
5617
+ type: "VariableDeclaration",
5618
+ kind: "var",
5619
+ declarations: [
5620
+ {
5621
+ type: "VariableDeclarator",
5622
+ id: paramClone.left,
5623
+ init: initExpr
5624
+ }
5625
+ ]
5626
+ });
5627
+ } else {
5628
+ preludeDecls.push({
5629
+ type: "VariableDeclaration",
5630
+ kind: "var",
5631
+ declarations: [
5632
+ {
5633
+ type: "VariableDeclarator",
5634
+ id: paramClone,
5635
+ init: { type: "Identifier", name: synthName }
5636
+ }
5637
+ ]
5638
+ });
5639
+ }
5640
+ continue;
5641
+ }
5642
+ return null;
5643
+ }
5644
+ clone.params = loweredParams;
5645
+ if (clone.body?.type !== "BlockStatement") {
5646
+ clone.body = {
5647
+ type: "BlockStatement",
5648
+ body: [
5649
+ {
5650
+ type: "ReturnStatement",
5651
+ argument: clone.body
5652
+ }
5653
+ ]
5654
+ };
5655
+ clone.expression = false;
5656
+ }
5657
+ if (preludeDecls.length > 0) {
5658
+ clone.body.body = [...preludeDecls, ...clone.body.body || []];
5659
+ }
5660
+ return { loweredFn: clone, wrapperParams, paramPassExprs };
5661
+ }
4250
5662
  function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4251
5663
  const bytecode = [];
4252
5664
  const consts = [];
4253
5665
  const stateSlots = /* @__PURE__ */ new Set();
5666
+ const accSlots = /* @__PURE__ */ new Set();
4254
5667
  const fnScope = /* @__PURE__ */ new Map();
4255
5668
  const scopeStack = [fnScope];
4256
5669
  const upvalues = [];
4257
5670
  const upvalueMap = /* @__PURE__ */ new Map();
4258
5671
  let localCount = 0;
5672
+ let tryDepth = 0;
5673
+ const loopStack = [];
4259
5674
  for (const param of fnNode.params) {
4260
5675
  if (param.type !== "Identifier") return null;
4261
5676
  if (fnScope.has(param.name)) return null;
4262
5677
  fnScope.set(param.name, localCount++);
4263
5678
  }
5679
+ function allocTempSlot() {
5680
+ return localCount++;
5681
+ }
4264
5682
  let invalidDecl = false;
4265
5683
  function scanVarDecls(node, isTopBody) {
4266
5684
  if (!node || invalidDecl) return;
@@ -4273,13 +5691,13 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4273
5691
  if (node.type === "VariableDeclaration") {
4274
5692
  const isVar = node.kind === "var";
4275
5693
  if (isVar || isTopBody) {
5694
+ const names = /* @__PURE__ */ new Set();
4276
5695
  for (const decl of node.declarations || []) {
4277
- if (decl.id?.type !== "Identifier") {
4278
- invalidDecl = true;
4279
- return;
4280
- }
4281
- if (!fnScope.has(decl.id.name)) {
4282
- fnScope.set(decl.id.name, localCount++);
5696
+ collectPatternNames(decl.id, names);
5697
+ }
5698
+ for (const name of names) {
5699
+ if (!fnScope.has(name)) {
5700
+ fnScope.set(name, localCount++);
4283
5701
  }
4284
5702
  }
4285
5703
  }
@@ -4294,6 +5712,21 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4294
5712
  if (node.type === "IfStatement") {
4295
5713
  scanVarDecls(node.consequent, false);
4296
5714
  if (node.alternate) scanVarDecls(node.alternate, false);
5715
+ return;
5716
+ }
5717
+ if (node.type === "ForStatement" || node.type === "WhileStatement" || node.type === "DoWhileStatement") {
5718
+ if (node.init) scanVarDecls(node.init, false);
5719
+ scanVarDecls(node.body, false);
5720
+ return;
5721
+ }
5722
+ if (node.type === "TryStatement") {
5723
+ scanVarDecls(node.block, false);
5724
+ if (node.handler?.body) scanVarDecls(node.handler.body, false);
5725
+ if (node.finalizer) scanVarDecls(node.finalizer, false);
5726
+ return;
5727
+ }
5728
+ if (node.type === "LabeledStatement") {
5729
+ scanVarDecls(node.body, false);
4297
5730
  }
4298
5731
  }
4299
5732
  if (fnNode.body.type === "BlockStatement") {
@@ -4361,16 +5794,169 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4361
5794
  bytecode.push(opMap[op]);
4362
5795
  for (const a of args) bytecode.push(a);
4363
5796
  }
5797
+ function emitJumpPlaceholder(op) {
5798
+ const pos = bytecode.length;
5799
+ emit(op, 0, 0, 0);
5800
+ stateSlots.add(pos + 2);
5801
+ accSlots.add(pos + 3);
5802
+ return pos;
5803
+ }
5804
+ function patchJump(pos, targetPc) {
5805
+ bytecode[pos + 1] = targetPc;
5806
+ }
5807
+ function compilePatternAssignFromSlot(pattern, sourceSlot) {
5808
+ if (!pattern) return false;
5809
+ switch (pattern.type) {
5810
+ case "Identifier": {
5811
+ const slot = resolveLocal(pattern.name);
5812
+ if (slot !== void 0) {
5813
+ emit(OP_LDV, sourceSlot);
5814
+ emit(OP_STV, slot);
5815
+ return true;
5816
+ }
5817
+ emit(OP_LDV, sourceSlot);
5818
+ return emitStoreVar(pattern.name);
5819
+ }
5820
+ case "AssignmentPattern": {
5821
+ const valSlot = allocTempSlot();
5822
+ emit(OP_LDV, sourceSlot);
5823
+ emit(OP_LDC, addConst(void 0));
5824
+ emit(OP_SEQ);
5825
+ const jzPos = emitJumpPlaceholder(OP_JZ);
5826
+ if (!compileExpr(pattern.right, true)) return false;
5827
+ emit(OP_STV, valSlot);
5828
+ const jmpEnd = emitJumpPlaceholder(OP_JMP);
5829
+ patchJump(jzPos, bytecode.length);
5830
+ emit(OP_LDV, sourceSlot);
5831
+ emit(OP_STV, valSlot);
5832
+ patchJump(jmpEnd, bytecode.length);
5833
+ return compilePatternAssignFromSlot(pattern.left, valSlot);
5834
+ }
5835
+ case "ObjectPattern": {
5836
+ for (const prop of pattern.properties || []) {
5837
+ if (prop.type !== "Property") return false;
5838
+ emit(OP_LDV, sourceSlot);
5839
+ if (prop.computed) {
5840
+ if (!compileExpr(prop.key, true)) return false;
5841
+ } else {
5842
+ const keyName = prop.key?.type === "Identifier" ? prop.key.name : prop.key?.type === "Literal" ? String(prop.key.value) : void 0;
5843
+ if (keyName === void 0) return false;
5844
+ emit(OP_LDC, addConst(keyName));
5845
+ }
5846
+ emit(OP_GETP);
5847
+ const propSlot = allocTempSlot();
5848
+ emit(OP_STV, propSlot);
5849
+ if (!compilePatternAssignFromSlot(prop.value, propSlot)) return false;
5850
+ }
5851
+ return true;
5852
+ }
5853
+ case "ArrayPattern": {
5854
+ const elems = pattern.elements || [];
5855
+ for (let i = 0; i < elems.length; i++) {
5856
+ const el = elems[i];
5857
+ if (!el) continue;
5858
+ if (el.type === "RestElement") {
5859
+ if (i !== elems.length - 1) return false;
5860
+ emit(OP_LDV, sourceSlot);
5861
+ emit(OP_LDC, addConst("slice"));
5862
+ emit(OP_LDC, addConst(i));
5863
+ emit(OP_MCALL, 1);
5864
+ const restSlot = allocTempSlot();
5865
+ emit(OP_STV, restSlot);
5866
+ return compilePatternAssignFromSlot(el.argument, restSlot);
5867
+ }
5868
+ emit(OP_LDV, sourceSlot);
5869
+ emit(OP_LDC, addConst(i));
5870
+ emit(OP_GETP);
5871
+ const elSlot = allocTempSlot();
5872
+ emit(OP_STV, elSlot);
5873
+ if (!compilePatternAssignFromSlot(el, elSlot)) return false;
5874
+ }
5875
+ return true;
5876
+ }
5877
+ default:
5878
+ return false;
5879
+ }
5880
+ }
5881
+ function compileBinaryOp(operator) {
5882
+ switch (operator) {
5883
+ case "+":
5884
+ emit(OP_ADD);
5885
+ return true;
5886
+ case "-":
5887
+ emit(OP_SUB);
5888
+ return true;
5889
+ case "*":
5890
+ emit(OP_MUL);
5891
+ return true;
5892
+ case "/":
5893
+ emit(OP_DIV);
5894
+ return true;
5895
+ case "%":
5896
+ emit(OP_MOD);
5897
+ return true;
5898
+ case "**":
5899
+ emit(OP_POW);
5900
+ return true;
5901
+ case "^":
5902
+ emit(OP_XOR);
5903
+ return true;
5904
+ case "&":
5905
+ emit(OP_AND);
5906
+ return true;
5907
+ case "|":
5908
+ emit(OP_OR);
5909
+ return true;
5910
+ case "<<":
5911
+ emit(OP_SHL);
5912
+ return true;
5913
+ case ">>":
5914
+ emit(OP_SHR);
5915
+ return true;
5916
+ case ">>>":
5917
+ emit(OP_USHR);
5918
+ return true;
5919
+ case "==":
5920
+ emit(OP_EQ);
5921
+ return true;
5922
+ case "===":
5923
+ emit(OP_SEQ);
5924
+ return true;
5925
+ case "!=":
5926
+ emit(OP_EQ);
5927
+ emit(OP_NOT);
5928
+ return true;
5929
+ case "!==":
5930
+ emit(OP_SEQ);
5931
+ emit(OP_NOT);
5932
+ return true;
5933
+ case "<":
5934
+ emit(OP_LT);
5935
+ return true;
5936
+ case "in":
5937
+ emit(OP_IN);
5938
+ return true;
5939
+ case "instanceof":
5940
+ emit(OP_INSTOF);
5941
+ return true;
5942
+ default:
5943
+ return false;
5944
+ }
5945
+ }
4364
5946
  function compileExpr(node, inValuePos = true) {
4365
5947
  if (!node) return false;
4366
5948
  switch (node.type) {
4367
5949
  case "Literal": {
4368
5950
  if (node.regex || typeof node.value === "bigint") return false;
4369
- const idx = addConst(node.value);
4370
- emit(OP_LDC, idx);
5951
+ if (inValuePos) {
5952
+ emit(OP_LDC, addConst(node.value));
5953
+ }
4371
5954
  return true;
4372
5955
  }
4373
5956
  case "Identifier": {
5957
+ if (!inValuePos) {
5958
+ return true;
5959
+ }
4374
5960
  if (node.name === "undefined") {
4375
5961
  const localSlot = resolveLocal("undefined");
4376
5962
  if (localSlot !== void 0) {
@@ -4378,78 +5964,119 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4378
5964
  } else if (enclosingBindings && enclosingBindings.has("undefined")) {
4379
5965
  emit(OP_LDU, getOrCreateUpvalue("undefined", false));
4380
5966
  } else {
4381
- const idx = addConst(void 0);
4382
- emit(OP_LDC, idx);
5967
+ emit(OP_LDC, addConst(void 0));
4383
5968
  }
4384
5969
  return true;
4385
5970
  }
4386
5971
  emitLoadVar(node.name);
4387
5972
  return true;
4388
5973
  }
5974
+ case "ThisExpression": {
5975
+ if (inValuePos) emit(OP_THIS);
5976
+ return true;
5977
+ }
5978
+ case "TemplateLiteral": {
5979
+ const quasis = node.quasis || [];
5980
+ const exprs = node.expressions || [];
5981
+ emit(OP_LDC, addConst(quasis[0]?.value?.cooked ?? quasis[0]?.value?.raw ?? ""));
5982
+ for (let i = 0; i < exprs.length; i++) {
5983
+ if (!compileExpr(exprs[i], true)) return false;
5984
+ emit(OP_ADD);
5985
+ const qStr = quasis[i + 1]?.value?.cooked ?? quasis[i + 1]?.value?.raw ?? "";
5986
+ if (qStr.length > 0) {
5987
+ emit(OP_LDC, addConst(qStr));
5988
+ emit(OP_ADD);
5989
+ }
5990
+ }
5991
+ if (!inValuePos) emit(OP_POP);
5992
+ return true;
5993
+ }
4389
5994
  case "BinaryExpression": {
4390
5995
  if (node.operator === ">") {
4391
5996
  if (!compileExpr(node.right, true)) return false;
4392
5997
  if (!compileExpr(node.left, true)) return false;
4393
5998
  emit(OP_LT);
4394
- return true;
4395
- }
4396
- if (node.operator === "<=") {
5999
+ } else if (node.operator === "<=") {
4397
6000
  if (!compileExpr(node.right, true)) return false;
4398
6001
  if (!compileExpr(node.left, true)) return false;
4399
6002
  emit(OP_LT);
4400
6003
  emit(OP_NOT);
4401
- return true;
4402
- }
4403
- if (node.operator === ">=") {
6004
+ } else if (node.operator === ">=") {
4404
6005
  if (!compileExpr(node.left, true)) return false;
4405
6006
  if (!compileExpr(node.right, true)) return false;
4406
6007
  emit(OP_LT);
4407
6008
  emit(OP_NOT);
4408
- return true;
6009
+ } else {
6010
+ if (!compileExpr(node.left, true)) return false;
6011
+ if (!compileExpr(node.right, true)) return false;
6012
+ if (!compileBinaryOp(node.operator)) return false;
4409
6013
  }
6014
+ if (!inValuePos) emit(OP_POP);
6015
+ return true;
6016
+ }
6017
+ case "LogicalExpression": {
6018
+ const tmpSlot = allocTempSlot();
4410
6019
  if (!compileExpr(node.left, true)) return false;
4411
- if (!compileExpr(node.right, true)) return false;
4412
- switch (node.operator) {
4413
- case "+":
4414
- emit(OP_ADD);
4415
- break;
4416
- case "-":
4417
- emit(OP_SUB);
4418
- break;
4419
- case "*":
4420
- emit(OP_MUL);
4421
- break;
4422
- case "^":
4423
- emit(OP_XOR);
4424
- break;
4425
- case "&":
4426
- emit(OP_AND);
4427
- break;
4428
- case "|":
4429
- emit(OP_OR);
4430
- break;
4431
- case "==":
4432
- case "===":
4433
- emit(OP_SEQ);
4434
- break;
4435
- case "!=":
4436
- case "!==":
4437
- emit(OP_SEQ);
4438
- emit(OP_NOT);
4439
- break;
4440
- case "<":
4441
- emit(OP_LT);
4442
- break;
4443
- default:
4444
- return false;
6020
+ emit(OP_STV, tmpSlot);
6021
+ emit(OP_LDV, tmpSlot);
6022
+ if (node.operator === "&&") {
6023
+ const jzEnd = emitJumpPlaceholder(OP_JZ);
6024
+ if (!compileExpr(node.right, true)) return false;
6025
+ emit(OP_STV, tmpSlot);
6026
+ patchJump(jzEnd, bytecode.length);
6027
+ } else if (node.operator === "||") {
6028
+ emit(OP_NOT);
6029
+ const jzEnd = emitJumpPlaceholder(OP_JZ);
6030
+ if (!compileExpr(node.right, true)) return false;
6031
+ emit(OP_STV, tmpSlot);
6032
+ patchJump(jzEnd, bytecode.length);
6033
+ } else if (node.operator === "??") {
6034
+ emit(OP_NULLISH);
6035
+ const jzEnd = emitJumpPlaceholder(OP_JZ);
6036
+ if (!compileExpr(node.right, true)) return false;
6037
+ emit(OP_STV, tmpSlot);
6038
+ patchJump(jzEnd, bytecode.length);
6039
+ } else {
6040
+ return false;
6041
+ }
6042
+ if (inValuePos) {
6043
+ emit(OP_LDV, tmpSlot);
4445
6044
  }
4446
6045
  return true;
4447
6046
  }
6047
+ case "ConditionalExpression": {
6048
+ if (!compileExpr(node.test, true)) return false;
6049
+ const jzAlt = emitJumpPlaceholder(OP_JZ);
6050
+ if (!compileExpr(node.consequent, inValuePos)) return false;
6051
+ const jmpEnd = emitJumpPlaceholder(OP_JMP);
6052
+ patchJump(jzAlt, bytecode.length);
6053
+ if (!compileExpr(node.alternate, inValuePos)) return false;
6054
+ patchJump(jmpEnd, bytecode.length);
6055
+ return true;
6056
+ }
6057
+ case "SequenceExpression": {
6058
+ const exprs = node.expressions || [];
6059
+ if (exprs.length === 0) return false;
6060
+ for (let i = 0; i < exprs.length - 1; i++) {
6061
+ if (!compileExpr(exprs[i], false)) return false;
6062
+ }
6063
+ return compileExpr(exprs[exprs.length - 1], inValuePos);
6064
+ }
4448
6065
  case "UnaryExpression": {
4449
6066
  if (node.operator === "void") {
4450
- if (node.argument?.type !== "Literal" || node.argument.regex) return false;
4451
- const undefIdx2 = addConst(void 0);
4452
- emit(OP_LDC, undefIdx2);
6067
+ if (!compileExpr(node.argument, false)) return false;
6068
+ if (inValuePos) emit(OP_LDC, addConst(void 0));
6069
+ return true;
6070
+ }
6071
+ if (node.operator === "typeof" && node.argument?.type === "Identifier") {
6072
+ const name = node.argument.name;
6073
+ if (name === "undefined" && resolveLocal("undefined") === void 0) {
6074
+ emit(OP_LDC, addConst(void 0));
6075
+ } else {
6076
+ emitLoadVar(name);
6077
+ }
6078
+ emit(OP_TYPEOF);
6079
+ if (!inValuePos) emit(OP_POP);
4453
6080
  return true;
4454
6081
  }
4455
6082
  if (!compileExpr(node.argument, true)) return false;
@@ -4458,26 +6085,28 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4458
6085
  emit(OP_NOT);
4459
6086
  break;
4460
6087
  case "-": {
4461
- const neg1Idx = addConst(-1);
4462
- emit(OP_LDC, neg1Idx);
6088
+ emit(OP_LDC, addConst(-1));
4463
6089
  emit(OP_MUL);
4464
6090
  break;
4465
6091
  }
4466
6092
  case "+": {
4467
- const zeroIdx = addConst(0);
4468
- emit(OP_LDC, zeroIdx);
4469
- emit(OP_ADD);
6093
+ emit(OP_LDC, addConst(1));
6094
+ emit(OP_MUL);
4470
6095
  break;
4471
6096
  }
4472
6097
  case "~": {
4473
- const neg1Idx = addConst(-1);
4474
- emit(OP_LDC, neg1Idx);
6098
+ emit(OP_LDC, addConst(-1));
4475
6099
  emit(OP_XOR);
4476
6100
  break;
4477
6101
  }
6102
+ case "typeof": {
6103
+ emit(OP_TYPEOF);
6104
+ break;
6105
+ }
4478
6106
  default:
4479
6107
  return false;
4480
6108
  }
6109
+ if (!inValuePos) emit(OP_POP);
4481
6110
  return true;
4482
6111
  }
4483
6112
  case "MemberExpression": {
@@ -4487,14 +6116,17 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4487
6116
  if (!compileExpr(node.property, true)) return false;
4488
6117
  } else {
4489
6118
  if (node.property?.type !== "Identifier") return false;
4490
- const idx = addConst(node.property.name);
4491
- emit(OP_LDC, idx);
6119
+ emit(OP_LDC, addConst(node.property.name));
4492
6120
  }
4493
6121
  emit(OP_GETP);
6122
+ if (!inValuePos) emit(OP_POP);
4494
6123
  return true;
4495
6124
  }
4496
6125
  case "CallExpression": {
4497
6126
  if (node.optional) return false;
6127
+ for (const arg of node.arguments || []) {
6128
+ if (arg?.type === "SpreadElement") return false;
6129
+ }
4498
6130
  if (node.callee.type === "MemberExpression") {
4499
6131
  if (node.callee.optional) return false;
4500
6132
  if (!compileExpr(node.callee.object, true)) return false;
@@ -4502,8 +6134,7 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4502
6134
  if (!compileExpr(node.callee.property, true)) return false;
4503
6135
  } else {
4504
6136
  if (node.callee.property?.type !== "Identifier") return false;
4505
- const idx = addConst(node.callee.property.name);
4506
- emit(OP_LDC, idx);
6137
+ emit(OP_LDC, addConst(node.callee.property.name));
4507
6138
  }
4508
6139
  for (const arg of node.arguments) {
4509
6140
  if (!compileExpr(arg, true)) return false;
@@ -4516,6 +6147,19 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4516
6147
  }
4517
6148
  emit(OP_CALL, node.arguments.length);
4518
6149
  }
6150
+ if (!inValuePos) emit(OP_POP);
6151
+ return true;
6152
+ }
6153
+ case "NewExpression": {
6154
+ for (const arg of node.arguments || []) {
6155
+ if (arg?.type === "SpreadElement") return false;
6156
+ }
6157
+ if (!compileExpr(node.callee, true)) return false;
6158
+ for (const arg of node.arguments || []) {
6159
+ if (!compileExpr(arg, true)) return false;
6160
+ }
6161
+ emit(OP_NEW, (node.arguments || []).length);
6162
+ if (!inValuePos) emit(OP_POP);
4519
6163
  return true;
4520
6164
  }
4521
6165
  case "AssignmentExpression": {
@@ -4524,86 +6168,129 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4524
6168
  if (!canWriteVar(name)) return false;
4525
6169
  if (node.operator === "=") {
4526
6170
  if (!compileExpr(node.right, true)) return false;
6171
+ } else if (node.operator === "&&=" || node.operator === "||=" || node.operator === "??=") {
6172
+ emitLoadVar(name);
6173
+ if (node.operator === "||=") emit(OP_NOT);
6174
+ else if (node.operator === "??=") emit(OP_NULLISH);
6175
+ const jzSkip = emitJumpPlaceholder(OP_JZ);
6176
+ if (!compileExpr(node.right, true)) return false;
6177
+ if (!emitStoreVar(name)) return false;
6178
+ patchJump(jzSkip, bytecode.length);
6179
+ if (inValuePos) emitLoadVar(name);
6180
+ return true;
4527
6181
  } else {
4528
- let binOp = null;
4529
- switch (node.operator) {
4530
- case "+=":
4531
- binOp = OP_ADD;
4532
- break;
4533
- case "-=":
4534
- binOp = OP_SUB;
4535
- break;
4536
- case "*=":
4537
- binOp = OP_MUL;
4538
- break;
4539
- case "^=":
4540
- binOp = OP_XOR;
4541
- break;
4542
- case "&=":
4543
- binOp = OP_AND;
4544
- break;
4545
- case "|=":
4546
- binOp = OP_OR;
4547
- break;
4548
- default:
4549
- return false;
4550
- }
6182
+ const baseOp = node.operator.slice(0, -1);
4551
6183
  emitLoadVar(name);
4552
6184
  if (!compileExpr(node.right, true)) return false;
4553
- emit(binOp);
6185
+ if (!compileBinaryOp(baseOp)) return false;
4554
6186
  }
4555
6187
  if (!emitStoreVar(name)) return false;
4556
- if (inValuePos) {
4557
- emitLoadVar(name);
4558
- }
6188
+ if (inValuePos) emitLoadVar(name);
4559
6189
  return true;
4560
6190
  }
4561
6191
  if (node.left.type === "MemberExpression") {
4562
- if (node.operator !== "=" || node.left.optional) return false;
6192
+ if (node.left.optional) return false;
6193
+ if (node.operator === "=") {
6194
+ if (!compileExpr(node.left.object, true)) return false;
6195
+ if (node.left.computed) {
6196
+ if (!compileExpr(node.left.property, true)) return false;
6197
+ } else {
6198
+ if (node.left.property?.type !== "Identifier") return false;
6199
+ emit(OP_LDC, addConst(node.left.property.name));
6200
+ }
6201
+ if (!compileExpr(node.right, true)) return false;
6202
+ emit(OP_SETP);
6203
+ if (!inValuePos) emit(OP_POP);
6204
+ return true;
6205
+ }
6206
+ const baseOp = node.operator.slice(0, -1);
6207
+ const objSlot = allocTempSlot();
6208
+ const keySlot = allocTempSlot();
4563
6209
  if (!compileExpr(node.left.object, true)) return false;
6210
+ emit(OP_STV, objSlot);
4564
6211
  if (node.left.computed) {
4565
6212
  if (!compileExpr(node.left.property, true)) return false;
4566
6213
  } else {
4567
6214
  if (node.left.property?.type !== "Identifier") return false;
4568
- const idx = addConst(node.left.property.name);
4569
- emit(OP_LDC, idx);
6215
+ emit(OP_LDC, addConst(node.left.property.name));
4570
6216
  }
6217
+ emit(OP_STV, keySlot);
6218
+ emit(OP_LDV, objSlot);
6219
+ emit(OP_LDV, keySlot);
6220
+ emit(OP_LDV, objSlot);
6221
+ emit(OP_LDV, keySlot);
6222
+ emit(OP_GETP);
4571
6223
  if (!compileExpr(node.right, true)) return false;
6224
+ if (!compileBinaryOp(baseOp)) return false;
4572
6225
  emit(OP_SETP);
6226
+ if (!inValuePos) emit(OP_POP);
4573
6227
  return true;
4574
6228
  }
4575
6229
  return false;
4576
6230
  }
4577
6231
  case "UpdateExpression": {
4578
- if (node.argument?.type !== "Identifier") return false;
4579
- const name = node.argument.name;
4580
- if (!canWriteVar(name)) return false;
4581
6232
  const oneIdx = addConst(1);
4582
6233
  const stepOp = node.operator === "++" ? OP_ADD : OP_SUB;
4583
- if (node.prefix) {
4584
- emitLoadVar(name);
4585
- emit(OP_LDC, oneIdx);
4586
- emit(OP_MUL);
4587
- emit(OP_LDC, oneIdx);
4588
- emit(stepOp);
4589
- if (!emitStoreVar(name)) return false;
4590
- if (inValuePos) {
6234
+ if (node.argument?.type === "Identifier") {
6235
+ const name = node.argument.name;
6236
+ if (!canWriteVar(name)) return false;
6237
+ if (node.prefix) {
4591
6238
  emitLoadVar(name);
4592
- }
4593
- } else {
4594
- if (inValuePos) {
6239
+ emit(OP_LDC, oneIdx);
6240
+ emit(OP_MUL);
6241
+ emit(OP_LDC, oneIdx);
6242
+ emit(stepOp);
6243
+ if (!emitStoreVar(name)) return false;
6244
+ if (inValuePos) emitLoadVar(name);
6245
+ } else {
6246
+ if (inValuePos) {
6247
+ emitLoadVar(name);
6248
+ emit(OP_LDC, oneIdx);
6249
+ emit(OP_MUL);
6250
+ }
4595
6251
  emitLoadVar(name);
4596
6252
  emit(OP_LDC, oneIdx);
4597
6253
  emit(OP_MUL);
6254
+ emit(OP_LDC, oneIdx);
6255
+ emit(stepOp);
6256
+ if (!emitStoreVar(name)) return false;
6257
+ }
6258
+ return true;
6259
+ }
6260
+ if (node.argument?.type === "MemberExpression" && !node.argument.optional) {
6261
+ const objSlot = allocTempSlot();
6262
+ const keySlot = allocTempSlot();
6263
+ const oldSlot = allocTempSlot();
6264
+ if (!compileExpr(node.argument.object, true)) return false;
6265
+ emit(OP_STV, objSlot);
6266
+ if (node.argument.computed) {
6267
+ if (!compileExpr(node.argument.property, true)) return false;
6268
+ } else {
6269
+ if (node.argument.property?.type !== "Identifier") return false;
6270
+ emit(OP_LDC, addConst(node.argument.property.name));
4598
6271
  }
4599
- emitLoadVar(name);
6272
+ emit(OP_STV, keySlot);
6273
+ emit(OP_LDV, objSlot);
6274
+ emit(OP_LDV, keySlot);
6275
+ emit(OP_GETP);
4600
6276
  emit(OP_LDC, oneIdx);
4601
6277
  emit(OP_MUL);
6278
+ emit(OP_STV, oldSlot);
6279
+ emit(OP_LDV, objSlot);
6280
+ emit(OP_LDV, keySlot);
6281
+ emit(OP_LDV, oldSlot);
4602
6282
  emit(OP_LDC, oneIdx);
4603
6283
  emit(stepOp);
4604
- if (!emitStoreVar(name)) return false;
6284
+ emit(OP_SETP);
6285
+ if (node.prefix) {
6286
+ if (!inValuePos) emit(OP_POP);
6287
+ } else {
6288
+ emit(OP_POP);
6289
+ if (inValuePos) emit(OP_LDV, oldSlot);
6290
+ }
6291
+ return true;
4605
6292
  }
4606
- return true;
6293
+ return false;
4607
6294
  }
4608
6295
  case "ObjectExpression": {
4609
6296
  for (const prop of node.properties) {
@@ -4613,87 +6300,331 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4613
6300
  } else {
4614
6301
  const keyName = prop.key?.name ?? prop.key?.value;
4615
6302
  if (keyName === void 0) return false;
4616
- const idx = addConst(keyName);
4617
- emit(OP_LDC, idx);
6303
+ emit(OP_LDC, addConst(keyName));
4618
6304
  }
4619
6305
  if (!compileExpr(prop.value, true)) return false;
4620
6306
  }
4621
6307
  emit(OP_OBJ, node.properties.length);
6308
+ if (!inValuePos) emit(OP_POP);
4622
6309
  return true;
4623
6310
  }
4624
6311
  case "ArrayExpression": {
4625
6312
  for (const elem of node.elements) {
4626
- if (!elem || !compileExpr(elem, true)) return false;
6313
+ if (!elem || elem.type === "SpreadElement" || !compileExpr(elem, true)) return false;
4627
6314
  }
4628
6315
  emit(OP_ARR, node.elements.length);
6316
+ if (!inValuePos) emit(OP_POP);
4629
6317
  return true;
4630
6318
  }
4631
6319
  case "AwaitExpression": {
4632
6320
  if (!compileExpr(node.argument, true)) return false;
4633
6321
  emit(OP_AWAIT);
6322
+ if (!inValuePos) emit(OP_POP);
4634
6323
  return true;
4635
6324
  }
4636
6325
  default:
4637
6326
  return false;
4638
6327
  }
4639
6328
  }
4640
- function compileStmt(stmt, isFnBody = false) {
6329
+ function compileStmt(stmt, isFnBody = false, activeLabel) {
4641
6330
  if (!stmt) return false;
4642
6331
  switch (stmt.type) {
6332
+ case "EmptyStatement":
6333
+ return true;
4643
6334
  case "ReturnStatement": {
4644
6335
  if (stmt.argument) {
4645
6336
  if (!compileExpr(stmt.argument, true)) return false;
4646
6337
  } else {
4647
- const idx = addConst(void 0);
4648
- emit(OP_LDC, idx);
6338
+ emit(OP_LDC, addConst(void 0));
4649
6339
  }
4650
6340
  emit(OP_RET);
4651
6341
  return true;
4652
6342
  }
4653
- case "ExpressionStatement": {
4654
- if (!compileExpr(stmt.expression, false)) return false;
6343
+ case "ThrowStatement": {
6344
+ if (!compileExpr(stmt.argument, true)) return false;
6345
+ emit(OP_THROW);
4655
6346
  return true;
4656
6347
  }
6348
+ case "ExpressionStatement": {
6349
+ return compileExpr(stmt.expression, false);
6350
+ }
4657
6351
  case "VariableDeclaration": {
4658
6352
  for (const decl of stmt.declarations) {
4659
- if (decl.id?.type !== "Identifier") return false;
4660
- const slot = resolveLocal(decl.id.name);
4661
- if (slot === void 0) return false;
4662
- if (decl.init) {
6353
+ if (decl.id?.type === "Identifier") {
6354
+ const slot = resolveLocal(decl.id.name);
6355
+ if (slot === void 0) return false;
6356
+ if (decl.init) {
6357
+ if (!compileExpr(decl.init, true)) return false;
6358
+ emit(OP_STV, slot);
6359
+ }
6360
+ } else if (decl.id?.type === "ObjectPattern" || decl.id?.type === "ArrayPattern") {
6361
+ if (!decl.init) return false;
6362
+ const srcSlot = allocTempSlot();
4663
6363
  if (!compileExpr(decl.init, true)) return false;
4664
- emit(OP_STV, slot);
6364
+ emit(OP_STV, srcSlot);
6365
+ if (!compilePatternAssignFromSlot(decl.id, srcSlot)) return false;
6366
+ } else {
6367
+ return false;
4665
6368
  }
4666
6369
  }
4667
6370
  return true;
4668
6371
  }
4669
6372
  case "IfStatement": {
4670
6373
  if (!compileExpr(stmt.test, true)) return false;
4671
- const jzPos = bytecode.length;
4672
- emit(OP_JZ, 0, 0);
4673
- stateSlots.add(jzPos + 2);
6374
+ const jzPos = emitJumpPlaceholder(OP_JZ);
4674
6375
  if (!compileStmt(stmt.consequent, false)) return false;
4675
6376
  if (stmt.alternate) {
4676
- const jmpPos = bytecode.length;
4677
- emit(OP_JMP, 0, 0);
4678
- stateSlots.add(jmpPos + 2);
4679
- bytecode[jzPos + 1] = bytecode.length;
6377
+ const jmpPos = emitJumpPlaceholder(OP_JMP);
6378
+ patchJump(jzPos, bytecode.length);
4680
6379
  if (!compileStmt(stmt.alternate, false)) return false;
4681
- bytecode[jmpPos + 1] = bytecode.length;
6380
+ patchJump(jmpPos, bytecode.length);
4682
6381
  } else {
4683
- bytecode[jzPos + 1] = bytecode.length;
6382
+ patchJump(jzPos, bytecode.length);
4684
6383
  }
4685
6384
  return true;
4686
6385
  }
6386
+ case "WhileStatement": {
6387
+ const loopStart = bytecode.length;
6388
+ const target = {
6389
+ label: activeLabel,
6390
+ tryDepth,
6391
+ breakJumps: [],
6392
+ continueJumps: []
6393
+ };
6394
+ loopStack.push(target);
6395
+ if (!compileExpr(stmt.test, true)) {
6396
+ loopStack.pop();
6397
+ return false;
6398
+ }
6399
+ const jzEnd = emitJumpPlaceholder(OP_JZ);
6400
+ if (!compileStmt(stmt.body, false)) {
6401
+ loopStack.pop();
6402
+ return false;
6403
+ }
6404
+ for (const cPos of target.continueJumps) {
6405
+ patchJump(cPos, loopStart);
6406
+ }
6407
+ const jmpLoop = emitJumpPlaceholder(OP_JMP);
6408
+ patchJump(jmpLoop, loopStart);
6409
+ const loopEnd = bytecode.length;
6410
+ patchJump(jzEnd, loopEnd);
6411
+ for (const bPos of target.breakJumps) {
6412
+ patchJump(bPos, loopEnd);
6413
+ }
6414
+ loopStack.pop();
6415
+ return true;
6416
+ }
6417
+ case "DoWhileStatement": {
6418
+ const loopStart = bytecode.length;
6419
+ const target = {
6420
+ label: activeLabel,
6421
+ tryDepth,
6422
+ breakJumps: [],
6423
+ continueJumps: []
6424
+ };
6425
+ loopStack.push(target);
6426
+ if (!compileStmt(stmt.body, false)) {
6427
+ loopStack.pop();
6428
+ return false;
6429
+ }
6430
+ const continuePc = bytecode.length;
6431
+ for (const cPos of target.continueJumps) {
6432
+ patchJump(cPos, continuePc);
6433
+ }
6434
+ if (!compileExpr(stmt.test, true)) {
6435
+ loopStack.pop();
6436
+ return false;
6437
+ }
6438
+ const jzEnd = emitJumpPlaceholder(OP_JZ);
6439
+ const jmpLoop = emitJumpPlaceholder(OP_JMP);
6440
+ patchJump(jmpLoop, loopStart);
6441
+ const loopEnd = bytecode.length;
6442
+ patchJump(jzEnd, loopEnd);
6443
+ for (const bPos of target.breakJumps) {
6444
+ patchJump(bPos, loopEnd);
6445
+ }
6446
+ loopStack.pop();
6447
+ return true;
6448
+ }
6449
+ case "ForStatement": {
6450
+ let pushedForScope = false;
6451
+ if (stmt.init?.type === "VariableDeclaration" && stmt.init.kind !== "var") {
6452
+ const forScope = /* @__PURE__ */ new Map();
6453
+ const names = /* @__PURE__ */ new Set();
6454
+ for (const decl of stmt.init.declarations || []) {
6455
+ collectPatternNames(decl.id, names);
6456
+ }
6457
+ for (const name of names) {
6458
+ forScope.set(name, localCount++);
6459
+ }
6460
+ if (forScope.size > 0) {
6461
+ scopeStack.push(forScope);
6462
+ pushedForScope = true;
6463
+ }
6464
+ }
6465
+ if (stmt.init) {
6466
+ const ok = stmt.init.type === "VariableDeclaration" ? compileStmt(stmt.init, false) : compileExpr(stmt.init, false);
6467
+ if (!ok) {
6468
+ if (pushedForScope) scopeStack.pop();
6469
+ return false;
6470
+ }
6471
+ }
6472
+ const testPc = bytecode.length;
6473
+ const target = {
6474
+ label: activeLabel,
6475
+ tryDepth,
6476
+ breakJumps: [],
6477
+ continueJumps: []
6478
+ };
6479
+ loopStack.push(target);
6480
+ let jzEnd = null;
6481
+ if (stmt.test) {
6482
+ if (!compileExpr(stmt.test, true)) {
6483
+ loopStack.pop();
6484
+ if (pushedForScope) scopeStack.pop();
6485
+ return false;
6486
+ }
6487
+ jzEnd = emitJumpPlaceholder(OP_JZ);
6488
+ }
6489
+ if (!compileStmt(stmt.body, false)) {
6490
+ loopStack.pop();
6491
+ if (pushedForScope) scopeStack.pop();
6492
+ return false;
6493
+ }
6494
+ const updatePc = bytecode.length;
6495
+ for (const cPos of target.continueJumps) {
6496
+ patchJump(cPos, updatePc);
6497
+ }
6498
+ if (stmt.update) {
6499
+ if (!compileExpr(stmt.update, false)) {
6500
+ loopStack.pop();
6501
+ if (pushedForScope) scopeStack.pop();
6502
+ return false;
6503
+ }
6504
+ }
6505
+ const jmpTest = emitJumpPlaceholder(OP_JMP);
6506
+ patchJump(jmpTest, testPc);
6507
+ const loopEnd = bytecode.length;
6508
+ if (jzEnd !== null) patchJump(jzEnd, loopEnd);
6509
+ for (const bPos of target.breakJumps) {
6510
+ patchJump(bPos, loopEnd);
6511
+ }
6512
+ loopStack.pop();
6513
+ if (pushedForScope) scopeStack.pop();
6514
+ return true;
6515
+ }
6516
+ case "BreakStatement":
6517
+ case "ContinueStatement": {
6518
+ const isBreak = stmt.type === "BreakStatement";
6519
+ const labelName = stmt.label?.name;
6520
+ let target;
6521
+ for (let i = loopStack.length - 1; i >= 0; i--) {
6522
+ if (!labelName || loopStack[i].label === labelName) {
6523
+ target = loopStack[i];
6524
+ break;
6525
+ }
6526
+ }
6527
+ if (!target) return false;
6528
+ const exitTryCount = tryDepth - target.tryDepth;
6529
+ for (let t = 0; t < exitTryCount; t++) {
6530
+ emit(OP_ENDTRY);
6531
+ }
6532
+ const jmpPos = emitJumpPlaceholder(OP_JMP);
6533
+ if (isBreak) target.breakJumps.push(jmpPos);
6534
+ else target.continueJumps.push(jmpPos);
6535
+ return true;
6536
+ }
6537
+ case "LabeledStatement": {
6538
+ return compileStmt(stmt.body, false, stmt.label?.name);
6539
+ }
6540
+ case "TryStatement": {
6541
+ if (stmt.finalizer) {
6542
+ if (hasAbruptControlFlow(stmt.block) || stmt.handler && hasAbruptControlFlow(stmt.handler.body)) {
6543
+ return false;
6544
+ }
6545
+ const outerTryPos = emitJumpPlaceholder(OP_TRY);
6546
+ tryDepth++;
6547
+ const innerOk = compileStmt(
6548
+ {
6549
+ type: "TryStatement",
6550
+ block: stmt.block,
6551
+ handler: stmt.handler,
6552
+ finalizer: null
6553
+ },
6554
+ false
6555
+ );
6556
+ tryDepth--;
6557
+ if (!innerOk) return false;
6558
+ emit(OP_ENDTRY);
6559
+ if (!compileStmt(stmt.finalizer, false)) return false;
6560
+ const jmpAfter = emitJumpPlaceholder(OP_JMP);
6561
+ patchJump(outerTryPos, bytecode.length);
6562
+ const finErrSlot = allocTempSlot();
6563
+ emit(OP_STV, finErrSlot);
6564
+ if (!compileStmt(stmt.finalizer, false)) return false;
6565
+ emit(OP_LDV, finErrSlot);
6566
+ emit(OP_THROW);
6567
+ patchJump(jmpAfter, bytecode.length);
6568
+ return true;
6569
+ }
6570
+ const tryPos = emitJumpPlaceholder(OP_TRY);
6571
+ tryDepth++;
6572
+ if (!compileStmt(stmt.block, false)) {
6573
+ tryDepth--;
6574
+ return false;
6575
+ }
6576
+ tryDepth--;
6577
+ emit(OP_ENDTRY);
6578
+ const jmpAfterCatch = emitJumpPlaceholder(OP_JMP);
6579
+ patchJump(tryPos, bytecode.length);
6580
+ if (stmt.handler) {
6581
+ let pushedCatch = false;
6582
+ if (stmt.handler.param) {
6583
+ const catchScope = /* @__PURE__ */ new Map();
6584
+ const names = /* @__PURE__ */ new Set();
6585
+ collectPatternNames(stmt.handler.param, names);
6586
+ for (const name of names) {
6587
+ catchScope.set(name, localCount++);
6588
+ }
6589
+ scopeStack.push(catchScope);
6590
+ pushedCatch = true;
6591
+ if (stmt.handler.param.type === "Identifier") {
6592
+ emit(OP_STV, catchScope.get(stmt.handler.param.name));
6593
+ } else {
6594
+ const errSlot = allocTempSlot();
6595
+ emit(OP_STV, errSlot);
6596
+ if (!compilePatternAssignFromSlot(stmt.handler.param, errSlot)) {
6597
+ scopeStack.pop();
6598
+ return false;
6599
+ }
6600
+ }
6601
+ } else {
6602
+ emit(OP_POP);
6603
+ }
6604
+ if (!compileStmt(stmt.handler.body, false)) {
6605
+ if (pushedCatch) scopeStack.pop();
6606
+ return false;
6607
+ }
6608
+ if (pushedCatch) scopeStack.pop();
6609
+ } else {
6610
+ emit(OP_POP);
6611
+ }
6612
+ patchJump(jmpAfterCatch, bytecode.length);
6613
+ return true;
6614
+ }
4687
6615
  case "BlockStatement": {
4688
6616
  let pushedBlock = false;
4689
6617
  if (!isFnBody) {
4690
6618
  const blockScope = /* @__PURE__ */ new Map();
4691
6619
  for (const s of stmt.body || []) {
4692
6620
  if (s.type === "VariableDeclaration" && s.kind !== "var") {
6621
+ const names = /* @__PURE__ */ new Set();
4693
6622
  for (const decl of s.declarations || []) {
4694
- if (decl.id?.type !== "Identifier") return false;
4695
- if (!blockScope.has(decl.id.name)) {
4696
- blockScope.set(decl.id.name, localCount++);
6623
+ collectPatternNames(decl.id, names);
6624
+ }
6625
+ for (const name of names) {
6626
+ if (!blockScope.has(name)) {
6627
+ blockScope.set(name, localCount++);
4697
6628
  }
4698
6629
  }
4699
6630
  }
@@ -4722,10 +6653,9 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
4722
6653
  if (!compileExpr(fnNode.body, true)) return null;
4723
6654
  emit(OP_RET);
4724
6655
  }
4725
- const undefIdx = addConst(void 0);
4726
- emit(OP_LDC, undefIdx);
6656
+ emit(OP_LDC, addConst(void 0));
4727
6657
  emit(OP_RET);
4728
- return { bytecode, consts, localCount, stateSlots, upvalues };
6658
+ return { bytecode, consts, localCount, stateSlots, accSlots, upvalues };
4729
6659
  }
4730
6660
  function findInjectedVmHelperName(ast) {
4731
6661
  if (!ast || !Array.isArray(ast.body)) return null;
@@ -4743,7 +6673,7 @@ function findInjectedVmHelperName(ast) {
4743
6673
  }
4744
6674
  return null;
4745
6675
  }
4746
- function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769, windowKeySymbol, expectedDelta) {
6676
+ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769, windowKeySymbol, expectedDelta, extraOpts) {
4747
6677
  const suffix = computeFnv1aHash(`micro-vm:${seed}`, seed).toString(36);
4748
6678
  const vmHelperName = `_uVm${suffix}`;
4749
6679
  const existingName = findInjectedVmHelperName(ast);
@@ -4753,6 +6683,8 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4753
6683
  vmHelperName: existingName
4754
6684
  };
4755
6685
  }
6686
+ const maxFunctions = extraOpts?.maxFunctionsPerChunk ?? 12;
6687
+ const criticalSet = extraOpts?.criticalFunctionNodes;
4756
6688
  const opMap = generateOpcodeMap(seed, OPCODE_COUNT);
4757
6689
  const vmKey = deriveVmKey(seed);
4758
6690
  const scopeBindings = /* @__PURE__ */ new Map();
@@ -4781,7 +6713,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4781
6713
  }
4782
6714
  return ast;
4783
6715
  }
4784
- const candidates = [];
6716
+ const rawCandidates = [];
4785
6717
  walk7.ancestor(ast, {
4786
6718
  ImportDeclaration(node) {
4787
6719
  for (const spec of node.specifiers || []) {
@@ -4813,7 +6745,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4813
6745
  for (const name of paramNames) {
4814
6746
  addScopeBinding(node, name);
4815
6747
  }
4816
- candidates.push({ fn: node, ancestors: ancestors.slice() });
6748
+ rawCandidates.push({ fn: node, ancestors: ancestors.slice() });
4817
6749
  },
4818
6750
  FunctionExpression(node, _state, ancestors) {
4819
6751
  if (node.id?.type === "Identifier") {
@@ -4826,7 +6758,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4826
6758
  for (const name of paramNames) {
4827
6759
  addScopeBinding(node, name);
4828
6760
  }
4829
- candidates.push({ fn: node, ancestors: ancestors.slice() });
6761
+ rawCandidates.push({ fn: node, ancestors: ancestors.slice() });
4830
6762
  },
4831
6763
  ArrowFunctionExpression(node, _state, ancestors) {
4832
6764
  const paramNames = /* @__PURE__ */ new Set();
@@ -4836,7 +6768,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4836
6768
  for (const name of paramNames) {
4837
6769
  addScopeBinding(node, name);
4838
6770
  }
4839
- candidates.push({ fn: node, ancestors: ancestors.slice() });
6771
+ rawCandidates.push({ fn: node, ancestors: ancestors.slice() });
4840
6772
  },
4841
6773
  ClassDeclaration(node, _state, ancestors) {
4842
6774
  if (node.id?.type === "Identifier") {
@@ -4859,9 +6791,13 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4859
6791
  }
4860
6792
  }
4861
6793
  });
6794
+ const candidates = criticalSet ? [
6795
+ ...rawCandidates.filter((c) => criticalSet.has(c.fn)),
6796
+ ...rawCandidates.filter((c) => !criticalSet.has(c.fn))
6797
+ ] : rawCandidates;
4862
6798
  let virtualizedCount = 0;
4863
6799
  for (const { fn, ancestors } of candidates) {
4864
- if (virtualizedCount >= 5) break;
6800
+ if (virtualizedCount >= maxFunctions) break;
4865
6801
  if (coldFunctionNodes && !coldFunctionNodes.has(fn)) {
4866
6802
  continue;
4867
6803
  }
@@ -4882,7 +6818,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4882
6818
  continue;
4883
6819
  }
4884
6820
  const nodeCount = countAstNodes(fn);
4885
- if (nodeCount < 15 || nodeCount > 80) {
6821
+ if (nodeCount < 8 || nodeCount > 400) {
4886
6822
  continue;
4887
6823
  }
4888
6824
  const enclosingBindings = /* @__PURE__ */ new Set();
@@ -4897,7 +6833,11 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4897
6833
  if (fn.type === "FunctionExpression" && fn.id?.type === "Identifier") {
4898
6834
  enclosingBindings.add(fn.id.name);
4899
6835
  }
4900
- const compiled = compileFunctionToBytecode(fn, opMap, enclosingBindings);
6836
+ const lowered = prepareLoweredFunction(fn, enclosingBindings);
6837
+ if (!lowered) {
6838
+ continue;
6839
+ }
6840
+ const compiled = compileFunctionToBytecode(lowered.loweredFn, opMap, enclosingBindings);
4901
6841
  if (!compiled) {
4902
6842
  continue;
4903
6843
  }
@@ -4906,12 +6846,9 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4906
6846
  compiled.bytecode,
4907
6847
  fnSalt,
4908
6848
  vmKey,
4909
- compiled.stateSlots
6849
+ compiled.stateSlots,
6850
+ compiled.accSlots
4910
6851
  );
4911
- const paramArgs = fn.params.map((p) => ({
4912
- type: "Identifier",
4913
- name: p.name
4914
- }));
4915
6852
  const constElements = compiled.consts.map((c) => {
4916
6853
  if (c === void 0) {
4917
6854
  return {
@@ -4942,7 +6879,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
4942
6879
  },
4943
6880
  {
4944
6881
  type: "ArrayExpression",
4945
- elements: paramArgs
6882
+ elements: lowered.paramPassExprs
4946
6883
  },
4947
6884
  {
4948
6885
  type: "ThisExpression"
@@ -5010,6 +6947,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
5010
6947
  arguments: callArgs,
5011
6948
  optional: false
5012
6949
  };
6950
+ fn.params = lowered.wrapperParams;
5013
6951
  if (fn.body.type === "BlockStatement") {
5014
6952
  fn.body.body = [
5015
6953
  {
@@ -5030,7 +6968,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
5030
6968
  windowKeySymbol,
5031
6969
  expectedDelta
5032
6970
  );
5033
- const parsedHelper = acorn5.parse(interpreterSource, {
6971
+ const parsedHelper = acorn6.parse(interpreterSource, {
5034
6972
  ecmaVersion: "latest",
5035
6973
  sourceType: "script"
5036
6974
  });
@@ -5056,14 +6994,20 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
5056
6994
  import * as walk8 from "acorn-walk";
5057
6995
  var FILE_URI_USER_RE = /file:\/\/\/(?:[A-Za-z]:\/)?(?:Users|home)\/[^/\s"'`]+\/([^\s"'`]+)/gi;
5058
6996
  var FILE_URI_LOCAL_RE = /file:\/\/\/(?:[A-Za-z]:\/)?([^\s"'`]+)/gi;
6997
+ var WEBPACK_URI_RE = /webpack(?:-internal)?:\/\/[^/\s"'`]*\/(?:\.\/)?([^\s"'`]+)/gi;
6998
+ var TURBOPACK_PROJECT_RE = /\[project\][\\/]([^\s"'`]+)/g;
5059
6999
  var POSIX_USER_PATH_RE = /\/?(?:Users|home)\/[^/\s"'`]+\/([^\s"'`]+)/g;
5060
- var WIN_USER_PATH_RE = /[A-Za-z]:\\{1,2}Users\\{1,2}[^\\\s"'`]+\\{1,2}([^\s"'`]+)/g;
7000
+ var WIN_USER_PATH_RE = /[A-Za-z]:(?:\\{1,2}|\/)Users(?:\\{1,2}|\/)[^\\/\s"'`]+(?:\\{1,2}|\/)([^\s"'`]+)/gi;
7001
+ var WIN_DRIVE_PATH_RE = /(^|[\s"'`(\[=,;:])([A-Za-z]:(?:\\{1,2}|\/)([^\s"'`]+))/g;
5061
7002
  var PROTECTED_URL_OR_ASSET_RE = /(?:https?:\/\/[^\s"'`]+|(?:\/assets\/|\/_next\/static\/)[^\s"'`]*)/gi;
5062
7003
  function escapeTemplateRaw(str) {
5063
7004
  return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
5064
7005
  }
7006
+ function escapeRegExp(str) {
7007
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7008
+ }
5065
7009
  function scrubStringValue(val, rootDir) {
5066
- if (!val.includes("/") && !val.includes("\\") && !val.includes("file:")) {
7010
+ if (!val.includes("/") && !val.includes("\\") && !val.includes("file:") && !val.includes("webpack:") && !val.includes("[project]")) {
5067
7011
  return val;
5068
7012
  }
5069
7013
  const shielded = [];
@@ -5074,23 +7018,35 @@ function scrubStringValue(val, rootDir) {
5074
7018
  });
5075
7019
  out = out.replace(FILE_URI_USER_RE, (_m, tail) => `[src]/${tail}`);
5076
7020
  out = out.replace(FILE_URI_LOCAL_RE, (_m, tail) => `[src]/${tail}`);
5077
- out = out.replace(POSIX_USER_PATH_RE, (_m, tail) => `[src]/${tail}`);
7021
+ out = out.replace(WEBPACK_URI_RE, (_m, tail) => `[src]/${tail}`);
5078
7022
  out = out.replace(
5079
- WIN_USER_PATH_RE,
7023
+ TURBOPACK_PROJECT_RE,
5080
7024
  (_m, tail) => `[src]/${tail.replace(/\\+/g, "/")}`
5081
7025
  );
5082
7026
  if (rootDir && rootDir.length > 1) {
5083
7027
  const normalizedRoot = rootDir.replace(/\\/g, "/").replace(/\/+$/, "");
5084
7028
  if (normalizedRoot.length > 1) {
5085
- if (out.includes(normalizedRoot + "/")) {
5086
- out = out.split(normalizedRoot + "/").join("[src]/");
5087
- }
5088
- const winRoot = normalizedRoot.replace(/\//g, "\\");
5089
- if (out.includes(winRoot + "\\")) {
5090
- out = out.split(winRoot + "\\").join("[src]/");
5091
- }
7029
+ const parts = normalizedRoot.split("/").map(escapeRegExp);
7030
+ const sepPattern = "(?:\\\\{1,2}|\\/)";
7031
+ const rootPattern = new RegExp(
7032
+ `${parts.join(sepPattern)}${sepPattern}([^\\s"'\`]+)`,
7033
+ /^[A-Za-z]:/.test(normalizedRoot) ? "gi" : "g"
7034
+ );
7035
+ out = out.replace(
7036
+ rootPattern,
7037
+ (_m, tail) => `[src]/${tail.replace(/\\+/g, "/")}`
7038
+ );
5092
7039
  }
5093
7040
  }
7041
+ out = out.replace(POSIX_USER_PATH_RE, (_m, tail) => `[src]/${tail}`);
7042
+ out = out.replace(
7043
+ WIN_USER_PATH_RE,
7044
+ (_m, tail) => `[src]/${tail.replace(/\\+/g, "/")}`
7045
+ );
7046
+ out = out.replace(
7047
+ WIN_DRIVE_PATH_RE,
7048
+ (_m, prefix, _full, tail) => `${prefix}[src]/${tail.replace(/\\+/g, "/")}`
7049
+ );
5094
7050
  if (shielded.length > 0) {
5095
7051
  out = out.replace(
5096
7052
  /\u0000_UP_SHIELD_(\d+)_\u0000/g,
@@ -5150,6 +7106,27 @@ function scrubResidualPaths(ast, options = {}, hotExemptNodes, exemptSubtreeRoot
5150
7106
  }
5151
7107
 
5152
7108
  // src/ast/index.ts
7109
+ function containsUnpeekShieldMarker(node, depth = 0) {
7110
+ if (!node || typeof node !== "object" || depth > 24) return false;
7111
+ if (node.type === "Identifier" && node.name === "__unpeek_tampered") {
7112
+ return true;
7113
+ }
7114
+ if (node.type === "Literal" && typeof node.value === "string" && (node.value === "__unpeek_tampered" || node.value === "unpeek:tamper" || node.value.startsWith("__upk_v4_"))) {
7115
+ return true;
7116
+ }
7117
+ for (const key of Object.keys(node)) {
7118
+ if (key === "loc" || key === "start" || key === "end") continue;
7119
+ const val = node[key];
7120
+ if (Array.isArray(val)) {
7121
+ for (const item of val) {
7122
+ if (containsUnpeekShieldMarker(item, depth + 1)) return true;
7123
+ }
7124
+ } else if (val && typeof val === "object" && typeof val.type === "string") {
7125
+ if (containsUnpeekShieldMarker(val, depth + 1)) return true;
7126
+ }
7127
+ }
7128
+ return false;
7129
+ }
5153
7130
  function isAstAlreadyProtected(ast) {
5154
7131
  if (!ast || !Array.isArray(ast.body)) return false;
5155
7132
  return ast.body.some((stmt) => {
@@ -5157,17 +7134,23 @@ function isAstAlreadyProtected(ast) {
5157
7134
  for (const d of stmt.declarations) {
5158
7135
  const name = d.id?.type === "Identifier" ? d.id.name : void 0;
5159
7136
  if (typeof name === "string") {
5160
- 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") {
7137
+ if (name === "_d" || name.startsWith("_uC") || name.startsWith("_uD") || name.startsWith("_uS") || name.startsWith("_uVm") || name.startsWith("_wKdf") || name.startsWith("_uP") || name.startsWith("_uCache") || name.startsWith("_uDc") || name.startsWith("_m") || name.startsWith("_w") || name.startsWith("_k") || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression" || d.init?.type === "CallExpression" && d.init.callee?.type === "MemberExpression" && d.init.callee.object?.type === "Identifier" && d.init.callee.object.name === "Symbol" && d.init.callee.property?.type === "Identifier" && d.init.callee.property.name === "for" && typeof d.init.arguments?.[0]?.value === "string" && d.init.arguments[0].value.startsWith("__upk_v4_")) {
5161
7138
  return true;
5162
7139
  }
5163
7140
  }
5164
7141
  }
5165
7142
  }
7143
+ if (stmt.type === "FunctionDeclaration" && stmt.id?.type === "Identifier") {
7144
+ const fnName = stmt.id.name;
7145
+ if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName.startsWith("_hX"))) {
7146
+ return true;
7147
+ }
7148
+ }
5166
7149
  if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression") {
5167
7150
  const callee = stmt.expression.callee;
5168
7151
  if (callee?.type === "FunctionExpression") {
5169
7152
  const name = callee.id?.name;
5170
- if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b"))) {
7153
+ if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b") || containsUnpeekShieldMarker(callee.body))) {
5171
7154
  return true;
5172
7155
  }
5173
7156
  }
@@ -5242,24 +7225,31 @@ function transformJavaScript(code, options = {}) {
5242
7225
  }
5243
7226
  const boundary = classifyChunkBoundary(ast);
5244
7227
  attachMagicComments(boundary.importExpressions, comments);
7228
+ const effectiveConfig = options.critical ? { ...options.config ?? {}, critical: options.critical } : options.config;
7229
+ const effectiveProfile = options.profile ?? effectiveConfig?.profile;
7230
+ const hotRes = analyzeAstHotPaths(ast, effectiveConfig);
5245
7231
  const {
5246
7232
  report: hotPathReport,
5247
7233
  coldFunctionNodes,
5248
7234
  hotFunctionNodes,
5249
7235
  hotExemptNodes,
5250
7236
  serializedFunctionNodes
5251
- } = analyzeAstHotPaths(ast, options.config);
5252
- if (options.scrubPaths || options.config?.scrubPaths) {
7237
+ } = hotRes;
7238
+ const criticalFunctionNodes = hotRes.criticalFunctionNodes;
7239
+ if (options.scrubPaths || effectiveConfig?.scrubPaths) {
5253
7240
  scrubResidualPaths(
5254
7241
  ast,
5255
- { scrubPaths: true },
7242
+ {
7243
+ scrubPaths: true,
7244
+ rootDir: internalOptions.rootDir ?? options.rootDir ?? process.cwd()
7245
+ },
5256
7246
  hotExemptNodes,
5257
7247
  boundary.exemptSubtreeRoots
5258
7248
  );
5259
7249
  }
5260
7250
  const shieldCoupled = internalOptions.shieldCoupled ?? Boolean(internalOptions.injectRuntimeShield);
5261
- const deterrentMode = internalOptions.deterrentMode ?? internalOptions.config?.shield?.deterrentMode ?? "passive";
5262
- const detectHeadless = internalOptions.detectHeadless ?? internalOptions.config?.shield?.detectHeadless ?? false;
7251
+ const deterrentMode = internalOptions.deterrentMode ?? effectiveConfig?.shield?.deterrentMode ?? "passive";
7252
+ const detectHeadless = internalOptions.detectHeadless ?? effectiveConfig?.shield?.detectHeadless ?? false;
5263
7253
  const sym = shieldCoupled ? internalOptions.windowKeySymbol ?? deriveWindowKeySymbol(seed) : void 0;
5264
7254
  let shieldDelta = shieldCoupled ? internalOptions.expectedDelta : void 0;
5265
7255
  if (shieldCoupled && shieldDelta === void 0) {
@@ -5273,7 +7263,19 @@ function transformJavaScript(code, options = {}) {
5273
7263
  }
5274
7264
  let virtualizedFunctionsCount = 0;
5275
7265
  if (isAggressive) {
5276
- const vmRes = applyMicroVm(
7266
+ const extraVmOpts = criticalFunctionNodes || effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? {
7267
+ ...criticalFunctionNodes ? { criticalFunctionNodes } : {},
7268
+ ...effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? { maxFunctionsPerChunk: effectiveConfig.critical.maxFunctionsPerChunk } : {}
7269
+ } : void 0;
7270
+ const vmRes = extraVmOpts ? applyMicroVm(
7271
+ ast,
7272
+ coldFunctionNodes,
7273
+ serializedFunctionNodes,
7274
+ seed,
7275
+ sym,
7276
+ shieldDelta,
7277
+ extraVmOpts
7278
+ ) : applyMicroVm(
5277
7279
  ast,
5278
7280
  coldFunctionNodes,
5279
7281
  serializedFunctionNodes,
@@ -5283,12 +7285,14 @@ function transformJavaScript(code, options = {}) {
5283
7285
  );
5284
7286
  virtualizedFunctionsCount = vmRes.virtualizedCount;
5285
7287
  }
5286
- applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
7288
+ if (effectiveProfile !== "minimal" && effectiveConfig?.coldFlow !== false) {
7289
+ applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
7290
+ }
5287
7291
  const mangledSymbolsCount = applyPolymorphicMangler(
5288
7292
  ast,
5289
7293
  seed,
5290
7294
  serializedFunctionNodes,
5291
- options.config
7295
+ effectiveConfig
5292
7296
  );
5293
7297
  let encryptedStringsCount = 0;
5294
7298
  let integrityToken = 0;
@@ -5299,7 +7303,7 @@ function transformJavaScript(code, options = {}) {
5299
7303
  seed,
5300
7304
  minStringLength,
5301
7305
  hotExemptNodes,
5302
- options.config,
7306
+ effectiveConfig,
5303
7307
  sym,
5304
7308
  shieldDelta,
5305
7309
  deterrentMode,
@@ -5318,7 +7322,7 @@ function transformJavaScript(code, options = {}) {
5318
7322
  sym,
5319
7323
  shieldDelta,
5320
7324
  deterrentMode,
5321
- options.config,
7325
+ effectiveConfig,
5322
7326
  shieldCoupled,
5323
7327
  detectHeadless,
5324
7328
  boundary.exemptSubtreeRoots
@@ -5327,7 +7331,22 @@ function transformJavaScript(code, options = {}) {
5327
7331
  integrityToken = vaultRes.integrityToken;
5328
7332
  shaderBuffersCount = vaultRes.shaderBuffersCount ?? 0;
5329
7333
  }
5330
- const outputCode = generateCompactJs(ast);
7334
+ const wantMap = Boolean(internalOptions.generateMap || options.map);
7335
+ let outputCode;
7336
+ let generatedMap;
7337
+ if (wantMap) {
7338
+ const mapped = generateCompactJsWithMap(ast, options.filename);
7339
+ outputCode = mapped.code;
7340
+ generatedMap = {
7341
+ version: 3,
7342
+ ...options.filename ? { file: options.filename } : {},
7343
+ sources: mapped.sources,
7344
+ names: mapped.names,
7345
+ mappings: mapped.mappings
7346
+ };
7347
+ } else {
7348
+ outputCode = generateCompactJs(ast);
7349
+ }
5331
7350
  let finalCode = outputCode;
5332
7351
  if (internalOptions.injectRuntimeShield && !internalOptions.skipShieldPreamble) {
5333
7352
  const shield = generateRuntimeShield({
@@ -5341,6 +7360,10 @@ function transformJavaScript(code, options = {}) {
5341
7360
  if (shield.preambleCode) {
5342
7361
  finalCode = `${shield.preambleCode}
5343
7362
  ${finalCode}`;
7363
+ if (generatedMap && generatedMap.mappings) {
7364
+ const preambleLines = shield.preambleCode.split("\n").length;
7365
+ generatedMap.mappings = ";".repeat(preambleLines) + generatedMap.mappings;
7366
+ }
5344
7367
  }
5345
7368
  }
5346
7369
  const finalResult = {
@@ -5350,7 +7373,8 @@ ${finalCode}`;
5350
7373
  hotPathReport,
5351
7374
  integrityToken,
5352
7375
  virtualizedFunctionsCount,
5353
- shaderBuffersCount
7376
+ shaderBuffersCount,
7377
+ ...generatedMap ? { sourceMap: generatedMap } : {}
5354
7378
  };
5355
7379
  return finalResult;
5356
7380
  }