@mondaydotcomorg/atp-compiler 0.19.8 → 0.19.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2947 @@
1
+ 'use strict';
2
+
3
+ var parser = require('@babel/parser');
4
+ var _traverse = require('@babel/traverse');
5
+ var _generate = require('@babel/generator');
6
+ var t7 = require('@babel/types');
7
+ var atpRuntime = require('@mondaydotcomorg/atp-runtime');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var _traverse__default = /*#__PURE__*/_interopDefault(_traverse);
30
+ var _generate__default = /*#__PURE__*/_interopDefault(_generate);
31
+ var t7__namespace = /*#__PURE__*/_interopNamespace(t7);
32
+
33
+ var __defProp = Object.defineProperty;
34
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
35
+
36
+ // src/types.ts
37
+ var PAUSABLE_CALL_PATTERNS = [
38
+ {
39
+ namespace: "atp.llm",
40
+ method: "call"
41
+ },
42
+ {
43
+ namespace: "atp.llm",
44
+ method: "extract"
45
+ },
46
+ {
47
+ namespace: "atp.llm",
48
+ method: "classify"
49
+ },
50
+ {
51
+ namespace: "atp.llm",
52
+ method: "stream"
53
+ },
54
+ {
55
+ namespace: "atp.llm",
56
+ method: "generate"
57
+ },
58
+ {
59
+ namespace: "atp.approval",
60
+ method: "request"
61
+ },
62
+ {
63
+ namespace: "atp.approval",
64
+ method: "confirm"
65
+ },
66
+ {
67
+ namespace: "atp.approval",
68
+ method: "verify"
69
+ },
70
+ {
71
+ namespace: "atp.embedding",
72
+ method: "embed"
73
+ },
74
+ {
75
+ namespace: "atp.embedding",
76
+ method: "search"
77
+ },
78
+ {
79
+ namespace: "atp.embedding",
80
+ method: "create"
81
+ },
82
+ {
83
+ namespace: "atp.embedding",
84
+ method: "generate"
85
+ },
86
+ {
87
+ namespace: "atp.embedding",
88
+ method: "encode"
89
+ }
90
+ ];
91
+ var DEFAULT_COMPILER_CONFIG = {
92
+ enableBatchParallel: true,
93
+ maxLoopNesting: 10,
94
+ checkpointInterval: 1,
95
+ debugMode: false,
96
+ batchSizeThreshold: 10
97
+ };
98
+ function isPausableCall(node) {
99
+ if (!t7__namespace.isAwaitExpression(node)) {
100
+ return false;
101
+ }
102
+ const argument = node.argument;
103
+ if (!t7__namespace.isCallExpression(argument)) {
104
+ return false;
105
+ }
106
+ return isPausableCallExpression(argument);
107
+ }
108
+ __name(isPausableCall, "isPausableCall");
109
+ function isPausableCallExpression(node) {
110
+ const callee = node.callee;
111
+ if (!t7__namespace.isMemberExpression(callee)) {
112
+ return false;
113
+ }
114
+ const fullPath = getMemberExpressionPath(callee);
115
+ return PAUSABLE_CALL_PATTERNS.some((pattern) => fullPath === `${pattern.namespace}.${pattern.method}`);
116
+ }
117
+ __name(isPausableCallExpression, "isPausableCallExpression");
118
+ function getMemberExpressionPath(node) {
119
+ const parts = [];
120
+ let current = node;
121
+ while (t7__namespace.isMemberExpression(current)) {
122
+ if (t7__namespace.isIdentifier(current.property)) {
123
+ parts.unshift(current.property.name);
124
+ }
125
+ current = current.object;
126
+ }
127
+ if (t7__namespace.isIdentifier(current)) {
128
+ parts.unshift(current.name);
129
+ }
130
+ return parts.join(".");
131
+ }
132
+ __name(getMemberExpressionPath, "getMemberExpressionPath");
133
+ function containsAwait(node) {
134
+ let hasAwait = false;
135
+ const checkNode = /* @__PURE__ */ __name((n) => {
136
+ if (t7__namespace.isAwaitExpression(n)) {
137
+ hasAwait = true;
138
+ return;
139
+ }
140
+ if (hasAwait) return;
141
+ Object.keys(n).forEach((key) => {
142
+ const value = n[key];
143
+ if (Array.isArray(value)) {
144
+ value.forEach((item) => {
145
+ if (item && typeof item === "object" && item.type) {
146
+ checkNode(item);
147
+ }
148
+ });
149
+ } else if (value && typeof value === "object" && value.type) {
150
+ checkNode(value);
151
+ }
152
+ });
153
+ }, "checkNode");
154
+ checkNode(node);
155
+ return hasAwait;
156
+ }
157
+ __name(containsAwait, "containsAwait");
158
+ function containsPausableCall(node) {
159
+ let hasPausable = false;
160
+ const checkNode = /* @__PURE__ */ __name((n) => {
161
+ if (t7__namespace.isAwaitExpression(n) && isPausableCall(n)) {
162
+ hasPausable = true;
163
+ return;
164
+ }
165
+ if (hasPausable) return;
166
+ Object.keys(n).forEach((key) => {
167
+ const value = n[key];
168
+ if (Array.isArray(value)) {
169
+ value.forEach((item) => {
170
+ if (item && typeof item === "object" && item.type) {
171
+ checkNode(item);
172
+ }
173
+ });
174
+ } else if (value && typeof value === "object" && value.type) {
175
+ checkNode(value);
176
+ }
177
+ });
178
+ }, "checkNode");
179
+ checkNode(node);
180
+ return hasPausable;
181
+ }
182
+ __name(containsPausableCall, "containsPausableCall");
183
+ function isAsyncFunction(node) {
184
+ return (t7__namespace.isFunctionDeclaration(node) || t7__namespace.isFunctionExpression(node) || t7__namespace.isArrowFunctionExpression(node)) && node.async === true;
185
+ }
186
+ __name(isAsyncFunction, "isAsyncFunction");
187
+ function getNodeLocation(node) {
188
+ if (node.loc) {
189
+ return {
190
+ line: node.loc.start.line,
191
+ column: node.loc.start.column
192
+ };
193
+ }
194
+ return void 0;
195
+ }
196
+ __name(getNodeLocation, "getNodeLocation");
197
+ function createRuntimeCall(fnName, args) {
198
+ return t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier(fnName)), args));
199
+ }
200
+ __name(createRuntimeCall, "createRuntimeCall");
201
+ function wrapInAsyncFunction(body) {
202
+ return t7__namespace.functionExpression(null, [], t7__namespace.blockStatement(body), false, true);
203
+ }
204
+ __name(wrapInAsyncFunction, "wrapInAsyncFunction");
205
+ function isArrayMethod(node, methodName) {
206
+ if (!t7__namespace.isCallExpression(node)) {
207
+ return false;
208
+ }
209
+ const callee = node.callee;
210
+ if (!t7__namespace.isMemberExpression(callee)) {
211
+ return false;
212
+ }
213
+ return t7__namespace.isIdentifier(callee.property) && callee.property.name === methodName;
214
+ }
215
+ __name(isArrayMethod, "isArrayMethod");
216
+ function extractForOfParamName(left) {
217
+ if (t7__namespace.isVariableDeclaration(left)) {
218
+ const id = left.declarations[0]?.id;
219
+ return t7__namespace.isIdentifier(id) ? id.name : "item";
220
+ } else if (t7__namespace.isIdentifier(left)) {
221
+ return left.name;
222
+ } else {
223
+ return "item";
224
+ }
225
+ }
226
+ __name(extractForOfParamName, "extractForOfParamName");
227
+
228
+ // src/transformer/detector.ts
229
+ var traverse = typeof _traverse__default.default.default === "function" ? _traverse__default.default.default : _traverse__default.default;
230
+ var AsyncIterationDetector = class {
231
+ static {
232
+ __name(this, "AsyncIterationDetector");
233
+ }
234
+ detect(code) {
235
+ const patterns = [];
236
+ let batchableParallel = false;
237
+ try {
238
+ const ast = parser.parse(code, {
239
+ sourceType: "module",
240
+ plugins: [
241
+ "typescript"
242
+ ],
243
+ allowAwaitOutsideFunction: true,
244
+ allowReturnOutsideFunction: true
245
+ });
246
+ traverse(ast, {
247
+ ForOfStatement: /* @__PURE__ */ __name((path) => {
248
+ if (containsAwait(path.node.body)) {
249
+ patterns.push("for-of-await");
250
+ }
251
+ }, "ForOfStatement"),
252
+ WhileStatement: /* @__PURE__ */ __name((path) => {
253
+ if (containsAwait(path.node.body)) {
254
+ patterns.push("while-await");
255
+ }
256
+ }, "WhileStatement"),
257
+ CallExpression: /* @__PURE__ */ __name((path) => {
258
+ const node = path.node;
259
+ if (isArrayMethod(node, "map")) {
260
+ const callback = node.arguments[0];
261
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
262
+ patterns.push("map-async");
263
+ }
264
+ }
265
+ if (isArrayMethod(node, "forEach")) {
266
+ const callback = node.arguments[0];
267
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
268
+ patterns.push("forEach-async");
269
+ }
270
+ }
271
+ if (isArrayMethod(node, "filter")) {
272
+ const callback = node.arguments[0];
273
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
274
+ patterns.push("filter-async");
275
+ }
276
+ }
277
+ if (isArrayMethod(node, "reduce")) {
278
+ const callback = node.arguments[0];
279
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
280
+ patterns.push("reduce-async");
281
+ }
282
+ }
283
+ if (isArrayMethod(node, "find")) {
284
+ const callback = node.arguments[0];
285
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
286
+ patterns.push("find-async");
287
+ }
288
+ }
289
+ if (isArrayMethod(node, "some")) {
290
+ const callback = node.arguments[0];
291
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
292
+ patterns.push("some-async");
293
+ }
294
+ }
295
+ if (isArrayMethod(node, "every")) {
296
+ const callback = node.arguments[0];
297
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
298
+ patterns.push("every-async");
299
+ }
300
+ }
301
+ if (isArrayMethod(node, "flatMap")) {
302
+ const callback = node.arguments[0];
303
+ if (callback && t7__namespace.isFunction(callback) && callback.async) {
304
+ patterns.push("flatMap-async");
305
+ }
306
+ }
307
+ if (this.isPromiseAll(node)) {
308
+ patterns.push("promise-all");
309
+ if (this.canBatchPromiseAll(node)) {
310
+ batchableParallel = true;
311
+ }
312
+ }
313
+ if (this.isPromiseAllSettled(node)) {
314
+ patterns.push("promise-allSettled");
315
+ }
316
+ }, "CallExpression")
317
+ });
318
+ return {
319
+ needsTransform: patterns.length > 0,
320
+ patterns: [
321
+ ...new Set(patterns)
322
+ ],
323
+ batchableParallel
324
+ };
325
+ } catch (error) {
326
+ return {
327
+ needsTransform: false,
328
+ patterns: [],
329
+ batchableParallel: false
330
+ };
331
+ }
332
+ }
333
+ isPromiseAll(node) {
334
+ const callee = node.callee;
335
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
336
+ name: "Promise"
337
+ }) && t7__namespace.isIdentifier(callee.property, {
338
+ name: "all"
339
+ });
340
+ }
341
+ isPromiseAllSettled(node) {
342
+ const callee = node.callee;
343
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
344
+ name: "Promise"
345
+ }) && t7__namespace.isIdentifier(callee.property, {
346
+ name: "allSettled"
347
+ });
348
+ }
349
+ canBatchPromiseAll(node) {
350
+ const arrayArg = node.arguments[0];
351
+ if (!t7__namespace.isArrayExpression(arrayArg)) {
352
+ return false;
353
+ }
354
+ if (arrayArg.elements.length === 0) {
355
+ return false;
356
+ }
357
+ return arrayArg.elements.every((el) => {
358
+ if (!el || t7__namespace.isSpreadElement(el)) {
359
+ return false;
360
+ }
361
+ return this.isDirectPausableCall(el);
362
+ });
363
+ }
364
+ isDirectPausableCall(node) {
365
+ if (t7__namespace.isAwaitExpression(node)) {
366
+ node = node.argument;
367
+ }
368
+ if (!t7__namespace.isCallExpression(node)) {
369
+ return false;
370
+ }
371
+ return isPausableCallExpression(node);
372
+ }
373
+ };
374
+
375
+ // src/runtime/context.ts
376
+ var contextStack = [];
377
+ function setRuntimeContext(context) {
378
+ contextStack.push(context);
379
+ }
380
+ __name(setRuntimeContext, "setRuntimeContext");
381
+ function getRuntimeContext() {
382
+ const context = contextStack[contextStack.length - 1];
383
+ if (!context) {
384
+ throw new Error("No runtime context available. Compiler runtime not properly initialized.");
385
+ }
386
+ return context;
387
+ }
388
+ __name(getRuntimeContext, "getRuntimeContext");
389
+ function clearRuntimeContext() {
390
+ contextStack.pop();
391
+ }
392
+ __name(clearRuntimeContext, "clearRuntimeContext");
393
+ function hasRuntimeContext() {
394
+ return contextStack.length > 0;
395
+ }
396
+ __name(hasRuntimeContext, "hasRuntimeContext");
397
+ var idCounter = 0;
398
+ function generateUniqueId(prefix) {
399
+ return `${prefix}_${Date.now()}_${idCounter++}`;
400
+ }
401
+ __name(generateUniqueId, "generateUniqueId");
402
+ function resetIdCounter() {
403
+ idCounter = 0;
404
+ }
405
+ __name(resetIdCounter, "resetIdCounter");
406
+ var BatchOptimizer = class {
407
+ static {
408
+ __name(this, "BatchOptimizer");
409
+ }
410
+ arrayMethodsWithEarlyExit = [
411
+ "find",
412
+ "some",
413
+ "every"
414
+ ];
415
+ canBatchArrayMethod(callback) {
416
+ if (!callback.async) {
417
+ return {
418
+ canBatch: false,
419
+ reason: "Not async"
420
+ };
421
+ }
422
+ const body = callback.body;
423
+ if (!t7__namespace.isBlockStatement(body)) {
424
+ if (t7__namespace.isAwaitExpression(body)) {
425
+ if (this.isDirectPausableCall(body.argument)) {
426
+ return {
427
+ canBatch: true,
428
+ llmCallPattern: "single",
429
+ hasConditionals: false
430
+ };
431
+ }
432
+ }
433
+ return {
434
+ canBatch: false,
435
+ reason: "Non-block body without direct call"
436
+ };
437
+ }
438
+ const statements = body.body;
439
+ if (statements.length === 0) {
440
+ return {
441
+ canBatch: false,
442
+ reason: "Empty body"
443
+ };
444
+ }
445
+ let hasConditionals = false;
446
+ let hasLoops = false;
447
+ let hasTryCatch = false;
448
+ for (const stmt of statements) {
449
+ if (t7__namespace.isIfStatement(stmt) || t7__namespace.isSwitchStatement(stmt)) {
450
+ hasConditionals = true;
451
+ }
452
+ if (t7__namespace.isTryStatement(stmt)) {
453
+ hasTryCatch = true;
454
+ }
455
+ if (t7__namespace.isForStatement(stmt) || t7__namespace.isForOfStatement(stmt) || t7__namespace.isForInStatement(stmt) || t7__namespace.isWhileStatement(stmt) || t7__namespace.isDoWhileStatement(stmt)) {
456
+ hasLoops = true;
457
+ }
458
+ if (t7__namespace.isBreakStatement(stmt) || t7__namespace.isContinueStatement(stmt)) {
459
+ return {
460
+ canBatch: false,
461
+ reason: "Contains break/continue"
462
+ };
463
+ }
464
+ if (t7__namespace.isReturnStatement(stmt) && stmt !== statements[statements.length - 1]) {
465
+ return {
466
+ canBatch: false,
467
+ reason: "Early return"
468
+ };
469
+ }
470
+ }
471
+ if (hasLoops) {
472
+ return {
473
+ canBatch: false,
474
+ reason: "Contains loops",
475
+ hasLoops: true
476
+ };
477
+ }
478
+ if (hasTryCatch) {
479
+ return {
480
+ canBatch: false,
481
+ reason: "Contains try-catch"
482
+ };
483
+ }
484
+ const pausableCalls = this.countPausableCalls(body);
485
+ if (pausableCalls === 0) {
486
+ return {
487
+ canBatch: false,
488
+ reason: "No pausable calls"
489
+ };
490
+ }
491
+ if (pausableCalls > 1) {
492
+ return {
493
+ canBatch: false,
494
+ reason: "Multiple pausable calls",
495
+ llmCallPattern: "multiple"
496
+ };
497
+ }
498
+ if (hasConditionals) {
499
+ return {
500
+ canBatch: true,
501
+ llmCallPattern: "conditional",
502
+ hasConditionals: true,
503
+ reason: "Simple conditional - can batch but consider array size"
504
+ };
505
+ }
506
+ return {
507
+ canBatch: true,
508
+ llmCallPattern: "single",
509
+ hasConditionals: false
510
+ };
511
+ }
512
+ /**
513
+ * Smart decision: Should we batch based on array size and method type?
514
+ */
515
+ makeSmartBatchDecision(methodName, batchResult, arrayNode, threshold = 10) {
516
+ if (!batchResult.canBatch) {
517
+ return {
518
+ shouldBatch: false,
519
+ reason: "Complex callback - use sequential",
520
+ strategy: "never-batch"
521
+ };
522
+ }
523
+ if (!batchResult.hasConditionals) {
524
+ return {
525
+ shouldBatch: true,
526
+ reason: "Simple callback - batching is faster",
527
+ strategy: "always-batch"
528
+ };
529
+ }
530
+ const hasEarlyExitBenefit = this.arrayMethodsWithEarlyExit.includes(methodName);
531
+ if (!hasEarlyExitBenefit) {
532
+ const arraySize2 = this.estimateArraySize(arrayNode);
533
+ if (arraySize2 !== null && arraySize2 < threshold) {
534
+ return {
535
+ shouldBatch: true,
536
+ reason: `Small array (${arraySize2} < ${threshold}) - batch despite conditionals`,
537
+ strategy: "size-dependent"
538
+ };
539
+ }
540
+ return {
541
+ shouldBatch: false,
542
+ reason: "Conditionals + large/unknown array - sequential for safety",
543
+ strategy: "size-dependent"
544
+ };
545
+ }
546
+ const arraySize = this.estimateArraySize(arrayNode);
547
+ if (arraySize !== null && arraySize < threshold) {
548
+ return {
549
+ shouldBatch: true,
550
+ reason: `Small array (${arraySize} < ${threshold}) - batch for speed`,
551
+ strategy: "size-dependent"
552
+ };
553
+ }
554
+ if (arraySize !== null && arraySize >= threshold) {
555
+ return {
556
+ shouldBatch: false,
557
+ reason: `Large array (${arraySize} >= ${threshold}) + conditionals - sequential for early-exit savings`,
558
+ strategy: "size-dependent"
559
+ };
560
+ }
561
+ if (t7__namespace.isArrayExpression(arrayNode)) {
562
+ return {
563
+ shouldBatch: true,
564
+ reason: "Array literal (likely small) - batch",
565
+ strategy: "size-dependent"
566
+ };
567
+ }
568
+ return {
569
+ shouldBatch: false,
570
+ reason: "Unknown array size + conditionals - sequential for safety",
571
+ strategy: "size-dependent"
572
+ };
573
+ }
574
+ estimateArraySize(arrayNode) {
575
+ if (t7__namespace.isArrayExpression(arrayNode)) {
576
+ return arrayNode.elements.length;
577
+ }
578
+ return null;
579
+ }
580
+ canBatchForOfLoop(loopNode) {
581
+ const body = loopNode.body;
582
+ if (!t7__namespace.isBlockStatement(body)) {
583
+ return {
584
+ canBatch: false,
585
+ reason: "Loop body not a block"
586
+ };
587
+ }
588
+ const statements = body.body;
589
+ if (statements.length === 0) {
590
+ return {
591
+ canBatch: false,
592
+ reason: "Empty loop body"
593
+ };
594
+ }
595
+ const hasBreakOrContinue = this.containsBreakOrContinue(body);
596
+ if (hasBreakOrContinue) {
597
+ return {
598
+ canBatch: false,
599
+ reason: "Contains break/continue"
600
+ };
601
+ }
602
+ let hasConditionals = false;
603
+ for (const stmt of statements) {
604
+ if (t7__namespace.isIfStatement(stmt) || t7__namespace.isSwitchStatement(stmt)) {
605
+ hasConditionals = true;
606
+ }
607
+ if (t7__namespace.isForStatement(stmt) || t7__namespace.isForOfStatement(stmt) || t7__namespace.isForInStatement(stmt) || t7__namespace.isWhileStatement(stmt) || t7__namespace.isDoWhileStatement(stmt)) {
608
+ return {
609
+ canBatch: false,
610
+ reason: "Contains nested loops",
611
+ hasLoops: true
612
+ };
613
+ }
614
+ }
615
+ const pausableCalls = this.countPausableCalls(body);
616
+ if (pausableCalls === 0) {
617
+ return {
618
+ canBatch: false,
619
+ reason: "No pausable calls"
620
+ };
621
+ }
622
+ if (pausableCalls > 1) {
623
+ return {
624
+ canBatch: false,
625
+ reason: "Multiple pausable calls",
626
+ llmCallPattern: "multiple"
627
+ };
628
+ }
629
+ if (hasConditionals) {
630
+ return {
631
+ canBatch: true,
632
+ llmCallPattern: "conditional",
633
+ hasConditionals: true,
634
+ reason: "Simple conditional - can batch but consider array size"
635
+ };
636
+ }
637
+ return {
638
+ canBatch: true,
639
+ llmCallPattern: "single",
640
+ hasConditionals: false
641
+ };
642
+ }
643
+ containsBreakOrContinue(node) {
644
+ let found = false;
645
+ const visit = /* @__PURE__ */ __name((n) => {
646
+ if (found) return;
647
+ if (t7__namespace.isBreakStatement(n) || t7__namespace.isContinueStatement(n)) {
648
+ found = true;
649
+ return;
650
+ }
651
+ if (t7__namespace.isForStatement(n) || t7__namespace.isForOfStatement(n) || t7__namespace.isForInStatement(n) || t7__namespace.isWhileStatement(n) || t7__namespace.isDoWhileStatement(n)) {
652
+ return;
653
+ }
654
+ Object.keys(n).forEach((key) => {
655
+ const value = n[key];
656
+ if (Array.isArray(value)) {
657
+ value.forEach((item) => {
658
+ if (item && typeof item === "object" && item.type) {
659
+ visit(item);
660
+ }
661
+ });
662
+ } else if (value && typeof value === "object" && value.type) {
663
+ visit(value);
664
+ }
665
+ });
666
+ }, "visit");
667
+ visit(node);
668
+ return found;
669
+ }
670
+ isDirectPausableCall(node) {
671
+ if (!t7__namespace.isCallExpression(node)) {
672
+ return false;
673
+ }
674
+ return isPausableCallExpression(node);
675
+ }
676
+ countPausableCalls(body) {
677
+ let count = 0;
678
+ const visit = /* @__PURE__ */ __name((node) => {
679
+ if (t7__namespace.isAwaitExpression(node) && this.isDirectPausableCall(node.argument)) {
680
+ count++;
681
+ return;
682
+ }
683
+ Object.keys(node).forEach((key) => {
684
+ const value = node[key];
685
+ if (Array.isArray(value)) {
686
+ value.forEach((item) => {
687
+ if (item && typeof item === "object" && item.type) {
688
+ visit(item);
689
+ }
690
+ });
691
+ } else if (value && typeof value === "object" && value.type) {
692
+ visit(value);
693
+ }
694
+ });
695
+ }, "visit");
696
+ visit(body);
697
+ return count;
698
+ }
699
+ };
700
+ var BatchParallelDetector = class {
701
+ static {
702
+ __name(this, "BatchParallelDetector");
703
+ }
704
+ canBatch(promiseAllNode) {
705
+ const arrayArg = promiseAllNode.arguments[0];
706
+ if (!t7__namespace.isArrayExpression(arrayArg)) {
707
+ return false;
708
+ }
709
+ if (arrayArg.elements.length === 0) {
710
+ return false;
711
+ }
712
+ return arrayArg.elements.every((el) => {
713
+ if (!el || t7__namespace.isSpreadElement(el)) {
714
+ return false;
715
+ }
716
+ return this.isDirectPausableCall(el);
717
+ });
718
+ }
719
+ isDirectPausableCall(node) {
720
+ if (t7__namespace.isAwaitExpression(node)) {
721
+ node = node.argument;
722
+ }
723
+ if (!t7__namespace.isCallExpression(node)) {
724
+ return false;
725
+ }
726
+ return isPausableCallExpression(node);
727
+ }
728
+ extractBatchCalls(arrayNode) {
729
+ const calls = [];
730
+ for (const el of arrayNode.elements) {
731
+ if (!el || t7__namespace.isSpreadElement(el)) {
732
+ continue;
733
+ }
734
+ let callNode = el;
735
+ if (t7__namespace.isAwaitExpression(callNode)) {
736
+ callNode = callNode.argument;
737
+ }
738
+ if (!t7__namespace.isCallExpression(callNode)) {
739
+ continue;
740
+ }
741
+ const callInfo = this.extractCallInfo(callNode);
742
+ if (callInfo) {
743
+ calls.push(callInfo);
744
+ }
745
+ }
746
+ return calls;
747
+ }
748
+ extractCallInfo(callNode) {
749
+ if (!t7__namespace.isMemberExpression(callNode.callee)) {
750
+ return null;
751
+ }
752
+ const path = getMemberExpressionPath(callNode.callee);
753
+ const parts = path.split(".");
754
+ if (parts.length < 3) {
755
+ return null;
756
+ }
757
+ const [namespace, service, method] = parts;
758
+ if (namespace !== "atp" || !method) {
759
+ return null;
760
+ }
761
+ const type = service;
762
+ const payload = this.extractPayload(callNode.arguments);
763
+ return {
764
+ type,
765
+ operation: method,
766
+ payload
767
+ };
768
+ }
769
+ /**
770
+ * Extract payload AST node directly
771
+ */
772
+ extractPayloadNode(callNode) {
773
+ if (callNode.arguments.length === 0) {
774
+ return t7__namespace.objectExpression([]);
775
+ }
776
+ const firstArg = callNode.arguments[0];
777
+ if (!firstArg || t7__namespace.isSpreadElement(firstArg) || !t7__namespace.isExpression(firstArg)) {
778
+ return null;
779
+ }
780
+ return firstArg;
781
+ }
782
+ extractPayload(args) {
783
+ if (args.length === 0) {
784
+ return {};
785
+ }
786
+ const firstArg = args[0];
787
+ if (t7__namespace.isSpreadElement(firstArg)) {
788
+ return {};
789
+ }
790
+ if (t7__namespace.isObjectExpression(firstArg)) {
791
+ return this.objectExpressionToRecord(firstArg);
792
+ }
793
+ if (t7__namespace.isStringLiteral(firstArg)) {
794
+ return {
795
+ message: firstArg.value
796
+ };
797
+ }
798
+ return {};
799
+ }
800
+ objectExpressionToRecord(obj) {
801
+ const record = {};
802
+ for (const prop of obj.properties) {
803
+ if (t7__namespace.isObjectProperty(prop) && !prop.computed) {
804
+ const key = t7__namespace.isIdentifier(prop.key) ? prop.key.name : String(prop.key);
805
+ const value = this.extractValue(prop.value);
806
+ record[key] = value;
807
+ }
808
+ }
809
+ return record;
810
+ }
811
+ extractValue(node) {
812
+ if (t7__namespace.isStringLiteral(node)) {
813
+ return node.value;
814
+ }
815
+ if (t7__namespace.isNumericLiteral(node)) {
816
+ return node.value;
817
+ }
818
+ if (t7__namespace.isBooleanLiteral(node)) {
819
+ return node.value;
820
+ }
821
+ if (t7__namespace.isNullLiteral(node)) {
822
+ return null;
823
+ }
824
+ if (t7__namespace.isArrayExpression(node)) {
825
+ return node.elements.map((el) => el && !t7__namespace.isSpreadElement(el) ? this.extractValue(el) : null);
826
+ }
827
+ if (t7__namespace.isObjectExpression(node)) {
828
+ return this.objectExpressionToRecord(node);
829
+ }
830
+ return void 0;
831
+ }
832
+ };
833
+ function findLLMCallExpression(body) {
834
+ let found = null;
835
+ const visit = /* @__PURE__ */ __name((node) => {
836
+ if (found) return;
837
+ if (t7__namespace.isAwaitExpression(node) && t7__namespace.isCallExpression(node.argument)) {
838
+ const call = node.argument;
839
+ if (t7__namespace.isMemberExpression(call.callee)) {
840
+ found = call;
841
+ return;
842
+ }
843
+ }
844
+ Object.keys(node).forEach((key) => {
845
+ const value = node[key];
846
+ if (Array.isArray(value)) {
847
+ value.forEach((item) => {
848
+ if (item && typeof item === "object" && item.type) {
849
+ visit(item);
850
+ }
851
+ });
852
+ } else if (value && typeof value === "object" && value.type) {
853
+ visit(value);
854
+ }
855
+ });
856
+ }, "visit");
857
+ visit(body);
858
+ return found;
859
+ }
860
+ __name(findLLMCallExpression, "findLLMCallExpression");
861
+ function getArrayMethodName(node) {
862
+ const arrayMethods = [
863
+ "map",
864
+ "forEach",
865
+ "filter",
866
+ "reduce",
867
+ "find",
868
+ "some",
869
+ "every",
870
+ "flatMap"
871
+ ];
872
+ for (const method of arrayMethods) {
873
+ if (isArrayMethod(node, method)) {
874
+ return method;
875
+ }
876
+ }
877
+ return null;
878
+ }
879
+ __name(getArrayMethodName, "getArrayMethodName");
880
+ function getRuntimeMethodName(arrayMethod) {
881
+ const mapping = {
882
+ map: "resumableMap",
883
+ forEach: "resumableForEach",
884
+ filter: "resumableFilter",
885
+ reduce: "resumableReduce",
886
+ find: "resumableFind",
887
+ some: "resumableSome",
888
+ every: "resumableEvery",
889
+ flatMap: "resumableFlatMap"
890
+ };
891
+ return mapping[arrayMethod] || null;
892
+ }
893
+ __name(getRuntimeMethodName, "getRuntimeMethodName");
894
+ function canUseBatchParallel(methodName) {
895
+ return [
896
+ "map",
897
+ "forEach",
898
+ "filter",
899
+ "find",
900
+ "some",
901
+ "every"
902
+ ].includes(methodName);
903
+ }
904
+ __name(canUseBatchParallel, "canUseBatchParallel");
905
+
906
+ // src/transformer/loop-transformer.ts
907
+ var LoopTransformer = class {
908
+ static {
909
+ __name(this, "LoopTransformer");
910
+ }
911
+ transformCount = 0;
912
+ batchOptimizer;
913
+ batchDetector;
914
+ batchSizeThreshold;
915
+ constructor(batchSizeThreshold = 10) {
916
+ this.batchOptimizer = new BatchOptimizer();
917
+ this.batchDetector = new BatchParallelDetector();
918
+ this.batchSizeThreshold = batchSizeThreshold;
919
+ }
920
+ transformForOfLoop(path) {
921
+ const node = path.node;
922
+ if (!containsAwait(node.body)) {
923
+ return false;
924
+ }
925
+ const batchResult = this.batchOptimizer.canBatchForOfLoop(node);
926
+ if (batchResult.canBatch) {
927
+ const decision = this.batchOptimizer.makeSmartBatchDecision("for...of", batchResult, node.right, this.batchSizeThreshold);
928
+ if (decision.shouldBatch) {
929
+ return this.transformForOfToBatch(path, node);
930
+ }
931
+ }
932
+ return this.transformForOfToSequential(path, node);
933
+ }
934
+ /**
935
+ * Transform simple for...of to batch parallel
936
+ */
937
+ transformForOfToBatch(path, node) {
938
+ const loopId = generateUniqueId("for_of_batch");
939
+ const right = node.right;
940
+ const paramName = extractForOfParamName(node.left);
941
+ const llmCall = findLLMCallExpression(node.body);
942
+ if (!llmCall) {
943
+ return this.transformForOfToSequential(path, node);
944
+ }
945
+ const callInfo = this.batchDetector.extractCallInfo(llmCall);
946
+ if (!callInfo) {
947
+ return this.transformForOfToSequential(path, node);
948
+ }
949
+ const payloadNode = this.batchDetector.extractPayloadNode(llmCall);
950
+ if (!payloadNode) {
951
+ return this.transformForOfToSequential(path, node);
952
+ }
953
+ const batchCallsArray = t7__namespace.callExpression(t7__namespace.memberExpression(right, t7__namespace.identifier("map")), [
954
+ t7__namespace.arrowFunctionExpression([
955
+ t7__namespace.identifier(paramName)
956
+ ], t7__namespace.objectExpression([
957
+ t7__namespace.objectProperty(t7__namespace.identifier("type"), t7__namespace.stringLiteral(callInfo.type)),
958
+ t7__namespace.objectProperty(t7__namespace.identifier("operation"), t7__namespace.stringLiteral(callInfo.operation)),
959
+ t7__namespace.objectProperty(t7__namespace.identifier("payload"), payloadNode)
960
+ ]))
961
+ ]);
962
+ const batchCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier("batchParallel")), [
963
+ batchCallsArray,
964
+ t7__namespace.stringLiteral(loopId)
965
+ ]));
966
+ path.replaceWith(t7__namespace.expressionStatement(batchCall));
967
+ this.transformCount++;
968
+ return true;
969
+ }
970
+ /**
971
+ * Transform for...of to sequential with checkpoints (fallback)
972
+ */
973
+ transformForOfToSequential(path, node) {
974
+ const loopId = generateUniqueId("for_of");
975
+ const right = node.right;
976
+ const paramName = extractForOfParamName(node.left);
977
+ const bodyStatements = t7__namespace.isBlockStatement(node.body) ? node.body.body : [
978
+ node.body
979
+ ];
980
+ const callbackFn = t7__namespace.arrowFunctionExpression([
981
+ t7__namespace.identifier(paramName),
982
+ t7__namespace.identifier("__index")
983
+ ], t7__namespace.blockStatement(bodyStatements), true);
984
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier("resumableForOf")), [
985
+ right,
986
+ callbackFn,
987
+ t7__namespace.stringLiteral(loopId)
988
+ ]));
989
+ path.replaceWith(t7__namespace.expressionStatement(runtimeCall));
990
+ this.transformCount++;
991
+ return true;
992
+ }
993
+ transformWhileLoop(path) {
994
+ const node = path.node;
995
+ if (!containsAwait(node.body)) {
996
+ return false;
997
+ }
998
+ const loopId = generateUniqueId("while");
999
+ const conditionFn = t7__namespace.arrowFunctionExpression([], node.test, false);
1000
+ const bodyStatements = t7__namespace.isBlockStatement(node.body) ? node.body.body : [
1001
+ node.body
1002
+ ];
1003
+ const bodyFn = t7__namespace.arrowFunctionExpression([
1004
+ t7__namespace.identifier("__iteration")
1005
+ ], t7__namespace.blockStatement(bodyStatements), true);
1006
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier("resumableWhile")), [
1007
+ conditionFn,
1008
+ bodyFn,
1009
+ t7__namespace.stringLiteral(loopId)
1010
+ ]));
1011
+ path.replaceWith(t7__namespace.expressionStatement(runtimeCall));
1012
+ this.transformCount++;
1013
+ return true;
1014
+ }
1015
+ transformForLoop(path) {
1016
+ const node = path.node;
1017
+ if (!containsAwait(node.body)) {
1018
+ return false;
1019
+ }
1020
+ if (!node.init || !node.test || !node.update) {
1021
+ return false;
1022
+ }
1023
+ const loopId = generateUniqueId("for");
1024
+ let initValue = t7__namespace.numericLiteral(0);
1025
+ let loopVar = "__i";
1026
+ if (t7__namespace.isVariableDeclaration(node.init)) {
1027
+ const decl = node.init.declarations[0];
1028
+ if (decl && t7__namespace.isIdentifier(decl.id) && decl.init) {
1029
+ loopVar = decl.id.name;
1030
+ initValue = decl.init;
1031
+ }
1032
+ }
1033
+ const conditionFn = t7__namespace.arrowFunctionExpression([
1034
+ t7__namespace.identifier(loopVar)
1035
+ ], node.test, false);
1036
+ const bodyStatements = t7__namespace.isBlockStatement(node.body) ? node.body.body : [
1037
+ node.body
1038
+ ];
1039
+ const bodyFn = t7__namespace.arrowFunctionExpression([
1040
+ t7__namespace.identifier(loopVar)
1041
+ ], t7__namespace.blockStatement(bodyStatements), true);
1042
+ let incrementFn;
1043
+ if (t7__namespace.isUpdateExpression(node.update)) {
1044
+ if (node.update.operator === "++") {
1045
+ incrementFn = t7__namespace.arrowFunctionExpression([
1046
+ t7__namespace.identifier(loopVar)
1047
+ ], t7__namespace.binaryExpression("+", t7__namespace.identifier(loopVar), t7__namespace.numericLiteral(1)), false);
1048
+ } else if (node.update.operator === "--") {
1049
+ incrementFn = t7__namespace.arrowFunctionExpression([
1050
+ t7__namespace.identifier(loopVar)
1051
+ ], t7__namespace.binaryExpression("-", t7__namespace.identifier(loopVar), t7__namespace.numericLiteral(1)), false);
1052
+ } else {
1053
+ return false;
1054
+ }
1055
+ } else {
1056
+ return false;
1057
+ }
1058
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier("resumableForLoop")), [
1059
+ initValue,
1060
+ conditionFn,
1061
+ incrementFn,
1062
+ bodyFn,
1063
+ t7__namespace.stringLiteral(loopId)
1064
+ ]));
1065
+ path.replaceWith(t7__namespace.expressionStatement(runtimeCall));
1066
+ this.transformCount++;
1067
+ return true;
1068
+ }
1069
+ getTransformCount() {
1070
+ return this.transformCount;
1071
+ }
1072
+ resetTransformCount() {
1073
+ this.transformCount = 0;
1074
+ }
1075
+ };
1076
+ function wrapFilterResult(batchCall, array, methodId) {
1077
+ const resultsVar = `__filter_results_${methodId}`;
1078
+ const indexVar = `__i_${methodId}`;
1079
+ const arrayClone = t7__namespace.cloneNode(array, true);
1080
+ return t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.arrowFunctionExpression([], t7__namespace.blockStatement([
1081
+ t7__namespace.variableDeclaration("const", [
1082
+ t7__namespace.variableDeclarator(t7__namespace.identifier(resultsVar), batchCall.argument)
1083
+ ]),
1084
+ t7__namespace.returnStatement(t7__namespace.callExpression(t7__namespace.memberExpression(arrayClone, t7__namespace.identifier("filter")), [
1085
+ t7__namespace.arrowFunctionExpression([
1086
+ t7__namespace.identifier("_"),
1087
+ t7__namespace.identifier(indexVar)
1088
+ ], t7__namespace.callExpression(t7__namespace.identifier("Boolean"), [
1089
+ t7__namespace.memberExpression(t7__namespace.identifier(resultsVar), t7__namespace.identifier(indexVar), true)
1090
+ ]))
1091
+ ]))
1092
+ ]), true), []));
1093
+ }
1094
+ __name(wrapFilterResult, "wrapFilterResult");
1095
+ function wrapFindResult(batchCall, array, methodId) {
1096
+ const resultsVar = `__find_results_${methodId}`;
1097
+ const arrayClone = t7__namespace.cloneNode(array, true);
1098
+ return t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.arrowFunctionExpression([], t7__namespace.blockStatement([
1099
+ t7__namespace.variableDeclaration("const", [
1100
+ t7__namespace.variableDeclarator(t7__namespace.identifier(resultsVar), batchCall.argument)
1101
+ ]),
1102
+ t7__namespace.returnStatement(t7__namespace.callExpression(t7__namespace.memberExpression(arrayClone, t7__namespace.identifier("find")), [
1103
+ t7__namespace.arrowFunctionExpression([
1104
+ t7__namespace.identifier("_"),
1105
+ t7__namespace.identifier("__i")
1106
+ ], t7__namespace.callExpression(t7__namespace.identifier("Boolean"), [
1107
+ t7__namespace.memberExpression(t7__namespace.identifier(resultsVar), t7__namespace.identifier("__i"), true)
1108
+ ]))
1109
+ ]))
1110
+ ]), true), []));
1111
+ }
1112
+ __name(wrapFindResult, "wrapFindResult");
1113
+ function wrapSomeResult(batchCall, methodId) {
1114
+ const resultsVar = `__some_results_${methodId}`;
1115
+ return t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.arrowFunctionExpression([], t7__namespace.blockStatement([
1116
+ t7__namespace.variableDeclaration("const", [
1117
+ t7__namespace.variableDeclarator(t7__namespace.identifier(resultsVar), batchCall.argument)
1118
+ ]),
1119
+ t7__namespace.returnStatement(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier(resultsVar), t7__namespace.identifier("some")), [
1120
+ t7__namespace.arrowFunctionExpression([
1121
+ t7__namespace.identifier("r")
1122
+ ], t7__namespace.callExpression(t7__namespace.identifier("Boolean"), [
1123
+ t7__namespace.identifier("r")
1124
+ ]))
1125
+ ]))
1126
+ ]), true), []));
1127
+ }
1128
+ __name(wrapSomeResult, "wrapSomeResult");
1129
+ function wrapEveryResult(batchCall, methodId) {
1130
+ const resultsVar = `__every_results_${methodId}`;
1131
+ return t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.arrowFunctionExpression([], t7__namespace.blockStatement([
1132
+ t7__namespace.variableDeclaration("const", [
1133
+ t7__namespace.variableDeclarator(t7__namespace.identifier(resultsVar), batchCall.argument)
1134
+ ]),
1135
+ t7__namespace.returnStatement(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier(resultsVar), t7__namespace.identifier("every")), [
1136
+ t7__namespace.arrowFunctionExpression([
1137
+ t7__namespace.identifier("r")
1138
+ ], t7__namespace.callExpression(t7__namespace.identifier("Boolean"), [
1139
+ t7__namespace.identifier("r")
1140
+ ]))
1141
+ ]))
1142
+ ]), true), []));
1143
+ }
1144
+ __name(wrapEveryResult, "wrapEveryResult");
1145
+ function wrapBatchResultIfNeeded(batchCall, methodName, array, methodId) {
1146
+ switch (methodName) {
1147
+ case "filter":
1148
+ return wrapFilterResult(batchCall, array, methodId);
1149
+ case "find":
1150
+ return wrapFindResult(batchCall, array, methodId);
1151
+ case "some":
1152
+ return wrapSomeResult(batchCall, methodId);
1153
+ case "every":
1154
+ return wrapEveryResult(batchCall, methodId);
1155
+ case "forEach":
1156
+ return batchCall;
1157
+ default:
1158
+ return batchCall;
1159
+ }
1160
+ }
1161
+ __name(wrapBatchResultIfNeeded, "wrapBatchResultIfNeeded");
1162
+
1163
+ // src/transformer/array-transformer-batch.ts
1164
+ function extractBatchCallInfo(callback, batchDetector) {
1165
+ const paramName = callback.params[0];
1166
+ if (!t7__namespace.isIdentifier(paramName)) {
1167
+ return null;
1168
+ }
1169
+ const param = paramName.name;
1170
+ const llmCall = findLLMCallExpression(callback.body);
1171
+ if (!llmCall) {
1172
+ return null;
1173
+ }
1174
+ const callInfo = batchDetector.extractCallInfo(llmCall);
1175
+ if (!callInfo) {
1176
+ return null;
1177
+ }
1178
+ const payloadNode = batchDetector.extractPayloadNode(llmCall);
1179
+ if (!payloadNode) {
1180
+ return null;
1181
+ }
1182
+ const mapperFunction = t7__namespace.arrowFunctionExpression([
1183
+ t7__namespace.identifier(param)
1184
+ ], t7__namespace.objectExpression([
1185
+ t7__namespace.objectProperty(t7__namespace.identifier("type"), t7__namespace.stringLiteral(callInfo.type)),
1186
+ t7__namespace.objectProperty(t7__namespace.identifier("operation"), t7__namespace.stringLiteral(callInfo.operation)),
1187
+ t7__namespace.objectProperty(t7__namespace.identifier("payload"), payloadNode)
1188
+ ]));
1189
+ return {
1190
+ mapperFunction
1191
+ };
1192
+ }
1193
+ __name(extractBatchCallInfo, "extractBatchCallInfo");
1194
+ function transformToBatchParallel(path, node, methodName, callback, batchDetector, onTransform, fallbackTransform) {
1195
+ const methodId = generateUniqueId(`${methodName}_batch`);
1196
+ const array = node.callee.object;
1197
+ const callInfo = extractBatchCallInfo(callback, batchDetector);
1198
+ if (!callInfo) {
1199
+ return fallbackTransform();
1200
+ }
1201
+ const batchCallsArray = t7__namespace.callExpression(t7__namespace.memberExpression(array, t7__namespace.identifier("map")), [
1202
+ callInfo.mapperFunction
1203
+ ]);
1204
+ const batchCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier("batchParallel")), [
1205
+ batchCallsArray,
1206
+ t7__namespace.stringLiteral(methodId)
1207
+ ]));
1208
+ const finalCall = wrapBatchResultIfNeeded(batchCall, methodName, array, methodId);
1209
+ path.replaceWith(finalCall);
1210
+ onTransform();
1211
+ return true;
1212
+ }
1213
+ __name(transformToBatchParallel, "transformToBatchParallel");
1214
+ function transformToSequential(path, node, methodName, callback, onTransform) {
1215
+ const runtimeMethod = getRuntimeMethodName(methodName);
1216
+ if (!runtimeMethod) {
1217
+ return false;
1218
+ }
1219
+ const methodId = generateUniqueId(methodName);
1220
+ const array = node.callee.object;
1221
+ const args = [
1222
+ array,
1223
+ callback,
1224
+ t7__namespace.stringLiteral(methodId)
1225
+ ];
1226
+ if (methodName === "reduce" && node.arguments[1]) {
1227
+ args.push(node.arguments[1]);
1228
+ }
1229
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier(runtimeMethod)), args));
1230
+ path.replaceWith(runtimeCall);
1231
+ onTransform();
1232
+ return true;
1233
+ }
1234
+ __name(transformToSequential, "transformToSequential");
1235
+
1236
+ // src/transformer/array-transformer.ts
1237
+ var ArrayTransformer = class {
1238
+ static {
1239
+ __name(this, "ArrayTransformer");
1240
+ }
1241
+ transformCount = 0;
1242
+ batchOptimizer;
1243
+ batchDetector;
1244
+ batchSizeThreshold;
1245
+ constructor(batchSizeThreshold = 10) {
1246
+ this.batchOptimizer = new BatchOptimizer();
1247
+ this.batchDetector = new BatchParallelDetector();
1248
+ this.batchSizeThreshold = batchSizeThreshold;
1249
+ }
1250
+ transformArrayMethod(path) {
1251
+ const node = path.node;
1252
+ const methodName = getArrayMethodName(node);
1253
+ if (!methodName) {
1254
+ return false;
1255
+ }
1256
+ const callback = node.arguments[0];
1257
+ if (!callback || !t7__namespace.isFunction(callback) || !callback.async) {
1258
+ return false;
1259
+ }
1260
+ const batchResult = this.batchOptimizer.canBatchArrayMethod(callback);
1261
+ if (batchResult.canBatch && canUseBatchParallel(methodName)) {
1262
+ const array = node.callee.object;
1263
+ const decision = this.batchOptimizer.makeSmartBatchDecision(methodName, batchResult, array, this.batchSizeThreshold);
1264
+ if (decision.shouldBatch) {
1265
+ return transformToBatchParallel(path, node, methodName, callback, this.batchDetector, () => this.transformCount++, () => this.doTransformToSequential(path, node, methodName, callback));
1266
+ }
1267
+ }
1268
+ return this.doTransformToSequential(path, node, methodName, callback);
1269
+ }
1270
+ doTransformToSequential(path, node, methodName, callback) {
1271
+ return transformToSequential(path, node, methodName, callback, () => this.transformCount++);
1272
+ }
1273
+ getTransformCount() {
1274
+ return this.transformCount;
1275
+ }
1276
+ resetTransformCount() {
1277
+ this.transformCount = 0;
1278
+ }
1279
+ };
1280
+
1281
+ // src/runtime/runtime-functions.ts
1282
+ var RuntimeFunction = {
1283
+ // Promise operations
1284
+ RESUMABLE_PROMISE_ALL: "resumablePromiseAll",
1285
+ RESUMABLE_PROMISE_ALL_SETTLED: "resumablePromiseAllSettled",
1286
+ BATCH_PARALLEL: "batchParallel",
1287
+ // Loop operations
1288
+ RESUMABLE_FOR_OF: "resumableForOf",
1289
+ RESUMABLE_FOR_LOOP: "resumableForLoop",
1290
+ RESUMABLE_WHILE: "resumableWhile",
1291
+ // Array method operations
1292
+ RESUMABLE_MAP: "resumableMap",
1293
+ RESUMABLE_FOR_EACH: "resumableForEach",
1294
+ RESUMABLE_FILTER: "resumableFilter",
1295
+ RESUMABLE_REDUCE: "resumableReduce",
1296
+ RESUMABLE_FIND: "resumableFind",
1297
+ RESUMABLE_SOME: "resumableSome",
1298
+ RESUMABLE_EVERY: "resumableEvery",
1299
+ RESUMABLE_FLAT_MAP: "resumableFlatMap"
1300
+ };
1301
+ var IN_ISOLATE_RUNTIME_FUNCTIONS = [
1302
+ RuntimeFunction.RESUMABLE_PROMISE_ALL,
1303
+ RuntimeFunction.RESUMABLE_PROMISE_ALL_SETTLED,
1304
+ RuntimeFunction.RESUMABLE_FOR_OF,
1305
+ RuntimeFunction.RESUMABLE_FOR_LOOP,
1306
+ RuntimeFunction.RESUMABLE_WHILE,
1307
+ RuntimeFunction.RESUMABLE_MAP,
1308
+ RuntimeFunction.RESUMABLE_FOR_EACH,
1309
+ RuntimeFunction.RESUMABLE_FILTER,
1310
+ RuntimeFunction.RESUMABLE_REDUCE,
1311
+ RuntimeFunction.RESUMABLE_FIND,
1312
+ RuntimeFunction.RESUMABLE_SOME,
1313
+ RuntimeFunction.RESUMABLE_EVERY,
1314
+ RuntimeFunction.RESUMABLE_FLAT_MAP
1315
+ ];
1316
+ function isInIsolateRuntimeFunction(name) {
1317
+ return IN_ISOLATE_RUNTIME_FUNCTIONS.includes(name);
1318
+ }
1319
+ __name(isInIsolateRuntimeFunction, "isInIsolateRuntimeFunction");
1320
+
1321
+ // src/transformer/promise-transformer.ts
1322
+ var PromiseTransformer = class {
1323
+ static {
1324
+ __name(this, "PromiseTransformer");
1325
+ }
1326
+ transformCount = 0;
1327
+ batchDetector;
1328
+ enableBatchParallel;
1329
+ constructor(enableBatchParallel = true) {
1330
+ this.batchDetector = new BatchParallelDetector();
1331
+ this.enableBatchParallel = enableBatchParallel;
1332
+ }
1333
+ transformPromiseAll(path) {
1334
+ const node = path.node;
1335
+ if (!this.isPromiseAll(node)) {
1336
+ return false;
1337
+ }
1338
+ const arrayArg = node.arguments[0];
1339
+ if (this.enableBatchParallel && this.batchDetector.canBatch(node)) {
1340
+ return this.transformToBatchParallel(path, node);
1341
+ }
1342
+ if (t7__namespace.isArrayExpression(arrayArg)) {
1343
+ return this.transformToSequential(path, node);
1344
+ }
1345
+ return false;
1346
+ }
1347
+ transformPromiseAllSettled(path) {
1348
+ const node = path.node;
1349
+ if (!this.isPromiseAllSettled(node)) {
1350
+ return false;
1351
+ }
1352
+ const arrayArg = node.arguments[0];
1353
+ if (t7__namespace.isArrayExpression(arrayArg)) {
1354
+ const parallelId = generateUniqueId("allSettled");
1355
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier(RuntimeFunction.RESUMABLE_PROMISE_ALL_SETTLED)), [
1356
+ arrayArg,
1357
+ t7__namespace.stringLiteral(parallelId)
1358
+ ]));
1359
+ path.replaceWith(runtimeCall);
1360
+ this.transformCount++;
1361
+ return true;
1362
+ }
1363
+ return false;
1364
+ }
1365
+ transformToBatchParallel(path, node) {
1366
+ const arrayArg = node.arguments[0];
1367
+ if (!t7__namespace.isArrayExpression(arrayArg)) {
1368
+ return false;
1369
+ }
1370
+ const batchId = generateUniqueId("batch");
1371
+ const batchCallsArray = t7__namespace.arrayExpression(arrayArg.elements.map((el) => {
1372
+ if (!el || t7__namespace.isSpreadElement(el)) {
1373
+ return t7__namespace.nullLiteral();
1374
+ }
1375
+ let callNode = el;
1376
+ if (t7__namespace.isAwaitExpression(callNode)) {
1377
+ callNode = callNode.argument;
1378
+ }
1379
+ if (!t7__namespace.isCallExpression(callNode) || !t7__namespace.isMemberExpression(callNode.callee)) {
1380
+ return t7__namespace.nullLiteral();
1381
+ }
1382
+ const callInfo = this.batchDetector.extractCallInfo(callNode);
1383
+ if (!callInfo) {
1384
+ return t7__namespace.nullLiteral();
1385
+ }
1386
+ const payloadArg = callNode.arguments[0];
1387
+ return t7__namespace.objectExpression([
1388
+ t7__namespace.objectProperty(t7__namespace.identifier("type"), t7__namespace.stringLiteral(callInfo.type)),
1389
+ t7__namespace.objectProperty(t7__namespace.identifier("operation"), t7__namespace.stringLiteral(callInfo.operation)),
1390
+ t7__namespace.objectProperty(t7__namespace.identifier("payload"), payloadArg && t7__namespace.isExpression(payloadArg) ? payloadArg : t7__namespace.objectExpression([]))
1391
+ ]);
1392
+ }));
1393
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier(RuntimeFunction.BATCH_PARALLEL)), [
1394
+ batchCallsArray,
1395
+ t7__namespace.stringLiteral(batchId)
1396
+ ]));
1397
+ path.replaceWith(runtimeCall);
1398
+ this.transformCount++;
1399
+ return true;
1400
+ }
1401
+ transformToSequential(path, node) {
1402
+ const arrayArg = node.arguments[0];
1403
+ if (!t7__namespace.isArrayExpression(arrayArg)) {
1404
+ return false;
1405
+ }
1406
+ const parallelId = generateUniqueId("parallel");
1407
+ const runtimeCall = t7__namespace.awaitExpression(t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("__runtime"), t7__namespace.identifier(RuntimeFunction.RESUMABLE_PROMISE_ALL)), [
1408
+ arrayArg,
1409
+ t7__namespace.stringLiteral(parallelId)
1410
+ ]));
1411
+ path.replaceWith(runtimeCall);
1412
+ this.transformCount++;
1413
+ return true;
1414
+ }
1415
+ payloadToExpression(payload) {
1416
+ const properties = [];
1417
+ for (const [key, value] of Object.entries(payload)) {
1418
+ properties.push(t7__namespace.objectProperty(t7__namespace.identifier(key), this.valueToExpression(value)));
1419
+ }
1420
+ return t7__namespace.objectExpression(properties);
1421
+ }
1422
+ valueToExpression(value) {
1423
+ if (typeof value === "string") {
1424
+ return t7__namespace.stringLiteral(value);
1425
+ }
1426
+ if (typeof value === "number") {
1427
+ return t7__namespace.numericLiteral(value);
1428
+ }
1429
+ if (typeof value === "boolean") {
1430
+ return t7__namespace.booleanLiteral(value);
1431
+ }
1432
+ if (value === null) {
1433
+ return t7__namespace.nullLiteral();
1434
+ }
1435
+ if (Array.isArray(value)) {
1436
+ return t7__namespace.arrayExpression(value.map((v) => this.valueToExpression(v)));
1437
+ }
1438
+ if (typeof value === "object") {
1439
+ return this.payloadToExpression(value);
1440
+ }
1441
+ return t7__namespace.identifier("undefined");
1442
+ }
1443
+ isPromiseAll(node) {
1444
+ const callee = node.callee;
1445
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
1446
+ name: "Promise"
1447
+ }) && t7__namespace.isIdentifier(callee.property, {
1448
+ name: "all"
1449
+ });
1450
+ }
1451
+ isPromiseAllSettled(node) {
1452
+ const callee = node.callee;
1453
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
1454
+ name: "Promise"
1455
+ }) && t7__namespace.isIdentifier(callee.property, {
1456
+ name: "allSettled"
1457
+ });
1458
+ }
1459
+ getTransformCount() {
1460
+ return this.transformCount;
1461
+ }
1462
+ resetTransformCount() {
1463
+ this.transformCount = 0;
1464
+ }
1465
+ };
1466
+
1467
+ // src/runtime/errors.ts
1468
+ exports.CheckpointOperation = void 0;
1469
+ (function(CheckpointOperation2) {
1470
+ CheckpointOperation2["SAVE"] = "save";
1471
+ CheckpointOperation2["LOAD"] = "load";
1472
+ CheckpointOperation2["CLEAR"] = "clear";
1473
+ })(exports.CheckpointOperation || (exports.CheckpointOperation = {}));
1474
+ var BatchPauseExecutionError = class extends Error {
1475
+ static {
1476
+ __name(this, "BatchPauseExecutionError");
1477
+ }
1478
+ calls;
1479
+ batchId;
1480
+ sequenceNumber;
1481
+ constructor(calls, batchId, sequenceNumber) {
1482
+ super(`Batch pause for parallel execution (${calls.length} callbacks)`);
1483
+ this.name = "BatchPauseExecutionError";
1484
+ this.calls = calls;
1485
+ this.batchId = batchId;
1486
+ this.sequenceNumber = sequenceNumber;
1487
+ }
1488
+ };
1489
+ var CheckpointError = class extends Error {
1490
+ static {
1491
+ __name(this, "CheckpointError");
1492
+ }
1493
+ checkpointId;
1494
+ operation;
1495
+ constructor(message, checkpointId, operation) {
1496
+ super(`Checkpoint ${operation} failed for ${checkpointId}: ${message}`);
1497
+ this.name = "CheckpointError";
1498
+ this.checkpointId = checkpointId;
1499
+ this.operation = operation;
1500
+ }
1501
+ };
1502
+ var TransformationError = class extends Error {
1503
+ static {
1504
+ __name(this, "TransformationError");
1505
+ }
1506
+ code;
1507
+ pattern;
1508
+ location;
1509
+ constructor(message, code, pattern, location) {
1510
+ const loc = location ? ` at line ${location.line}:${location.column}` : "";
1511
+ super(`Transformation failed for ${pattern}${loc}: ${message}`);
1512
+ this.name = "TransformationError";
1513
+ this.code = code;
1514
+ this.pattern = pattern;
1515
+ this.location = location;
1516
+ }
1517
+ };
1518
+ var InfiniteLoopDetectionError = class extends Error {
1519
+ static {
1520
+ __name(this, "InfiniteLoopDetectionError");
1521
+ }
1522
+ loopId;
1523
+ iterationCount;
1524
+ constructor(loopId, iterationCount) {
1525
+ super(`Infinite loop detected: ${loopId} exceeded ${iterationCount} iterations without completing`);
1526
+ this.name = "InfiniteLoopDetectionError";
1527
+ this.loopId = loopId;
1528
+ this.iterationCount = iterationCount;
1529
+ }
1530
+ };
1531
+ function isBatchPauseError(error) {
1532
+ return error instanceof BatchPauseExecutionError;
1533
+ }
1534
+ __name(isBatchPauseError, "isBatchPauseError");
1535
+ function isCheckpointError(error) {
1536
+ return error instanceof CheckpointError;
1537
+ }
1538
+ __name(isCheckpointError, "isCheckpointError");
1539
+ function isTransformationError(error) {
1540
+ return error instanceof TransformationError;
1541
+ }
1542
+ __name(isTransformationError, "isTransformationError");
1543
+
1544
+ // src/transformer/index.ts
1545
+ var traverse2 = _traverse__default.default.default || _traverse__default.default;
1546
+ var generate = _generate__default.default.default || _generate__default.default;
1547
+ var ATPCompiler = class {
1548
+ static {
1549
+ __name(this, "ATPCompiler");
1550
+ }
1551
+ config;
1552
+ detector;
1553
+ loopTransformer;
1554
+ arrayTransformer;
1555
+ promiseTransformer;
1556
+ constructor(config = {}) {
1557
+ this.config = {
1558
+ ...DEFAULT_COMPILER_CONFIG,
1559
+ ...config
1560
+ };
1561
+ this.detector = new AsyncIterationDetector();
1562
+ this.loopTransformer = new LoopTransformer(this.config.batchSizeThreshold);
1563
+ this.arrayTransformer = new ArrayTransformer(this.config.batchSizeThreshold);
1564
+ this.promiseTransformer = new PromiseTransformer(this.config.enableBatchParallel);
1565
+ }
1566
+ detect(code) {
1567
+ return this.detector.detect(code);
1568
+ }
1569
+ transform(code) {
1570
+ resetIdCounter();
1571
+ const detection = this.detector.detect(code);
1572
+ if (!detection.needsTransform) {
1573
+ return {
1574
+ code,
1575
+ transformed: false,
1576
+ patterns: [],
1577
+ metadata: {
1578
+ loopCount: 0,
1579
+ arrayMethodCount: 0,
1580
+ parallelCallCount: 0,
1581
+ batchableCount: 0
1582
+ }
1583
+ };
1584
+ }
1585
+ try {
1586
+ const ast = parser.parse(code, {
1587
+ sourceType: "module",
1588
+ plugins: [
1589
+ "typescript"
1590
+ ],
1591
+ allowAwaitOutsideFunction: true,
1592
+ allowReturnOutsideFunction: true
1593
+ });
1594
+ this.loopTransformer.resetTransformCount();
1595
+ this.arrayTransformer.resetTransformCount();
1596
+ this.promiseTransformer.resetTransformCount();
1597
+ traverse2(ast, {
1598
+ ForOfStatement: /* @__PURE__ */ __name((path) => {
1599
+ this.loopTransformer.transformForOfLoop(path);
1600
+ }, "ForOfStatement"),
1601
+ WhileStatement: /* @__PURE__ */ __name((path) => {
1602
+ this.loopTransformer.transformWhileLoop(path);
1603
+ }, "WhileStatement"),
1604
+ ForStatement: /* @__PURE__ */ __name((path) => {
1605
+ this.loopTransformer.transformForLoop(path);
1606
+ }, "ForStatement"),
1607
+ CallExpression: /* @__PURE__ */ __name((path) => {
1608
+ if (this.isArrayMethodCall(path.node)) {
1609
+ this.arrayTransformer.transformArrayMethod(path);
1610
+ } else if (this.isPromiseAllCall(path.node)) {
1611
+ this.promiseTransformer.transformPromiseAll(path);
1612
+ } else if (this.isPromiseAllSettledCall(path.node)) {
1613
+ this.promiseTransformer.transformPromiseAllSettled(path);
1614
+ }
1615
+ }, "CallExpression")
1616
+ });
1617
+ const output = generate(ast, {
1618
+ sourceMaps: false,
1619
+ retainLines: true,
1620
+ comments: true
1621
+ });
1622
+ const metadata = {
1623
+ loopCount: this.loopTransformer.getTransformCount(),
1624
+ arrayMethodCount: this.arrayTransformer.getTransformCount(),
1625
+ parallelCallCount: this.promiseTransformer.getTransformCount(),
1626
+ batchableCount: detection.batchableParallel ? 1 : 0
1627
+ };
1628
+ return {
1629
+ code: output.code,
1630
+ transformed: true,
1631
+ patterns: detection.patterns,
1632
+ metadata
1633
+ };
1634
+ } catch (error) {
1635
+ const message = error instanceof Error ? error.message : String(error);
1636
+ throw new TransformationError(message, code, "unknown");
1637
+ }
1638
+ }
1639
+ isArrayMethodCall(node) {
1640
+ if (!t7__namespace.isMemberExpression(node.callee)) {
1641
+ return false;
1642
+ }
1643
+ const property = node.callee.property;
1644
+ if (!t7__namespace.isIdentifier(property)) {
1645
+ return false;
1646
+ }
1647
+ const arrayMethods = [
1648
+ "map",
1649
+ "forEach",
1650
+ "filter",
1651
+ "reduce",
1652
+ "find",
1653
+ "some",
1654
+ "every",
1655
+ "flatMap"
1656
+ ];
1657
+ return arrayMethods.includes(property.name);
1658
+ }
1659
+ isPromiseAllCall(node) {
1660
+ const callee = node.callee;
1661
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
1662
+ name: "Promise"
1663
+ }) && t7__namespace.isIdentifier(callee.property, {
1664
+ name: "all"
1665
+ });
1666
+ }
1667
+ isPromiseAllSettledCall(node) {
1668
+ const callee = node.callee;
1669
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
1670
+ name: "Promise"
1671
+ }) && t7__namespace.isIdentifier(callee.property, {
1672
+ name: "allSettled"
1673
+ });
1674
+ }
1675
+ /**
1676
+ * Get the compiler type identifier (ICompiler interface requirement)
1677
+ */
1678
+ getType() {
1679
+ return "ATPCompiler";
1680
+ }
1681
+ /**
1682
+ * Get cache statistics (ICompiler interface requirement)
1683
+ * ATPCompiler doesn't cache ASTs, so returns null
1684
+ */
1685
+ getCacheStats() {
1686
+ return null;
1687
+ }
1688
+ };
1689
+
1690
+ // src/runtime/checkpoint-manager.ts
1691
+ var MAX_CHECKPOINT_SIZE = 10 * 1024 * 1024;
1692
+ var CHECKPOINT_TTL = 3600;
1693
+ var CheckpointManager = class {
1694
+ static {
1695
+ __name(this, "CheckpointManager");
1696
+ }
1697
+ cache;
1698
+ executionId;
1699
+ prefix;
1700
+ constructor(executionId, cache, prefix = "checkpoint") {
1701
+ this.executionId = executionId;
1702
+ this.cache = cache;
1703
+ this.prefix = prefix;
1704
+ }
1705
+ async save(checkpoint) {
1706
+ const key = this.getKey(checkpoint.loopId);
1707
+ try {
1708
+ const serialized = JSON.stringify(checkpoint);
1709
+ if (serialized.length > MAX_CHECKPOINT_SIZE) {
1710
+ throw new CheckpointError(`Checkpoint size ${serialized.length} exceeds maximum ${MAX_CHECKPOINT_SIZE}`, checkpoint.loopId, exports.CheckpointOperation.SAVE);
1711
+ }
1712
+ await this.cache.set(key, checkpoint, CHECKPOINT_TTL);
1713
+ } catch (error) {
1714
+ if (error instanceof CheckpointError) {
1715
+ throw error;
1716
+ }
1717
+ const message = error instanceof Error ? error.message : String(error);
1718
+ throw new CheckpointError(message, checkpoint.loopId, exports.CheckpointOperation.SAVE);
1719
+ }
1720
+ }
1721
+ async load(loopId) {
1722
+ const key = this.getKey(loopId);
1723
+ try {
1724
+ const checkpoint = await this.cache.get(key);
1725
+ if (!checkpoint) {
1726
+ return null;
1727
+ }
1728
+ if (checkpoint.completed && checkpoint.completed instanceof Array) {
1729
+ checkpoint.completed = new Set(checkpoint.completed);
1730
+ }
1731
+ return checkpoint;
1732
+ } catch (error) {
1733
+ const message = error instanceof Error ? error.message : String(error);
1734
+ throw new CheckpointError(message, loopId, exports.CheckpointOperation.LOAD);
1735
+ }
1736
+ }
1737
+ async clear(loopId) {
1738
+ const key = this.getKey(loopId);
1739
+ try {
1740
+ await this.cache.delete(key);
1741
+ } catch (error) {
1742
+ const message = error instanceof Error ? error.message : String(error);
1743
+ throw new CheckpointError(message, loopId, exports.CheckpointOperation.CLEAR);
1744
+ }
1745
+ }
1746
+ async clearAll() {
1747
+ }
1748
+ getKey(loopId) {
1749
+ return `${this.prefix}:${this.executionId}:${loopId}`;
1750
+ }
1751
+ getExecutionId() {
1752
+ return this.executionId;
1753
+ }
1754
+ };
1755
+ var globalCheckpointManager = null;
1756
+ function setCheckpointManager(manager) {
1757
+ globalCheckpointManager = manager;
1758
+ }
1759
+ __name(setCheckpointManager, "setCheckpointManager");
1760
+ function getCheckpointManager() {
1761
+ if (!globalCheckpointManager) {
1762
+ throw new Error("CheckpointManager not initialized");
1763
+ }
1764
+ return globalCheckpointManager;
1765
+ }
1766
+ __name(getCheckpointManager, "getCheckpointManager");
1767
+ function clearCheckpointManager() {
1768
+ globalCheckpointManager = null;
1769
+ }
1770
+ __name(clearCheckpointManager, "clearCheckpointManager");
1771
+ function hasCheckpointManager() {
1772
+ return globalCheckpointManager !== null;
1773
+ }
1774
+ __name(hasCheckpointManager, "hasCheckpointManager");
1775
+
1776
+ // src/runtime/resumable-loops.ts
1777
+ var MAX_ITERATIONS = 1e6;
1778
+ async function resumableForOf(items, callback, loopId) {
1779
+ const checkpointManager = getCheckpointManager();
1780
+ const checkpoint = await checkpointManager.load(loopId);
1781
+ const startIndex = checkpoint?.currentIndex || 0;
1782
+ for (let i = startIndex; i < items.length; i++) {
1783
+ if (i > MAX_ITERATIONS) {
1784
+ throw new InfiniteLoopDetectionError(loopId, i);
1785
+ }
1786
+ await callback(items[i], i);
1787
+ const newCheckpoint = {
1788
+ loopId,
1789
+ currentIndex: i + 1,
1790
+ timestamp: Date.now()
1791
+ };
1792
+ await checkpointManager.save(newCheckpoint);
1793
+ }
1794
+ await checkpointManager.clear(loopId);
1795
+ }
1796
+ __name(resumableForOf, "resumableForOf");
1797
+ async function resumableWhile(conditionFn, bodyFn, loopId) {
1798
+ const checkpointManager = getCheckpointManager();
1799
+ const checkpoint = await checkpointManager.load(loopId);
1800
+ let iteration = checkpoint?.currentIndex || 0;
1801
+ while (await Promise.resolve(conditionFn())) {
1802
+ if (iteration > MAX_ITERATIONS) {
1803
+ throw new InfiniteLoopDetectionError(loopId, iteration);
1804
+ }
1805
+ await bodyFn(iteration);
1806
+ const newCheckpoint = {
1807
+ loopId,
1808
+ currentIndex: iteration + 1,
1809
+ timestamp: Date.now()
1810
+ };
1811
+ await checkpointManager.save(newCheckpoint);
1812
+ iteration++;
1813
+ }
1814
+ await checkpointManager.clear(loopId);
1815
+ }
1816
+ __name(resumableWhile, "resumableWhile");
1817
+ async function resumableForLoop(initValue, conditionFn, incrementFn, bodyFn, loopId) {
1818
+ const checkpointManager = getCheckpointManager();
1819
+ const checkpoint = await checkpointManager.load(loopId);
1820
+ let i = checkpoint?.currentIndex !== void 0 ? checkpoint.currentIndex : initValue;
1821
+ let iterations = 0;
1822
+ while (conditionFn(i)) {
1823
+ if (iterations++ > MAX_ITERATIONS) {
1824
+ throw new InfiniteLoopDetectionError(loopId, iterations);
1825
+ }
1826
+ await bodyFn(i);
1827
+ const newCheckpoint = {
1828
+ loopId,
1829
+ currentIndex: incrementFn(i),
1830
+ timestamp: Date.now()
1831
+ };
1832
+ await checkpointManager.save(newCheckpoint);
1833
+ i = incrementFn(i);
1834
+ }
1835
+ await checkpointManager.clear(loopId);
1836
+ }
1837
+ __name(resumableForLoop, "resumableForLoop");
1838
+
1839
+ // src/runtime/resumable-arrays.ts
1840
+ var MAX_ITERATIONS2 = 1e6;
1841
+ async function resumableMap(items, callback, mapId) {
1842
+ const checkpointManager = getCheckpointManager();
1843
+ const checkpoint = await checkpointManager.load(mapId);
1844
+ const startIndex = checkpoint?.currentIndex || 0;
1845
+ const results = checkpoint?.results || [];
1846
+ for (let i = startIndex; i < items.length; i++) {
1847
+ if (i > MAX_ITERATIONS2) {
1848
+ throw new InfiniteLoopDetectionError(mapId, i);
1849
+ }
1850
+ results[i] = await callback(items[i], i, items);
1851
+ const newCheckpoint = {
1852
+ loopId: mapId,
1853
+ currentIndex: i + 1,
1854
+ results,
1855
+ timestamp: Date.now()
1856
+ };
1857
+ await checkpointManager.save(newCheckpoint);
1858
+ }
1859
+ await checkpointManager.clear(mapId);
1860
+ return results;
1861
+ }
1862
+ __name(resumableMap, "resumableMap");
1863
+ async function resumableForEach(items, callback, forEachId) {
1864
+ const checkpointManager = getCheckpointManager();
1865
+ const checkpoint = await checkpointManager.load(forEachId);
1866
+ const startIndex = checkpoint?.currentIndex || 0;
1867
+ for (let i = startIndex; i < items.length; i++) {
1868
+ if (i > MAX_ITERATIONS2) {
1869
+ throw new InfiniteLoopDetectionError(forEachId, i);
1870
+ }
1871
+ await callback(items[i], i, items);
1872
+ const newCheckpoint = {
1873
+ loopId: forEachId,
1874
+ currentIndex: i + 1,
1875
+ timestamp: Date.now()
1876
+ };
1877
+ await checkpointManager.save(newCheckpoint);
1878
+ }
1879
+ await checkpointManager.clear(forEachId);
1880
+ }
1881
+ __name(resumableForEach, "resumableForEach");
1882
+ async function resumableFilter(items, callback, filterId) {
1883
+ const checkpointManager = getCheckpointManager();
1884
+ const checkpoint = await checkpointManager.load(filterId);
1885
+ const startIndex = checkpoint?.currentIndex || 0;
1886
+ const results = checkpoint?.results || [];
1887
+ for (let i = startIndex; i < items.length; i++) {
1888
+ if (i > MAX_ITERATIONS2) {
1889
+ throw new InfiniteLoopDetectionError(filterId, i);
1890
+ }
1891
+ const passed = await callback(items[i], i, items);
1892
+ if (passed) {
1893
+ results.push(items[i]);
1894
+ }
1895
+ const newCheckpoint = {
1896
+ loopId: filterId,
1897
+ currentIndex: i + 1,
1898
+ results,
1899
+ timestamp: Date.now()
1900
+ };
1901
+ await checkpointManager.save(newCheckpoint);
1902
+ }
1903
+ await checkpointManager.clear(filterId);
1904
+ return results;
1905
+ }
1906
+ __name(resumableFilter, "resumableFilter");
1907
+ async function resumableReduce(items, callback, initialValue, reduceId) {
1908
+ const checkpointManager = getCheckpointManager();
1909
+ const checkpoint = await checkpointManager.load(reduceId);
1910
+ const startIndex = checkpoint?.currentIndex || 0;
1911
+ let accumulator = checkpoint?.accumulator ?? initialValue;
1912
+ for (let i = startIndex; i < items.length; i++) {
1913
+ if (i > MAX_ITERATIONS2) {
1914
+ throw new InfiniteLoopDetectionError(reduceId, i);
1915
+ }
1916
+ accumulator = await callback(accumulator, items[i], i, items);
1917
+ const newCheckpoint = {
1918
+ loopId: reduceId,
1919
+ currentIndex: i + 1,
1920
+ accumulator,
1921
+ timestamp: Date.now()
1922
+ };
1923
+ await checkpointManager.save(newCheckpoint);
1924
+ }
1925
+ await checkpointManager.clear(reduceId);
1926
+ return accumulator;
1927
+ }
1928
+ __name(resumableReduce, "resumableReduce");
1929
+ async function resumableFind(items, callback, findId) {
1930
+ const checkpointManager = getCheckpointManager();
1931
+ const checkpoint = await checkpointManager.load(findId);
1932
+ const startIndex = checkpoint?.currentIndex || 0;
1933
+ for (let i = startIndex; i < items.length; i++) {
1934
+ if (i > MAX_ITERATIONS2) {
1935
+ throw new InfiniteLoopDetectionError(findId, i);
1936
+ }
1937
+ const found = await callback(items[i], i, items);
1938
+ if (found) {
1939
+ await checkpointManager.clear(findId);
1940
+ return items[i];
1941
+ }
1942
+ const newCheckpoint = {
1943
+ loopId: findId,
1944
+ currentIndex: i + 1,
1945
+ timestamp: Date.now()
1946
+ };
1947
+ await checkpointManager.save(newCheckpoint);
1948
+ }
1949
+ await checkpointManager.clear(findId);
1950
+ return void 0;
1951
+ }
1952
+ __name(resumableFind, "resumableFind");
1953
+ async function resumableSome(items, callback, someId) {
1954
+ const checkpointManager = getCheckpointManager();
1955
+ const checkpoint = await checkpointManager.load(someId);
1956
+ const startIndex = checkpoint?.currentIndex || 0;
1957
+ for (let i = startIndex; i < items.length; i++) {
1958
+ if (i > MAX_ITERATIONS2) {
1959
+ throw new InfiniteLoopDetectionError(someId, i);
1960
+ }
1961
+ const result = await callback(items[i], i, items);
1962
+ if (result) {
1963
+ await checkpointManager.clear(someId);
1964
+ return true;
1965
+ }
1966
+ const newCheckpoint = {
1967
+ loopId: someId,
1968
+ currentIndex: i + 1,
1969
+ timestamp: Date.now()
1970
+ };
1971
+ await checkpointManager.save(newCheckpoint);
1972
+ }
1973
+ await checkpointManager.clear(someId);
1974
+ return false;
1975
+ }
1976
+ __name(resumableSome, "resumableSome");
1977
+ async function resumableEvery(items, callback, everyId) {
1978
+ const checkpointManager = getCheckpointManager();
1979
+ const checkpoint = await checkpointManager.load(everyId);
1980
+ const startIndex = checkpoint?.currentIndex || 0;
1981
+ for (let i = startIndex; i < items.length; i++) {
1982
+ if (i > MAX_ITERATIONS2) {
1983
+ throw new InfiniteLoopDetectionError(everyId, i);
1984
+ }
1985
+ const result = await callback(items[i], i, items);
1986
+ if (!result) {
1987
+ await checkpointManager.clear(everyId);
1988
+ return false;
1989
+ }
1990
+ const newCheckpoint = {
1991
+ loopId: everyId,
1992
+ currentIndex: i + 1,
1993
+ timestamp: Date.now()
1994
+ };
1995
+ await checkpointManager.save(newCheckpoint);
1996
+ }
1997
+ await checkpointManager.clear(everyId);
1998
+ return true;
1999
+ }
2000
+ __name(resumableEvery, "resumableEvery");
2001
+ async function resumableFlatMap(items, callback, flatMapId) {
2002
+ const checkpointManager = getCheckpointManager();
2003
+ const checkpoint = await checkpointManager.load(flatMapId);
2004
+ const startIndex = checkpoint?.currentIndex || 0;
2005
+ const results = checkpoint?.results || [];
2006
+ for (let i = startIndex; i < items.length; i++) {
2007
+ if (i > MAX_ITERATIONS2) {
2008
+ throw new InfiniteLoopDetectionError(flatMapId, i);
2009
+ }
2010
+ const mapped = await callback(items[i], i, items);
2011
+ results.push(...mapped);
2012
+ const newCheckpoint = {
2013
+ loopId: flatMapId,
2014
+ currentIndex: i + 1,
2015
+ results,
2016
+ timestamp: Date.now()
2017
+ };
2018
+ await checkpointManager.save(newCheckpoint);
2019
+ }
2020
+ await checkpointManager.clear(flatMapId);
2021
+ return results;
2022
+ }
2023
+ __name(resumableFlatMap, "resumableFlatMap");
2024
+
2025
+ // src/runtime/resumable-parallel.ts
2026
+ async function resumablePromiseAll(promises, parallelId) {
2027
+ const checkpointManager = getCheckpointManager();
2028
+ const checkpoint = await checkpointManager.load(parallelId);
2029
+ const startIndex = checkpoint?.currentIndex || 0;
2030
+ const results = checkpoint?.results || [];
2031
+ for (let i = startIndex; i < promises.length; i++) {
2032
+ results[i] = await promises[i];
2033
+ const newCheckpoint = {
2034
+ loopId: parallelId,
2035
+ currentIndex: i + 1,
2036
+ results,
2037
+ timestamp: Date.now()
2038
+ };
2039
+ await checkpointManager.save(newCheckpoint);
2040
+ }
2041
+ await checkpointManager.clear(parallelId);
2042
+ return results;
2043
+ }
2044
+ __name(resumablePromiseAll, "resumablePromiseAll");
2045
+ async function resumablePromiseAllSettled(promises, parallelId) {
2046
+ const checkpointManager = getCheckpointManager();
2047
+ const checkpoint = await checkpointManager.load(parallelId);
2048
+ const startIndex = checkpoint?.currentIndex || 0;
2049
+ const results = checkpoint?.results || [];
2050
+ for (let i = startIndex; i < promises.length; i++) {
2051
+ try {
2052
+ const value = await promises[i];
2053
+ results[i] = {
2054
+ status: "fulfilled",
2055
+ value
2056
+ };
2057
+ } catch (reason) {
2058
+ results[i] = {
2059
+ status: "rejected",
2060
+ reason
2061
+ };
2062
+ }
2063
+ const newCheckpoint = {
2064
+ loopId: parallelId,
2065
+ currentIndex: i + 1,
2066
+ results,
2067
+ timestamp: Date.now()
2068
+ };
2069
+ await checkpointManager.save(newCheckpoint);
2070
+ }
2071
+ await checkpointManager.clear(parallelId);
2072
+ return results;
2073
+ }
2074
+ __name(resumablePromiseAllSettled, "resumablePromiseAllSettled");
2075
+ async function batchParallel(batchCalls, parallelId) {
2076
+ const currentSequence = atpRuntime.getCallSequenceNumber();
2077
+ const cachedResult = atpRuntime.getCachedResult(currentSequence);
2078
+ if (cachedResult !== void 0) {
2079
+ atpRuntime.nextSequenceNumber();
2080
+ return cachedResult;
2081
+ }
2082
+ const sequenceForPause = atpRuntime.nextSequenceNumber();
2083
+ throw new BatchPauseExecutionError(batchCalls, parallelId, sequenceForPause);
2084
+ }
2085
+ __name(batchParallel, "batchParallel");
2086
+
2087
+ // src/runtime/index.ts
2088
+ function initializeRuntime(options) {
2089
+ const checkpointManager = new CheckpointManager(options.executionId, options.cache, options.checkpointPrefix);
2090
+ setCheckpointManager(checkpointManager);
2091
+ setRuntimeContext({
2092
+ executionId: options.executionId,
2093
+ cache: options.cache,
2094
+ checkpointPrefix: options.checkpointPrefix
2095
+ });
2096
+ }
2097
+ __name(initializeRuntime, "initializeRuntime");
2098
+ function cleanupRuntime() {
2099
+ }
2100
+ __name(cleanupRuntime, "cleanupRuntime");
2101
+
2102
+ // src/types/compiler-interface.ts
2103
+ function isCompiler(obj) {
2104
+ return typeof obj === "object" && obj !== null && "detect" in obj && "transform" in obj && "getType" in obj && typeof obj.detect === "function" && typeof obj.transform === "function" && typeof obj.getType === "function";
2105
+ }
2106
+ __name(isCompiler, "isCompiler");
2107
+
2108
+ // src/plugin-system/plugin-api.ts
2109
+ var PluginRegistry = class {
2110
+ static {
2111
+ __name(this, "PluginRegistry");
2112
+ }
2113
+ detectors = [];
2114
+ transformers = [];
2115
+ optimizers = [];
2116
+ validators = [];
2117
+ /**
2118
+ * Register a plugin
2119
+ */
2120
+ register(plugin) {
2121
+ if (this.findPlugin(plugin.name)) {
2122
+ throw new Error(`Plugin "${plugin.name}" is already registered. Please use a unique name or unregister the existing plugin first.`);
2123
+ }
2124
+ if (this.isDetectionPlugin(plugin)) {
2125
+ this.detectors.push(plugin);
2126
+ this.detectors.sort((a, b) => (b.priority || 50) - (a.priority || 50));
2127
+ }
2128
+ if (this.isTransformationPlugin(plugin)) {
2129
+ this.transformers.push(plugin);
2130
+ this.transformers.sort((a, b) => (b.priority || 50) - (a.priority || 50));
2131
+ }
2132
+ if (this.isOptimizerPlugin(plugin)) {
2133
+ this.optimizers.push(plugin);
2134
+ this.optimizers.sort((a, b) => (b.priority || 50) - (a.priority || 50));
2135
+ }
2136
+ if (this.isValidatorPlugin(plugin)) {
2137
+ this.validators.push(plugin);
2138
+ this.validators.sort((a, b) => (b.priority || 50) - (a.priority || 50));
2139
+ }
2140
+ }
2141
+ /**
2142
+ * Find a plugin by name
2143
+ */
2144
+ findPlugin(name) {
2145
+ const allPlugins = [
2146
+ ...this.detectors,
2147
+ ...this.transformers,
2148
+ ...this.optimizers,
2149
+ ...this.validators
2150
+ ];
2151
+ return allPlugins.find((p) => p.name === name);
2152
+ }
2153
+ /**
2154
+ * Unregister a plugin by name
2155
+ */
2156
+ unregister(name) {
2157
+ let removed = false;
2158
+ this.detectors = this.detectors.filter((p) => {
2159
+ if (p.name === name) {
2160
+ removed = true;
2161
+ return false;
2162
+ }
2163
+ return true;
2164
+ });
2165
+ this.transformers = this.transformers.filter((p) => {
2166
+ if (p.name === name) {
2167
+ removed = true;
2168
+ return false;
2169
+ }
2170
+ return true;
2171
+ });
2172
+ this.optimizers = this.optimizers.filter((p) => {
2173
+ if (p.name === name) {
2174
+ removed = true;
2175
+ return false;
2176
+ }
2177
+ return true;
2178
+ });
2179
+ this.validators = this.validators.filter((p) => {
2180
+ if (p.name === name) {
2181
+ removed = true;
2182
+ return false;
2183
+ }
2184
+ return true;
2185
+ });
2186
+ return removed;
2187
+ }
2188
+ /**
2189
+ * Get all detection plugins
2190
+ */
2191
+ getDetectors() {
2192
+ return this.detectors;
2193
+ }
2194
+ /**
2195
+ * Get all transformation plugins
2196
+ */
2197
+ getTransformers() {
2198
+ return this.transformers;
2199
+ }
2200
+ /**
2201
+ * Get all optimizer plugins
2202
+ */
2203
+ getOptimizers() {
2204
+ return this.optimizers;
2205
+ }
2206
+ /**
2207
+ * Get all validator plugins
2208
+ */
2209
+ getValidators() {
2210
+ return this.validators;
2211
+ }
2212
+ /**
2213
+ * Initialize all plugins
2214
+ */
2215
+ async initializeAll(config) {
2216
+ const allPlugins = [
2217
+ ...this.detectors,
2218
+ ...this.transformers,
2219
+ ...this.optimizers,
2220
+ ...this.validators
2221
+ ];
2222
+ for (const plugin of allPlugins) {
2223
+ if (plugin.initialize) {
2224
+ await plugin.initialize(config);
2225
+ }
2226
+ }
2227
+ }
2228
+ /**
2229
+ * Dispose all plugins
2230
+ */
2231
+ async disposeAll() {
2232
+ const allPlugins = [
2233
+ ...this.detectors,
2234
+ ...this.transformers,
2235
+ ...this.optimizers,
2236
+ ...this.validators
2237
+ ];
2238
+ for (const plugin of allPlugins) {
2239
+ if (plugin.dispose) {
2240
+ await plugin.dispose();
2241
+ }
2242
+ }
2243
+ }
2244
+ /**
2245
+ * Type guards
2246
+ */
2247
+ isDetectionPlugin(plugin) {
2248
+ return "detect" in plugin && "patterns" in plugin;
2249
+ }
2250
+ isTransformationPlugin(plugin) {
2251
+ return "getVisitor" in plugin && "getMetadata" in plugin && "reset" in plugin;
2252
+ }
2253
+ isOptimizerPlugin(plugin) {
2254
+ return "optimize" in plugin;
2255
+ }
2256
+ isValidatorPlugin(plugin) {
2257
+ return "validate" in plugin;
2258
+ }
2259
+ };
2260
+ function createTransformPlugin(config) {
2261
+ let transformCount = 0;
2262
+ return {
2263
+ name: config.name,
2264
+ version: config.version,
2265
+ priority: config.priority || 50,
2266
+ getVisitor() {
2267
+ return config.visitor;
2268
+ },
2269
+ getMetadata() {
2270
+ return config.getMetadata ? config.getMetadata() : {
2271
+ loopCount: transformCount
2272
+ };
2273
+ },
2274
+ reset() {
2275
+ transformCount = 0;
2276
+ }
2277
+ };
2278
+ }
2279
+ __name(createTransformPlugin, "createTransformPlugin");
2280
+ var traverse3 = _traverse__default.default.default || _traverse__default.default;
2281
+ var generate2 = _generate__default.default.default || _generate__default.default;
2282
+ var PluggableCompiler = class {
2283
+ static {
2284
+ __name(this, "PluggableCompiler");
2285
+ }
2286
+ config;
2287
+ registry;
2288
+ initialized = false;
2289
+ /**
2290
+ * AST cache - maps code string to parsed AST
2291
+ * This avoids re-parsing the same code multiple times
2292
+ * (e.g., once in detect() and once in transform())
2293
+ *
2294
+ * Performance Impact: ~30% reduction in compile time
2295
+ */
2296
+ astCache = /* @__PURE__ */ new Map();
2297
+ constructor(config = {}) {
2298
+ this.config = {
2299
+ ...DEFAULT_COMPILER_CONFIG,
2300
+ ...config
2301
+ };
2302
+ this.registry = new PluginRegistry();
2303
+ }
2304
+ /**
2305
+ * Register a plugin (chainable)
2306
+ */
2307
+ use(plugin) {
2308
+ this.registry.register(plugin);
2309
+ return this;
2310
+ }
2311
+ /**
2312
+ * Unregister a plugin by name
2313
+ */
2314
+ remove(pluginName) {
2315
+ return this.registry.unregister(pluginName);
2316
+ }
2317
+ /**
2318
+ * Initialize all plugins
2319
+ */
2320
+ async initialize() {
2321
+ if (this.initialized) return;
2322
+ await this.registry.initializeAll(this.config);
2323
+ this.initialized = true;
2324
+ }
2325
+ /**
2326
+ * Detect patterns using all detection plugins
2327
+ */
2328
+ async detect(code) {
2329
+ if (!this.initialized) {
2330
+ await this.initialize();
2331
+ }
2332
+ try {
2333
+ const ast = this.parseCode(code);
2334
+ const detectors = this.registry.getDetectors();
2335
+ const allPatterns = /* @__PURE__ */ new Set();
2336
+ let batchableParallel = false;
2337
+ for (const detector of detectors) {
2338
+ const result = await detector.detect(code, ast);
2339
+ result.patterns.forEach((p) => allPatterns.add(p));
2340
+ if (result.batchableParallel) {
2341
+ batchableParallel = true;
2342
+ }
2343
+ }
2344
+ return {
2345
+ needsTransform: allPatterns.size > 0,
2346
+ patterns: Array.from(allPatterns),
2347
+ batchableParallel
2348
+ };
2349
+ } catch (error) {
2350
+ return {
2351
+ needsTransform: false,
2352
+ patterns: [],
2353
+ batchableParallel: false
2354
+ };
2355
+ }
2356
+ }
2357
+ /**
2358
+ * Transform code using all transformation plugins
2359
+ */
2360
+ async transform(code) {
2361
+ if (!this.initialized) {
2362
+ await this.initialize();
2363
+ }
2364
+ resetIdCounter();
2365
+ await this.runValidation(code, "pre");
2366
+ const detection = await this.detect(code);
2367
+ if (!detection.needsTransform) {
2368
+ return {
2369
+ code,
2370
+ transformed: false,
2371
+ patterns: [],
2372
+ metadata: {
2373
+ loopCount: 0,
2374
+ arrayMethodCount: 0,
2375
+ parallelCallCount: 0,
2376
+ batchableCount: 0
2377
+ }
2378
+ };
2379
+ }
2380
+ try {
2381
+ const ast = this.parseCode(code);
2382
+ const transformers = this.registry.getTransformers();
2383
+ for (const transformer of transformers) {
2384
+ transformer.reset();
2385
+ }
2386
+ const visitors = {};
2387
+ for (const transformer of transformers) {
2388
+ const visitor = transformer.getVisitor(this.config);
2389
+ for (const [nodeType, handler] of Object.entries(visitor)) {
2390
+ if (!visitors[nodeType]) {
2391
+ visitors[nodeType] = handler;
2392
+ } else {
2393
+ const existing = visitors[nodeType];
2394
+ visitors[nodeType] = (path) => {
2395
+ existing(path);
2396
+ handler(path);
2397
+ };
2398
+ }
2399
+ }
2400
+ }
2401
+ traverse3(ast, visitors);
2402
+ let optimizedAst = ast;
2403
+ const optimizers = this.registry.getOptimizers();
2404
+ for (const optimizer of optimizers) {
2405
+ optimizedAst = await optimizer.optimize(optimizedAst, this.config);
2406
+ }
2407
+ const output = generate2(optimizedAst, {
2408
+ sourceMaps: false,
2409
+ retainLines: true,
2410
+ comments: true
2411
+ });
2412
+ const metadata = {
2413
+ loopCount: 0,
2414
+ arrayMethodCount: 0,
2415
+ parallelCallCount: 0,
2416
+ batchableCount: detection.batchableParallel ? 1 : 0
2417
+ };
2418
+ for (const transformer of transformers) {
2419
+ const pluginMetadata = transformer.getMetadata();
2420
+ metadata.loopCount += pluginMetadata.loopCount || 0;
2421
+ metadata.arrayMethodCount += pluginMetadata.arrayMethodCount || 0;
2422
+ metadata.parallelCallCount += pluginMetadata.parallelCallCount || 0;
2423
+ metadata.batchableCount += pluginMetadata.batchableCount || 0;
2424
+ }
2425
+ await this.runValidation(output.code, "post");
2426
+ return {
2427
+ code: output.code,
2428
+ transformed: true,
2429
+ patterns: detection.patterns,
2430
+ metadata
2431
+ };
2432
+ } catch (error) {
2433
+ const message = error instanceof Error ? error.message : String(error);
2434
+ const context = detection.patterns.length > 0 ? `[Plugin transformation] ${message}` : message;
2435
+ throw new TransformationError(context, code, "plugin-error");
2436
+ }
2437
+ }
2438
+ /**
2439
+ * Dispose compiler and all plugins
2440
+ */
2441
+ async dispose() {
2442
+ await this.registry.disposeAll();
2443
+ this.astCache.clear();
2444
+ this.initialized = false;
2445
+ }
2446
+ /**
2447
+ * Get current configuration
2448
+ */
2449
+ getConfig() {
2450
+ return {
2451
+ ...this.config
2452
+ };
2453
+ }
2454
+ /**
2455
+ * Update configuration
2456
+ */
2457
+ setConfig(config) {
2458
+ this.config = {
2459
+ ...this.config,
2460
+ ...config
2461
+ };
2462
+ }
2463
+ /**
2464
+ * Parse code to AST with caching
2465
+ *
2466
+ * Caches parsed AST to avoid re-parsing the same code multiple times.
2467
+ * This provides ~30% performance improvement when detect() and transform()
2468
+ * are called on the same code.
2469
+ */
2470
+ parseCode(code) {
2471
+ const cached = this.astCache.get(code);
2472
+ if (cached) {
2473
+ return cached;
2474
+ }
2475
+ const ast = parser.parse(code, {
2476
+ sourceType: "module",
2477
+ plugins: [
2478
+ "typescript"
2479
+ ],
2480
+ allowAwaitOutsideFunction: true,
2481
+ allowReturnOutsideFunction: true
2482
+ });
2483
+ this.astCache.set(code, ast);
2484
+ return ast;
2485
+ }
2486
+ /**
2487
+ * Clear AST cache
2488
+ *
2489
+ * Call this method to free memory if you've compiled many different code snippets.
2490
+ * The cache is automatically managed and uses Map, so old entries don't leak memory.
2491
+ */
2492
+ clearCache() {
2493
+ this.astCache.clear();
2494
+ }
2495
+ /**
2496
+ * Get the compiler type identifier (ICompiler interface requirement)
2497
+ */
2498
+ getType() {
2499
+ return "PluggableCompiler";
2500
+ }
2501
+ /**
2502
+ * Get cache statistics (for debugging/monitoring)
2503
+ */
2504
+ getCacheStats() {
2505
+ return {
2506
+ size: this.astCache.size,
2507
+ enabled: true
2508
+ };
2509
+ }
2510
+ /**
2511
+ * Run validators
2512
+ */
2513
+ async runValidation(code, phase) {
2514
+ const validators = this.registry.getValidators();
2515
+ const ast = this.parseCode(code);
2516
+ for (const validator of validators) {
2517
+ await validator.validate(code, ast, phase);
2518
+ }
2519
+ }
2520
+ };
2521
+
2522
+ // src/plugin-system/default-plugins/detection-plugin.ts
2523
+ var DefaultDetectionPlugin = class {
2524
+ static {
2525
+ __name(this, "DefaultDetectionPlugin");
2526
+ }
2527
+ name = "atp-default-detector";
2528
+ version = "1.0.0";
2529
+ priority = 100;
2530
+ patterns = [
2531
+ "for-of-await",
2532
+ "while-await",
2533
+ "map-async",
2534
+ "forEach-async",
2535
+ "filter-async",
2536
+ "reduce-async",
2537
+ "find-async",
2538
+ "some-async",
2539
+ "every-async",
2540
+ "flatMap-async",
2541
+ "promise-all",
2542
+ "promise-allSettled"
2543
+ ];
2544
+ detector;
2545
+ constructor() {
2546
+ this.detector = new AsyncIterationDetector();
2547
+ }
2548
+ async detect(code, ast) {
2549
+ return this.detector.detect(code);
2550
+ }
2551
+ };
2552
+
2553
+ // src/plugin-system/default-plugins/loop-transformer-plugin.ts
2554
+ var DefaultLoopTransformerPlugin = class {
2555
+ static {
2556
+ __name(this, "DefaultLoopTransformerPlugin");
2557
+ }
2558
+ name = "atp-loop-transformer";
2559
+ version = "1.0.0";
2560
+ priority = 100;
2561
+ transformer;
2562
+ constructor(batchSizeThreshold) {
2563
+ this.transformer = new LoopTransformer(batchSizeThreshold);
2564
+ }
2565
+ getVisitor(config) {
2566
+ return {
2567
+ ForOfStatement: /* @__PURE__ */ __name((path) => {
2568
+ this.transformer.transformForOfLoop(path);
2569
+ }, "ForOfStatement"),
2570
+ WhileStatement: /* @__PURE__ */ __name((path) => {
2571
+ this.transformer.transformWhileLoop(path);
2572
+ }, "WhileStatement"),
2573
+ ForStatement: /* @__PURE__ */ __name((path) => {
2574
+ this.transformer.transformForLoop(path);
2575
+ }, "ForStatement")
2576
+ };
2577
+ }
2578
+ getMetadata() {
2579
+ return {
2580
+ loopCount: this.transformer.getTransformCount()
2581
+ };
2582
+ }
2583
+ reset() {
2584
+ this.transformer.resetTransformCount();
2585
+ }
2586
+ };
2587
+ var DefaultArrayTransformerPlugin = class {
2588
+ static {
2589
+ __name(this, "DefaultArrayTransformerPlugin");
2590
+ }
2591
+ name = "atp-array-transformer";
2592
+ version = "1.0.0";
2593
+ priority = 100;
2594
+ transformer;
2595
+ constructor(batchSizeThreshold) {
2596
+ this.transformer = new ArrayTransformer(batchSizeThreshold);
2597
+ }
2598
+ getVisitor(config) {
2599
+ return {
2600
+ CallExpression: /* @__PURE__ */ __name((path) => {
2601
+ const node = path.node;
2602
+ if (this.isArrayMethodCall(node)) {
2603
+ this.transformer.transformArrayMethod(path);
2604
+ }
2605
+ }, "CallExpression")
2606
+ };
2607
+ }
2608
+ getMetadata() {
2609
+ return {
2610
+ arrayMethodCount: this.transformer.getTransformCount()
2611
+ };
2612
+ }
2613
+ reset() {
2614
+ this.transformer.resetTransformCount();
2615
+ }
2616
+ isArrayMethodCall(node) {
2617
+ if (!t7__namespace.isMemberExpression(node.callee)) {
2618
+ return false;
2619
+ }
2620
+ const property = node.callee.property;
2621
+ if (!t7__namespace.isIdentifier(property)) {
2622
+ return false;
2623
+ }
2624
+ const arrayMethods = [
2625
+ "map",
2626
+ "forEach",
2627
+ "filter",
2628
+ "reduce",
2629
+ "find",
2630
+ "some",
2631
+ "every",
2632
+ "flatMap"
2633
+ ];
2634
+ return arrayMethods.includes(property.name);
2635
+ }
2636
+ };
2637
+ var DefaultPromiseTransformerPlugin = class {
2638
+ static {
2639
+ __name(this, "DefaultPromiseTransformerPlugin");
2640
+ }
2641
+ name = "atp-promise-transformer";
2642
+ version = "1.0.0";
2643
+ priority = 100;
2644
+ transformer;
2645
+ constructor(enableBatchParallel) {
2646
+ this.transformer = new PromiseTransformer(enableBatchParallel);
2647
+ }
2648
+ getVisitor(config) {
2649
+ return {
2650
+ CallExpression: /* @__PURE__ */ __name((path) => {
2651
+ const node = path.node;
2652
+ if (this.isPromiseAllCall(node)) {
2653
+ this.transformer.transformPromiseAll(path);
2654
+ } else if (this.isPromiseAllSettledCall(node)) {
2655
+ this.transformer.transformPromiseAllSettled(path);
2656
+ }
2657
+ }, "CallExpression")
2658
+ };
2659
+ }
2660
+ getMetadata() {
2661
+ return {
2662
+ parallelCallCount: this.transformer.getTransformCount()
2663
+ };
2664
+ }
2665
+ reset() {
2666
+ this.transformer.resetTransformCount();
2667
+ }
2668
+ isPromiseAllCall(node) {
2669
+ const callee = node.callee;
2670
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
2671
+ name: "Promise"
2672
+ }) && t7__namespace.isIdentifier(callee.property, {
2673
+ name: "all"
2674
+ });
2675
+ }
2676
+ isPromiseAllSettledCall(node) {
2677
+ const callee = node.callee;
2678
+ return t7__namespace.isMemberExpression(callee) && t7__namespace.isIdentifier(callee.object, {
2679
+ name: "Promise"
2680
+ }) && t7__namespace.isIdentifier(callee.property, {
2681
+ name: "allSettled"
2682
+ });
2683
+ }
2684
+ };
2685
+
2686
+ // src/plugin-system/create-default-compiler.ts
2687
+ function createDefaultCompiler(config = {}) {
2688
+ const compiler = new PluggableCompiler(config);
2689
+ compiler.use(new DefaultDetectionPlugin());
2690
+ compiler.use(new DefaultLoopTransformerPlugin(config.batchSizeThreshold));
2691
+ compiler.use(new DefaultArrayTransformerPlugin(config.batchSizeThreshold));
2692
+ compiler.use(new DefaultPromiseTransformerPlugin(config.enableBatchParallel));
2693
+ return compiler;
2694
+ }
2695
+ __name(createDefaultCompiler, "createDefaultCompiler");
2696
+ var AsyncTimeoutPlugin = class {
2697
+ static {
2698
+ __name(this, "AsyncTimeoutPlugin");
2699
+ }
2700
+ name = "async-timeout";
2701
+ version = "1.0.0";
2702
+ priority = 40;
2703
+ options;
2704
+ transformCount = 0;
2705
+ constructor(options = {}) {
2706
+ this.options = {
2707
+ timeout: options.timeout || 5e3,
2708
+ patterns: options.patterns || [
2709
+ "fetch",
2710
+ "axios.*",
2711
+ "http.*"
2712
+ ],
2713
+ wrapAll: options.wrapAll || false
2714
+ };
2715
+ }
2716
+ getVisitor(config) {
2717
+ return {
2718
+ AwaitExpression: /* @__PURE__ */ __name((path) => {
2719
+ if (!this.shouldWrap(path.node.argument)) {
2720
+ return;
2721
+ }
2722
+ const timeoutPromise = t7__namespace.newExpression(t7__namespace.identifier("Promise"), [
2723
+ t7__namespace.arrowFunctionExpression([
2724
+ t7__namespace.identifier("_"),
2725
+ t7__namespace.identifier("reject")
2726
+ ], t7__namespace.blockStatement([
2727
+ t7__namespace.expressionStatement(t7__namespace.callExpression(t7__namespace.identifier("setTimeout"), [
2728
+ t7__namespace.arrowFunctionExpression([], t7__namespace.callExpression(t7__namespace.identifier("reject"), [
2729
+ t7__namespace.newExpression(t7__namespace.identifier("Error"), [
2730
+ t7__namespace.stringLiteral(`Timeout after ${this.options.timeout}ms`)
2731
+ ])
2732
+ ])),
2733
+ t7__namespace.numericLiteral(this.options.timeout)
2734
+ ]))
2735
+ ]))
2736
+ ]);
2737
+ const raceCall = t7__namespace.callExpression(t7__namespace.memberExpression(t7__namespace.identifier("Promise"), t7__namespace.identifier("race")), [
2738
+ t7__namespace.arrayExpression([
2739
+ path.node.argument,
2740
+ timeoutPromise
2741
+ ])
2742
+ ]);
2743
+ path.node.argument = raceCall;
2744
+ this.transformCount++;
2745
+ }, "AwaitExpression")
2746
+ };
2747
+ }
2748
+ getMetadata() {
2749
+ return {
2750
+ // Custom metadata
2751
+ loopCount: 0,
2752
+ arrayMethodCount: 0,
2753
+ parallelCallCount: this.transformCount,
2754
+ batchableCount: 0
2755
+ };
2756
+ }
2757
+ reset() {
2758
+ this.transformCount = 0;
2759
+ }
2760
+ /**
2761
+ * Check if this await should be wrapped with timeout
2762
+ */
2763
+ shouldWrap(node) {
2764
+ if (this.options.wrapAll) {
2765
+ return true;
2766
+ }
2767
+ if (t7__namespace.isCallExpression(node)) {
2768
+ const funcName = this.getFunctionName(node);
2769
+ if (funcName) {
2770
+ return this.options.patterns.some((pattern) => {
2771
+ const regex = new RegExp(pattern.replace("*", ".*"));
2772
+ return regex.test(funcName);
2773
+ });
2774
+ }
2775
+ }
2776
+ return false;
2777
+ }
2778
+ /**
2779
+ * Get function name from call expression
2780
+ */
2781
+ getFunctionName(node) {
2782
+ if (t7__namespace.isIdentifier(node.callee)) {
2783
+ return node.callee.name;
2784
+ }
2785
+ if (t7__namespace.isMemberExpression(node.callee)) {
2786
+ const obj = t7__namespace.isIdentifier(node.callee.object) ? node.callee.object.name : "";
2787
+ const prop = t7__namespace.isIdentifier(node.callee.property) ? node.callee.property.name : "";
2788
+ return `${obj}.${prop}`;
2789
+ }
2790
+ return null;
2791
+ }
2792
+ };
2793
+ var traverse4 = _traverse__default.default.default || _traverse__default.default;
2794
+ var SecurityValidatorPlugin = class {
2795
+ static {
2796
+ __name(this, "SecurityValidatorPlugin");
2797
+ }
2798
+ name = "security-validator";
2799
+ version = "1.0.0";
2800
+ priority = 100;
2801
+ options;
2802
+ constructor(options = {}) {
2803
+ this.options = {
2804
+ forbiddenPatterns: options.forbiddenPatterns || [
2805
+ /\beval\s*\(/,
2806
+ /new\s+Function\s*\(/,
2807
+ /constructor\s*\[\s*['"`]constructor['"`]\s*\]/
2808
+ ],
2809
+ maxComplexity: options.maxComplexity || 50,
2810
+ maxNesting: options.maxNesting || 10,
2811
+ forbiddenGlobals: options.forbiddenGlobals || [
2812
+ "process",
2813
+ "require",
2814
+ "__dirname",
2815
+ "__filename"
2816
+ ]
2817
+ };
2818
+ }
2819
+ async validate(code, ast, phase) {
2820
+ if (phase === "post") {
2821
+ return;
2822
+ }
2823
+ for (const pattern of this.options.forbiddenPatterns) {
2824
+ if (pattern.test(code)) {
2825
+ throw new SecurityValidationError(`Forbidden pattern detected: ${pattern}`, "forbidden-pattern");
2826
+ }
2827
+ }
2828
+ let maxNestingFound = 0;
2829
+ let complexityScore = 0;
2830
+ traverse4(ast, {
2831
+ enter(path) {
2832
+ const depth = path.scope.path.node ? getDepth(path) : 0;
2833
+ maxNestingFound = Math.max(maxNestingFound, depth);
2834
+ if (path.isIfStatement() || path.isWhileStatement() || path.isForStatement() || path.isForOfStatement() || path.isSwitchCase() || path.isCatchClause()) {
2835
+ complexityScore++;
2836
+ }
2837
+ },
2838
+ // 3. Check forbidden globals
2839
+ Identifier: /* @__PURE__ */ __name((path) => {
2840
+ if (this.options.forbiddenGlobals.includes(path.node.name) && !path.scope.hasBinding(path.node.name)) {
2841
+ throw new SecurityValidationError(`Access to forbidden global: ${path.node.name}`, "forbidden-global");
2842
+ }
2843
+ }, "Identifier")
2844
+ });
2845
+ if (maxNestingFound > this.options.maxNesting) {
2846
+ throw new SecurityValidationError(`Maximum nesting depth exceeded: ${maxNestingFound} > ${this.options.maxNesting}`, "max-nesting");
2847
+ }
2848
+ if (complexityScore > this.options.maxComplexity) {
2849
+ throw new SecurityValidationError(`Maximum complexity exceeded: ${complexityScore} > ${this.options.maxComplexity}`, "max-complexity");
2850
+ }
2851
+ }
2852
+ };
2853
+ var SecurityValidationError = class extends Error {
2854
+ static {
2855
+ __name(this, "SecurityValidationError");
2856
+ }
2857
+ code;
2858
+ constructor(message, code) {
2859
+ super(message);
2860
+ this.code = code;
2861
+ this.name = "SecurityValidationError";
2862
+ }
2863
+ };
2864
+ function getDepth(path) {
2865
+ let depth = 0;
2866
+ let current = path;
2867
+ while (current.parentPath) {
2868
+ if (current.isBlockStatement() || current.isFunctionDeclaration() || current.isArrowFunctionExpression()) {
2869
+ depth++;
2870
+ }
2871
+ current = current.parentPath;
2872
+ }
2873
+ return depth;
2874
+ }
2875
+ __name(getDepth, "getDepth");
2876
+
2877
+ exports.ATPCompiler = ATPCompiler;
2878
+ exports.ArrayTransformer = ArrayTransformer;
2879
+ exports.AsyncIterationDetector = AsyncIterationDetector;
2880
+ exports.AsyncTimeoutPlugin = AsyncTimeoutPlugin;
2881
+ exports.BatchOptimizer = BatchOptimizer;
2882
+ exports.BatchParallelDetector = BatchParallelDetector;
2883
+ exports.BatchPauseExecutionError = BatchPauseExecutionError;
2884
+ exports.CheckpointError = CheckpointError;
2885
+ exports.CheckpointManager = CheckpointManager;
2886
+ exports.DEFAULT_COMPILER_CONFIG = DEFAULT_COMPILER_CONFIG;
2887
+ exports.DefaultArrayTransformerPlugin = DefaultArrayTransformerPlugin;
2888
+ exports.DefaultDetectionPlugin = DefaultDetectionPlugin;
2889
+ exports.DefaultLoopTransformerPlugin = DefaultLoopTransformerPlugin;
2890
+ exports.DefaultPromiseTransformerPlugin = DefaultPromiseTransformerPlugin;
2891
+ exports.IN_ISOLATE_RUNTIME_FUNCTIONS = IN_ISOLATE_RUNTIME_FUNCTIONS;
2892
+ exports.InfiniteLoopDetectionError = InfiniteLoopDetectionError;
2893
+ exports.LoopTransformer = LoopTransformer;
2894
+ exports.PAUSABLE_CALL_PATTERNS = PAUSABLE_CALL_PATTERNS;
2895
+ exports.PluggableCompiler = PluggableCompiler;
2896
+ exports.PluginRegistry = PluginRegistry;
2897
+ exports.PromiseTransformer = PromiseTransformer;
2898
+ exports.RuntimeFunction = RuntimeFunction;
2899
+ exports.SecurityValidationError = SecurityValidationError;
2900
+ exports.SecurityValidatorPlugin = SecurityValidatorPlugin;
2901
+ exports.TransformationError = TransformationError;
2902
+ exports.batchParallel = batchParallel;
2903
+ exports.cleanupRuntime = cleanupRuntime;
2904
+ exports.clearCheckpointManager = clearCheckpointManager;
2905
+ exports.clearRuntimeContext = clearRuntimeContext;
2906
+ exports.containsAwait = containsAwait;
2907
+ exports.containsPausableCall = containsPausableCall;
2908
+ exports.createDefaultCompiler = createDefaultCompiler;
2909
+ exports.createRuntimeCall = createRuntimeCall;
2910
+ exports.createTransformPlugin = createTransformPlugin;
2911
+ exports.extractForOfParamName = extractForOfParamName;
2912
+ exports.generateUniqueId = generateUniqueId;
2913
+ exports.getCheckpointManager = getCheckpointManager;
2914
+ exports.getMemberExpressionPath = getMemberExpressionPath;
2915
+ exports.getNodeLocation = getNodeLocation;
2916
+ exports.getRuntimeContext = getRuntimeContext;
2917
+ exports.hasCheckpointManager = hasCheckpointManager;
2918
+ exports.hasRuntimeContext = hasRuntimeContext;
2919
+ exports.initializeRuntime = initializeRuntime;
2920
+ exports.isArrayMethod = isArrayMethod;
2921
+ exports.isAsyncFunction = isAsyncFunction;
2922
+ exports.isBatchPauseError = isBatchPauseError;
2923
+ exports.isCheckpointError = isCheckpointError;
2924
+ exports.isCompiler = isCompiler;
2925
+ exports.isInIsolateRuntimeFunction = isInIsolateRuntimeFunction;
2926
+ exports.isPausableCall = isPausableCall;
2927
+ exports.isPausableCallExpression = isPausableCallExpression;
2928
+ exports.isTransformationError = isTransformationError;
2929
+ exports.resetIdCounter = resetIdCounter;
2930
+ exports.resumableEvery = resumableEvery;
2931
+ exports.resumableFilter = resumableFilter;
2932
+ exports.resumableFind = resumableFind;
2933
+ exports.resumableFlatMap = resumableFlatMap;
2934
+ exports.resumableForEach = resumableForEach;
2935
+ exports.resumableForLoop = resumableForLoop;
2936
+ exports.resumableForOf = resumableForOf;
2937
+ exports.resumableMap = resumableMap;
2938
+ exports.resumablePromiseAll = resumablePromiseAll;
2939
+ exports.resumablePromiseAllSettled = resumablePromiseAllSettled;
2940
+ exports.resumableReduce = resumableReduce;
2941
+ exports.resumableSome = resumableSome;
2942
+ exports.resumableWhile = resumableWhile;
2943
+ exports.setCheckpointManager = setCheckpointManager;
2944
+ exports.setRuntimeContext = setRuntimeContext;
2945
+ exports.wrapInAsyncFunction = wrapInAsyncFunction;
2946
+ //# sourceMappingURL=index.cjs.map
2947
+ //# sourceMappingURL=index.cjs.map