@bash0816/claude-code 2.1.272 → 2.1.276-1

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.
@@ -1361,3 +1361,888 @@ test('recoverMissing integration: fs interception collaborates with recovery', a
1361
1361
  fs.rmSync(tempDir, { recursive: true, force: true });
1362
1362
  }
1363
1363
  });
1364
+
1365
+ // New tests for hooks-standalone-pattern integration
1366
+ test('hooks: ok + 1 record valid: qle replacement applied', async () => {
1367
+ const loader = await import('./bunfs-esm-loader.mjs');
1368
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-${process.pid}-${Date.now()}`);
1369
+ fs.mkdirSync(tempDir, { recursive: true });
1370
+ const chunkFile = path.join(tempDir, 'chunk.js');
1371
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1372
+ fs.writeFileSync(chunkFile, source);
1373
+
1374
+ try {
1375
+ loader.initialize({
1376
+ processOwnedDir: tempDir,
1377
+ sourceBin: '/dummy/bin',
1378
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1379
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1380
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1381
+ hooksMetadata: {
1382
+ status: 'ok',
1383
+ patches: [{ file: 'chunk.js', expectedOccurrences: 1 }],
1384
+ },
1385
+ });
1386
+
1387
+ let loadCalls = 0;
1388
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1389
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1390
+ const expected = 'var qle=(e,o,r)=>(!0)?ar(o,r(),e):{module:o,folder:e};';
1391
+ assert.equal(result.source, expected);
1392
+ } finally {
1393
+ fs.rmSync(tempDir, { recursive: true, force: true });
1394
+ }
1395
+ });
1396
+
1397
+ test('hooks: other files unmodified even if they contain qle pattern', async () => {
1398
+ const loader = await import('./bunfs-esm-loader.mjs');
1399
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test2-${process.pid}-${Date.now()}`);
1400
+ fs.mkdirSync(tempDir, { recursive: true });
1401
+ const recordedFile = path.join(tempDir, 'recorded.js');
1402
+ const otherFile = path.join(tempDir, 'other.js');
1403
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1404
+ fs.writeFileSync(recordedFile, source);
1405
+ fs.writeFileSync(otherFile, source);
1406
+
1407
+ try {
1408
+ loader.initialize({
1409
+ processOwnedDir: tempDir,
1410
+ sourceBin: '/dummy/bin',
1411
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1412
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1413
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1414
+ hooksMetadata: {
1415
+ status: 'ok',
1416
+ patches: [{ file: 'recorded.js', expectedOccurrences: 1 }],
1417
+ },
1418
+ });
1419
+
1420
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1421
+ const resultOther = await loader.load(pathToFileURL(otherFile).href, {}, nextLoad);
1422
+ // other file should be unchanged
1423
+ assert.equal(resultOther.source, source);
1424
+ } finally {
1425
+ fs.rmSync(tempDir, { recursive: true, force: true });
1426
+ }
1427
+ });
1428
+
1429
+ test('hooks: ok + count mismatch triggers fallback with warning', async () => {
1430
+ const loader = await import('./bunfs-esm-loader.mjs');
1431
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test3-${process.pid}-${Date.now()}`);
1432
+ fs.mkdirSync(tempDir, { recursive: true });
1433
+ const chunkFile = path.join(tempDir, 'chunk.js');
1434
+ const source = 'import.meta.dir\nvar qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1435
+ fs.writeFileSync(chunkFile, source);
1436
+
1437
+ let warnings = [];
1438
+ const origError = console.error;
1439
+ console.error = (msg) => warnings.push(msg);
1440
+
1441
+ try {
1442
+ loader.initialize({
1443
+ processOwnedDir: tempDir,
1444
+ sourceBin: '/dummy/bin',
1445
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1446
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1447
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1448
+ hooksMetadata: {
1449
+ status: 'ok',
1450
+ patches: [{ file: 'chunk.js', expectedOccurrences: 2 }], // expect 2 but has 1
1451
+ },
1452
+ });
1453
+
1454
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1455
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1456
+ // layer2 should apply: add import.meta.dir prelude
1457
+ assert.ok(result.source.includes('import.meta.dir ??= import.meta.dirname;'));
1458
+ // should have warning
1459
+ assert.equal(warnings.length, 1);
1460
+ assert.ok(warnings[0].includes('occurrence count mismatch'));
1461
+ } finally {
1462
+ console.error = origError;
1463
+ fs.rmSync(tempDir, { recursive: true, force: true });
1464
+ }
1465
+ });
1466
+
1467
+ test('hooks: ok + invalid record triggers fallback', async () => {
1468
+ const loader = await import('./bunfs-esm-loader.mjs');
1469
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test4-${process.pid}-${Date.now()}`);
1470
+ fs.mkdirSync(tempDir, { recursive: true });
1471
+ const chunkFile = path.join(tempDir, 'chunk.js');
1472
+ const source = 'import.meta.dir\ncode';
1473
+ fs.writeFileSync(chunkFile, source);
1474
+
1475
+ let warnings = [];
1476
+ const origError = console.error;
1477
+ console.error = (msg) => warnings.push(msg);
1478
+
1479
+ try {
1480
+ loader.initialize({
1481
+ processOwnedDir: tempDir,
1482
+ sourceBin: '/dummy/bin',
1483
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1484
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1485
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1486
+ hooksMetadata: {
1487
+ status: 'ok',
1488
+ patches: [{ file: '../invalid.js', expectedOccurrences: 1 }], // file with ..
1489
+ },
1490
+ });
1491
+
1492
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1493
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1494
+ // layer2 should apply
1495
+ assert.ok(result.source.includes('import.meta.dir ??= import.meta.dirname;'));
1496
+ assert.equal(warnings.length, 1);
1497
+ } finally {
1498
+ console.error = origError;
1499
+ fs.rmSync(tempDir, { recursive: true, force: true });
1500
+ }
1501
+ });
1502
+
1503
+ test('hooks: ok + empty patches triggers layer2 without warning', async () => {
1504
+ const loader = await import('./bunfs-esm-loader.mjs');
1505
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test5-${process.pid}-${Date.now()}`);
1506
+ fs.mkdirSync(tempDir, { recursive: true });
1507
+ const chunkFile = path.join(tempDir, 'chunk.js');
1508
+ const source = 'import.meta.dir\ncode';
1509
+ fs.writeFileSync(chunkFile, source);
1510
+
1511
+ let warnings = [];
1512
+ const origError = console.error;
1513
+ console.error = (msg) => warnings.push(msg);
1514
+
1515
+ try {
1516
+ loader.initialize({
1517
+ processOwnedDir: tempDir,
1518
+ sourceBin: '/dummy/bin',
1519
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1520
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1521
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1522
+ hooksMetadata: {
1523
+ status: 'ok',
1524
+ patches: [],
1525
+ },
1526
+ });
1527
+
1528
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1529
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1530
+ // layer2 should apply
1531
+ assert.ok(result.source.includes('import.meta.dir ??= import.meta.dirname;'));
1532
+ // no warning for empty patches
1533
+ assert.equal(warnings.length, 0);
1534
+ } finally {
1535
+ console.error = origError;
1536
+ fs.rmSync(tempDir, { recursive: true, force: true });
1537
+ }
1538
+ });
1539
+
1540
+ test('hooks: layer2 adds prelude only for import.meta.dir', async () => {
1541
+ const loader = await import('./bunfs-esm-loader.mjs');
1542
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test6-${process.pid}-${Date.now()}`);
1543
+ fs.mkdirSync(tempDir, { recursive: true });
1544
+ const chunkFile = path.join(tempDir, 'chunk.js');
1545
+ const source = 'const x = import.meta.dirname; // OK, should not match \\bimport\\.meta\\.dir\\b';
1546
+ fs.writeFileSync(chunkFile, source);
1547
+
1548
+ try {
1549
+ loader.initialize({
1550
+ processOwnedDir: tempDir,
1551
+ sourceBin: '/dummy/bin',
1552
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1553
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1554
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1555
+ hooksMetadata: { status: 'ok', patches: [] },
1556
+ });
1557
+
1558
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1559
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1560
+ // should not add prelude since only dirname exists
1561
+ assert.ok(!result.source.includes('import.meta.dir ??= import.meta.dirname;'));
1562
+ assert.equal(result.source, source);
1563
+ } finally {
1564
+ fs.rmSync(tempDir, { recursive: true, force: true });
1565
+ }
1566
+ });
1567
+
1568
+ test('hooks: field-absent warning on first layer2 prelude', async () => {
1569
+ const loader = await import('./bunfs-esm-loader.mjs');
1570
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test7-${process.pid}-${Date.now()}`);
1571
+ fs.mkdirSync(tempDir, { recursive: true });
1572
+ const chunkFile = path.join(tempDir, 'chunk.js');
1573
+ const chunkFile2 = path.join(tempDir, 'chunk2.js');
1574
+ const source = 'import.meta.dir\ncode';
1575
+ fs.writeFileSync(chunkFile, source);
1576
+ fs.writeFileSync(chunkFile2, source);
1577
+
1578
+ let warnings = [];
1579
+ const origError = console.error;
1580
+ console.error = (msg) => warnings.push(msg);
1581
+
1582
+ try {
1583
+ loader.initialize({
1584
+ processOwnedDir: tempDir,
1585
+ sourceBin: '/dummy/bin',
1586
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1587
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1588
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1589
+ hooksMetadata: { status: 'field-absent', patches: [] },
1590
+ });
1591
+
1592
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1593
+ // first load: should warn when layer2 prelude is applied
1594
+ const result1 = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1595
+ assert.equal(warnings.length, 1);
1596
+ assert.ok(warnings[0].includes('no hooks_standalone_patches record'));
1597
+
1598
+ // second load: warning already issued, should not repeat
1599
+ const result2 = await loader.load(pathToFileURL(chunkFile2).href, {}, nextLoad);
1600
+ assert.equal(warnings.length, 1); // still 1
1601
+ } finally {
1602
+ console.error = origError;
1603
+ fs.rmSync(tempDir, { recursive: true, force: true });
1604
+ }
1605
+ });
1606
+
1607
+ test('hooks: state transition - layer1 valid makes layer2 inactive', async () => {
1608
+ const loader = await import('./bunfs-esm-loader.mjs');
1609
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test8-${process.pid}-${Date.now()}`);
1610
+ fs.mkdirSync(tempDir, { recursive: true });
1611
+ const recordedFile = path.join(tempDir, 'recorded.js');
1612
+ const otherFile = path.join(tempDir, 'other.js');
1613
+ const recordedSource = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1614
+ const otherSource = 'import.meta.dir\ncode'; // has import.meta.dir
1615
+ fs.writeFileSync(recordedFile, recordedSource);
1616
+ fs.writeFileSync(otherFile, otherSource);
1617
+
1618
+ try {
1619
+ loader.initialize({
1620
+ processOwnedDir: tempDir,
1621
+ sourceBin: '/dummy/bin',
1622
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1623
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1624
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1625
+ hooksMetadata: {
1626
+ status: 'ok',
1627
+ patches: [{ file: 'recorded.js', expectedOccurrences: 1 }],
1628
+ },
1629
+ });
1630
+
1631
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1632
+ // Load other file first (has import.meta.dir): layer1 is valid, so layer2 should be inactive
1633
+ const resultOther = await loader.load(pathToFileURL(otherFile).href, {}, nextLoad);
1634
+ // should NOT add prelude because layer1 is valid
1635
+ assert.ok(!resultOther.source.includes('import.meta.dir ??='));
1636
+ assert.equal(resultOther.source, otherSource);
1637
+
1638
+ // Confirm layer1 still works
1639
+ const resultRecorded = await loader.load(pathToFileURL(recordedFile).href, {}, nextLoad);
1640
+ assert.equal(resultRecorded.source, 'var qle=(e,o,r)=>(!0)?ar(o,r(),e):{module:o,folder:e};');
1641
+ } finally {
1642
+ fs.rmSync(tempDir, { recursive: true, force: true });
1643
+ }
1644
+ });
1645
+
1646
+ test('hooks: initialize resets state and warnings', async () => {
1647
+ const loader = await import('./bunfs-esm-loader.mjs');
1648
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test9-${process.pid}-${Date.now()}`);
1649
+ fs.mkdirSync(tempDir, { recursive: true });
1650
+ const chunkFile = path.join(tempDir, 'chunk.js');
1651
+ const source = 'import.meta.dir\ncode';
1652
+ fs.writeFileSync(chunkFile, source);
1653
+
1654
+ let warnings = [];
1655
+ const origError = console.error;
1656
+ console.error = (msg) => warnings.push(msg);
1657
+
1658
+ try {
1659
+ // First initialize with field-absent
1660
+ loader.initialize({
1661
+ processOwnedDir: tempDir,
1662
+ sourceBin: '/dummy/bin',
1663
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1664
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1665
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1666
+ hooksMetadata: { status: 'field-absent', patches: [] },
1667
+ });
1668
+
1669
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1670
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1671
+ assert.equal(warnings.length, 1);
1672
+
1673
+ // Re-initialize: should reset warning flag
1674
+ warnings = [];
1675
+ loader.initialize({
1676
+ processOwnedDir: tempDir,
1677
+ sourceBin: '/dummy/bin',
1678
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1679
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1680
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1681
+ hooksMetadata: { status: 'read-failed', patches: [] },
1682
+ });
1683
+
1684
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1685
+ assert.equal(warnings.length, 1); // new warning from read-failed
1686
+ assert.ok(warnings[0].includes('could not be read'));
1687
+ } finally {
1688
+ console.error = origError;
1689
+ fs.rmSync(tempDir, { recursive: true, force: true });
1690
+ }
1691
+ });
1692
+
1693
+ test('hooks: hooksMetadata state warnings - entry-missing and read-failed', async () => {
1694
+ const loader = await import('./bunfs-esm-loader.mjs');
1695
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test10-${process.pid}-${Date.now()}`);
1696
+ fs.mkdirSync(tempDir, { recursive: true });
1697
+ const chunkFile = path.join(tempDir, 'chunk.js');
1698
+ fs.writeFileSync(chunkFile, 'code');
1699
+
1700
+ let warnings = [];
1701
+ const origError = console.error;
1702
+ console.error = (msg) => warnings.push(msg);
1703
+
1704
+ try {
1705
+ // Test entry-missing
1706
+ loader.initialize({
1707
+ processOwnedDir: tempDir,
1708
+ sourceBin: '/dummy/bin',
1709
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1710
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1711
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1712
+ hooksMetadata: { status: 'entry-missing', patches: [] },
1713
+ });
1714
+
1715
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1716
+ warnings = [];
1717
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1718
+ assert.equal(warnings.length, 1);
1719
+ assert.ok(warnings[0].includes('metadata entry missing'));
1720
+
1721
+ // Test read-failed
1722
+ loader.initialize({
1723
+ processOwnedDir: tempDir,
1724
+ sourceBin: '/dummy/bin',
1725
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1726
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1727
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1728
+ hooksMetadata: { status: 'read-failed', patches: [] },
1729
+ });
1730
+
1731
+ warnings = [];
1732
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1733
+ assert.equal(warnings.length, 1);
1734
+ assert.ok(warnings[0].includes('could not be read'));
1735
+ } finally {
1736
+ console.error = origError;
1737
+ fs.rmSync(tempDir, { recursive: true, force: true });
1738
+ }
1739
+ });
1740
+
1741
+ // #3/#4: 記録不正の種類ごと個別テスト
1742
+ test('hooks: ok + file contains .. triggers fallback with specific reason', async () => {
1743
+ const loader = await import('./bunfs-esm-loader.mjs');
1744
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-file-dd-${process.pid}-${Date.now()}`);
1745
+ fs.mkdirSync(tempDir, { recursive: true });
1746
+ const chunkFile = path.join(tempDir, 'chunk.js');
1747
+ fs.writeFileSync(chunkFile, 'import.meta.dir\ncode');
1748
+
1749
+ let warnings = [];
1750
+ const origError = console.error;
1751
+ console.error = (msg) => warnings.push(msg);
1752
+
1753
+ try {
1754
+ loader.initialize({
1755
+ processOwnedDir: tempDir,
1756
+ sourceBin: '/dummy/bin',
1757
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1758
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1759
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1760
+ hooksMetadata: {
1761
+ status: 'ok',
1762
+ patches: [{ file: '../escape.js', expectedOccurrences: 1 }],
1763
+ },
1764
+ });
1765
+
1766
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1767
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1768
+ assert.equal(warnings.length, 1);
1769
+ assert.ok(warnings[0].includes('file contains ..'));
1770
+ } finally {
1771
+ console.error = origError;
1772
+ fs.rmSync(tempDir, { recursive: true, force: true });
1773
+ }
1774
+ });
1775
+
1776
+ test('hooks: ok + absolute path triggers fallback with specific reason', async () => {
1777
+ const loader = await import('./bunfs-esm-loader.mjs');
1778
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-abs-${process.pid}-${Date.now()}`);
1779
+ fs.mkdirSync(tempDir, { recursive: true });
1780
+ const chunkFile = path.join(tempDir, 'chunk.js');
1781
+ fs.writeFileSync(chunkFile, 'import.meta.dir\ncode');
1782
+
1783
+ let warnings = [];
1784
+ const origError = console.error;
1785
+ console.error = (msg) => warnings.push(msg);
1786
+
1787
+ try {
1788
+ loader.initialize({
1789
+ processOwnedDir: tempDir,
1790
+ sourceBin: '/dummy/bin',
1791
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1792
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1793
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1794
+ hooksMetadata: {
1795
+ status: 'ok',
1796
+ patches: [{ file: '/absolute/path.js', expectedOccurrences: 1 }],
1797
+ },
1798
+ });
1799
+
1800
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1801
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1802
+ assert.equal(warnings.length, 1);
1803
+ assert.ok(warnings[0].includes('file is absolute path'));
1804
+ } finally {
1805
+ console.error = origError;
1806
+ fs.rmSync(tempDir, { recursive: true, force: true });
1807
+ }
1808
+ });
1809
+
1810
+ test('hooks: ok + file not found triggers fallback with specific reason', async () => {
1811
+ const loader = await import('./bunfs-esm-loader.mjs');
1812
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-notfound-${process.pid}-${Date.now()}`);
1813
+ fs.mkdirSync(tempDir, { recursive: true });
1814
+ const chunkFile = path.join(tempDir, 'chunk.js');
1815
+ fs.writeFileSync(chunkFile, 'import.meta.dir\ncode');
1816
+
1817
+ let warnings = [];
1818
+ const origError = console.error;
1819
+ console.error = (msg) => warnings.push(msg);
1820
+
1821
+ try {
1822
+ loader.initialize({
1823
+ processOwnedDir: tempDir,
1824
+ sourceBin: '/dummy/bin',
1825
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1826
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1827
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1828
+ hooksMetadata: {
1829
+ status: 'ok',
1830
+ patches: [{ file: 'nonexistent.js', expectedOccurrences: 1 }],
1831
+ },
1832
+ });
1833
+
1834
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1835
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1836
+ assert.equal(warnings.length, 1);
1837
+ assert.ok(warnings[0].includes('file not found or recovery failed'));
1838
+ } finally {
1839
+ console.error = origError;
1840
+ fs.rmSync(tempDir, { recursive: true, force: true });
1841
+ }
1842
+ });
1843
+
1844
+ test('hooks: ok + expectedOccurrences=0 triggers fallback with specific reason', async () => {
1845
+ const loader = await import('./bunfs-esm-loader.mjs');
1846
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-zero-${process.pid}-${Date.now()}`);
1847
+ fs.mkdirSync(tempDir, { recursive: true });
1848
+ const chunkFile = path.join(tempDir, 'chunk.js');
1849
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1850
+ fs.writeFileSync(chunkFile, source);
1851
+
1852
+ let warnings = [];
1853
+ const origError = console.error;
1854
+ console.error = (msg) => warnings.push(msg);
1855
+
1856
+ try {
1857
+ loader.initialize({
1858
+ processOwnedDir: tempDir,
1859
+ sourceBin: '/dummy/bin',
1860
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1861
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1862
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1863
+ hooksMetadata: {
1864
+ status: 'ok',
1865
+ patches: [{ file: 'chunk.js', expectedOccurrences: 0 }],
1866
+ },
1867
+ });
1868
+
1869
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1870
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1871
+ assert.equal(warnings.length, 1);
1872
+ assert.ok(warnings[0].includes('invalid expectedOccurrences'));
1873
+ } finally {
1874
+ console.error = origError;
1875
+ fs.rmSync(tempDir, { recursive: true, force: true });
1876
+ }
1877
+ });
1878
+
1879
+ test('hooks: ok + file duplicate triggers fallback with specific reason', async () => {
1880
+ const loader = await import('./bunfs-esm-loader.mjs');
1881
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-dup-${process.pid}-${Date.now()}`);
1882
+ fs.mkdirSync(tempDir, { recursive: true });
1883
+ const chunkFile = path.join(tempDir, 'chunk.js');
1884
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1885
+ fs.writeFileSync(chunkFile, source);
1886
+
1887
+ let warnings = [];
1888
+ const origError = console.error;
1889
+ console.error = (msg) => warnings.push(msg);
1890
+
1891
+ try {
1892
+ loader.initialize({
1893
+ processOwnedDir: tempDir,
1894
+ sourceBin: '/dummy/bin',
1895
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1896
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1897
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1898
+ hooksMetadata: {
1899
+ status: 'ok',
1900
+ patches: [
1901
+ { file: 'chunk.js', expectedOccurrences: 1 },
1902
+ { file: 'chunk.js', expectedOccurrences: 1 },
1903
+ ],
1904
+ },
1905
+ });
1906
+
1907
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1908
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1909
+ assert.equal(warnings.length, 1);
1910
+ assert.ok(warnings[0].includes('duplicate file'));
1911
+ } finally {
1912
+ console.error = origError;
1913
+ fs.rmSync(tempDir, { recursive: true, force: true });
1914
+ }
1915
+ });
1916
+
1917
+ test('hooks: ok + second record invalid: reason reflects second record failure', async () => {
1918
+ const loader = await import('./bunfs-esm-loader.mjs');
1919
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-2nd-${process.pid}-${Date.now()}`);
1920
+ fs.mkdirSync(tempDir, { recursive: true });
1921
+ const file1 = path.join(tempDir, 'chunk1.js');
1922
+ const file2 = path.join(tempDir, 'chunk2.js');
1923
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1924
+ fs.writeFileSync(file1, source);
1925
+ fs.writeFileSync(file2, source);
1926
+
1927
+ let warnings = [];
1928
+ const origError = console.error;
1929
+ console.error = (msg) => warnings.push(msg);
1930
+
1931
+ try {
1932
+ loader.initialize({
1933
+ processOwnedDir: tempDir,
1934
+ sourceBin: '/dummy/bin',
1935
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1936
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1937
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1938
+ hooksMetadata: {
1939
+ status: 'ok',
1940
+ patches: [
1941
+ { file: 'chunk1.js', expectedOccurrences: 1 },
1942
+ { file: 'chunk2.js', expectedOccurrences: 0 }, // 2番目だけ不正
1943
+ ],
1944
+ },
1945
+ });
1946
+
1947
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1948
+ await loader.load(pathToFileURL(file1).href, {}, nextLoad);
1949
+ assert.equal(warnings.length, 1);
1950
+ // 警告に「2番目の記録由来」の内容が反映されること
1951
+ assert.ok(warnings[0].includes('invalid expectedOccurrences'));
1952
+ } finally {
1953
+ console.error = origError;
1954
+ fs.rmSync(tempDir, { recursive: true, force: true });
1955
+ }
1956
+ });
1957
+
1958
+ test('hooks: #6(b) import.meta.dir in comment/string literal also gets prelude', async () => {
1959
+ const loader = await import('./bunfs-esm-loader.mjs');
1960
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-comment-${process.pid}-${Date.now()}`);
1961
+ fs.mkdirSync(tempDir, { recursive: true });
1962
+ const chunkFile = path.join(tempDir, 'chunk.js');
1963
+ const source = `// import.meta.dir is used here\nconst str = "import.meta.dir shim";\ncode`;
1964
+ fs.writeFileSync(chunkFile, source);
1965
+
1966
+ try {
1967
+ loader.initialize({
1968
+ processOwnedDir: tempDir,
1969
+ sourceBin: '/dummy/bin',
1970
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
1971
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
1972
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
1973
+ hooksMetadata: { status: 'ok', patches: [] },
1974
+ });
1975
+
1976
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
1977
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
1978
+ // Even if import.meta.dir is only in comment/string, it matches \\bimport\\.meta\\.dir\\b
1979
+ assert.ok(result.source.includes('import.meta.dir ??= import.meta.dirname;'));
1980
+ // Original content preserved (prelude prepended, not replaced)
1981
+ assert.ok(result.source.includes(source));
1982
+ } finally {
1983
+ fs.rmSync(tempDir, { recursive: true, force: true });
1984
+ }
1985
+ });
1986
+
1987
+ test('hooks: #7 state transition - plugin chunk loaded before qle chunk, layer1 valid', async () => {
1988
+ const loader = await import('./bunfs-esm-loader.mjs');
1989
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-order-${process.pid}-${Date.now()}`);
1990
+ fs.mkdirSync(tempDir, { recursive: true });
1991
+ const qleFile = path.join(tempDir, 'qle.js');
1992
+ const pluginFile = path.join(tempDir, 'plugin.js');
1993
+ const qleSource = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
1994
+ const pluginSource = 'import.meta.dir'; // plugin has import.meta.dir
1995
+ fs.writeFileSync(qleFile, qleSource);
1996
+ fs.writeFileSync(pluginFile, pluginSource);
1997
+
1998
+ try {
1999
+ loader.initialize({
2000
+ processOwnedDir: tempDir,
2001
+ sourceBin: '/dummy/bin',
2002
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
2003
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
2004
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
2005
+ hooksMetadata: {
2006
+ status: 'ok',
2007
+ patches: [{ file: 'qle.js', expectedOccurrences: 1 }],
2008
+ },
2009
+ });
2010
+
2011
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
2012
+ // Load plugin first (has import.meta.dir)
2013
+ const resultPlugin = await loader.load(pathToFileURL(pluginFile).href, {}, nextLoad);
2014
+ // Layer1 is valid, so layer2 should NOT be applied
2015
+ assert.ok(!resultPlugin.source.includes('import.meta.dir ??='));
2016
+ assert.equal(resultPlugin.source, pluginSource);
2017
+
2018
+ // Load qle second
2019
+ const resultQle = await loader.load(pathToFileURL(qleFile).href, {}, nextLoad);
2020
+ assert.equal(resultQle.source, 'var qle=(e,o,r)=>(!0)?ar(o,r(),e):{module:o,folder:e};');
2021
+ } finally {
2022
+ fs.rmSync(tempDir, { recursive: true, force: true });
2023
+ }
2024
+ });
2025
+
2026
+ test('hooks: #8 idempotency - same file loaded twice produces identical output', async () => {
2027
+ const loader = await import('./bunfs-esm-loader.mjs');
2028
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-idempotent-${process.pid}-${Date.now()}`);
2029
+ fs.mkdirSync(tempDir, { recursive: true });
2030
+ const chunkFile = path.join(tempDir, 'chunk.js');
2031
+ const source = 'import.meta.dir\ncode';
2032
+ fs.writeFileSync(chunkFile, source);
2033
+
2034
+ try {
2035
+ loader.initialize({
2036
+ processOwnedDir: tempDir,
2037
+ sourceBin: '/dummy/bin',
2038
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
2039
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
2040
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
2041
+ hooksMetadata: { status: 'ok', patches: [] },
2042
+ });
2043
+
2044
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
2045
+ const result1 = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
2046
+ const result2 = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
2047
+ // Second load should produce identical output (no double prelude)
2048
+ assert.equal(result1.source, result2.source);
2049
+ assert.ok(!result1.source.includes('import.meta.dir ??= import.meta.dirname;\nimport.meta.dir ??='));
2050
+ } finally {
2051
+ fs.rmSync(tempDir, { recursive: true, force: true });
2052
+ }
2053
+ });
2054
+
2055
+ test('hooks: #9 import.meta.require prelude + hooks transformation coexist correctly', async () => {
2056
+ const loader = await import('./bunfs-esm-loader.mjs');
2057
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-coexist-${process.pid}-${Date.now()}`);
2058
+ fs.mkdirSync(tempDir, { recursive: true });
2059
+ const chunkFile = path.join(tempDir, 'chunk.js');
2060
+ // Source with both qle and import.meta.require
2061
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};\nimport.meta.require("/$bunfs/root/x.js");';
2062
+ fs.writeFileSync(chunkFile, source);
2063
+
2064
+ try {
2065
+ loader.initialize({
2066
+ processOwnedDir: tempDir,
2067
+ sourceBin: '/dummy/bin',
2068
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
2069
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
2070
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
2071
+ hooksMetadata: {
2072
+ status: 'ok',
2073
+ patches: [{ file: 'chunk.js', expectedOccurrences: 1 }],
2074
+ },
2075
+ });
2076
+
2077
+ const nextLoad = async () => ({ format: 'module', source: 'nextLoad result', shortCircuit: true });
2078
+ const result = await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
2079
+ // QLE replacement should happen
2080
+ assert.ok(result.source.includes('(!0)?ar'));
2081
+ // import.meta.require replacement should happen
2082
+ assert.ok(result.source.includes('__bunfsMetaRequire'));
2083
+ // import.meta.require prelude should be present
2084
+ assert.ok(result.source.includes('const __bunfsMetaRequire'));
2085
+ } finally {
2086
+ fs.rmSync(tempDir, { recursive: true, force: true });
2087
+ }
2088
+ });
2089
+
2090
+ test('hooks: ok + expectedOccurrences=1.5 (non-integer) triggers fallback', async () => {
2091
+ const loader = await import('./bunfs-esm-loader.mjs');
2092
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-float-${process.pid}-${Date.now()}`);
2093
+ fs.mkdirSync(tempDir, { recursive: true });
2094
+ const chunkFile = path.join(tempDir, 'chunk.js');
2095
+ const source = 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};';
2096
+ fs.writeFileSync(chunkFile, source);
2097
+
2098
+ let warnings = [];
2099
+ const origError = console.error;
2100
+ console.error = (msg) => warnings.push(msg);
2101
+
2102
+ try {
2103
+ loader.initialize({
2104
+ processOwnedDir: tempDir,
2105
+ sourceBin: '/dummy/bin',
2106
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
2107
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
2108
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
2109
+ hooksMetadata: {
2110
+ status: 'ok',
2111
+ patches: [{ file: 'chunk.js', expectedOccurrences: 1.5 }],
2112
+ },
2113
+ });
2114
+
2115
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
2116
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
2117
+ assert.equal(warnings.length, 1);
2118
+ assert.ok(warnings[0].includes('invalid expectedOccurrences'));
2119
+ } finally {
2120
+ console.error = origError;
2121
+ fs.rmSync(tempDir, { recursive: true, force: true });
2122
+ }
2123
+ });
2124
+
2125
+ test('hooks: ok + expectedOccurrences="1" (string) triggers fallback', async () => {
2126
+ const loader = await import('./bunfs-esm-loader.mjs');
2127
+ const tempDir = path.join(os.tmpdir(), `bunfs-hooks-test-str-${process.pid}-${Date.now()}`);
2128
+ fs.mkdirSync(tempDir, { recursive: true });
2129
+ const chunkFile = path.join(tempDir, 'chunk.js');
2130
+ fs.writeFileSync(chunkFile, 'import.meta.dir\ncode');
2131
+
2132
+ let warnings = [];
2133
+ const origError = console.error;
2134
+ console.error = (msg) => warnings.push(msg);
2135
+
2136
+ try {
2137
+ loader.initialize({
2138
+ processOwnedDir: tempDir,
2139
+ sourceBin: '/dummy/bin',
2140
+ childProcessGuardPath: path.join(tempDir, 'guard.mjs'),
2141
+ vmGuardPath: path.join(tempDir, 'vm.mjs'),
2142
+ wsStubPath: path.join(tempDir, 'ws.mjs'),
2143
+ hooksMetadata: {
2144
+ status: 'ok',
2145
+ patches: [{ file: 'chunk.js', expectedOccurrences: '1' }],
2146
+ },
2147
+ });
2148
+
2149
+ const nextLoad = async () => ({ format: 'module', source: '', shortCircuit: true });
2150
+ await loader.load(pathToFileURL(chunkFile).href, {}, nextLoad);
2151
+ assert.equal(warnings.length, 1);
2152
+ assert.ok(warnings[0].includes('invalid expectedOccurrences'));
2153
+ } finally {
2154
+ console.error = origError;
2155
+ fs.rmSync(tempDir, { recursive: true, force: true });
2156
+ }
2157
+ });
2158
+
2159
+
2160
+
2161
+ test('hooks: #11 real ESM integration - qle export and plugin import coexist', async (t) => {
2162
+ const { spawnSync } = require('node:child_process');
2163
+ const { registerHooks } = await import('node:module');
2164
+ if (typeof registerHooks !== 'function') return t.skip('registerHooks unavailable');
2165
+ const loaderPath = path.resolve(__dirname, 'bunfs-esm-loader.mjs');
2166
+ const run = (metadata, order = false, useLoader = true) => {
2167
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bunfs-hooks-esm-'));
2168
+ const guard = path.join(tmp, 'guard.mjs');
2169
+ const vm = path.join(tmp, 'vm.mjs');
2170
+ const ws = path.join(tmp, 'ws.mjs');
2171
+ fs.writeFileSync(guard, 'export {};\n');
2172
+ fs.writeFileSync(vm, 'export {};\n');
2173
+ fs.writeFileSync(ws, 'export {};\n');
2174
+ fs.writeFileSync(path.join(tmp, 'chunk-qle.mjs'), 'function uu(){return false}\nvar ar=(e,o,r)=>({module:e,scan:o.scan,files:o.files,dir:r});\nvar qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};\nexport { qle };\n');
2175
+ fs.writeFileSync(path.join(tmp, 'plugin-mermaid.mjs'), "import { qle } from './chunk-qle.mjs';\nexport const result={name:'mermaid',hooksModule:qle(import.meta.dir,{id:'mod-mermaid'},()=>({scan:{hooks:[],calls:[],events:['ui.render']},files:{}}))};\n");
2176
+ fs.writeFileSync(path.join(tmp, 'plugin-agents.mjs'), "import { qle } from './chunk-qle.mjs';\nexport const result={name:'agents-md',hooksModule:qle(import.meta.dir,{id:'mod-agents'},()=>({scan:{hooks:[],calls:[],events:['session.start','prompt.context']},files:{}}))};\n");
2177
+ const init = useLoader ? 'loader.initialize({processOwnedDir:' + JSON.stringify(tmp) + ",sourceBin:'/dummy/bin',childProcessGuardPath:" + JSON.stringify(guard) + ',vmGuardPath:' + JSON.stringify(vm) + ',wsStubPath:' + JSON.stringify(ws) + ',hooksMetadata:' + JSON.stringify(metadata) + '}); registerHooks({resolve:loader.resolve,load:loader.load});' : '';
2178
+ const imports = order ? 'const b=await import(pathToFileURL(' + JSON.stringify(path.join(tmp, 'plugin-agents.mjs')) + ').href); const a=await import(pathToFileURL(' + JSON.stringify(path.join(tmp, 'plugin-mermaid.mjs')) + ').href);' : 'const a=await import(pathToFileURL(' + JSON.stringify(path.join(tmp, 'plugin-mermaid.mjs')) + ').href); const b=await import(pathToFileURL(' + JSON.stringify(path.join(tmp, 'plugin-agents.mjs')) + ').href);';
2179
+ const script = 'import {registerHooks} from \'node:module\'; import {pathToFileURL} from \'node:url\'; const loader=await import(' + JSON.stringify(pathToFileURL(loaderPath).href) + '); ' + init + ' ' + imports + ' console.log(JSON.stringify({a:a.result,b:b.result}));';
2180
+ try {
2181
+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' });
2182
+ assert.equal(child.status, 0, 'child failed status=' + child.status + ': ' + child.stderr);
2183
+ return { data: JSON.parse(child.stdout.trim().split(/\r?\n/).at(-1)), stderr: child.stderr, tmp };
2184
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
2185
+ };
2186
+ const ok = run({ status: 'ok', patches: [{ file: 'chunk-qle.mjs', expectedOccurrences: 1 }] });
2187
+ assert.equal(ok.data.a.hooksModule.module.id, 'mod-mermaid');
2188
+ assert.deepEqual(ok.data.a.hooksModule.scan.events, ['ui.render']);
2189
+ assert.equal(Object.hasOwn(ok.data.a.hooksModule, 'folder'), false);
2190
+ assert.deepEqual(ok.data.b.hooksModule.scan.events, ['session.start', 'prompt.context']);
2191
+ assert.equal(ok.stderr, '');
2192
+ const mismatch = run({ status: 'ok', patches: [{ file: 'chunk-qle.mjs', expectedOccurrences: 2 }] });
2193
+ assert.deepEqual(mismatch.data.a.hooksModule, { module: { id: 'mod-mermaid' }, folder: mismatch.tmp });
2194
+ assert.deepEqual(mismatch.data.b.hooksModule, { module: { id: 'mod-agents' }, folder: mismatch.tmp });
2195
+ assert.equal((mismatch.stderr.match(/hooks standalone patch not applied/g) || []).length, 1);
2196
+ const absent = run({ status: 'field-absent' });
2197
+ assert.equal(absent.data.a.hooksModule.folder, absent.tmp);
2198
+ assert.equal(absent.data.b.hooksModule.folder, absent.tmp);
2199
+ assert.equal((absent.stderr.match(/no hooks_standalone_patches record/g) || []).length, 1);
2200
+ const direct = run({ status: 'field-absent' }, false, false);
2201
+ assert.equal(Object.hasOwn(direct.data.a.hooksModule, 'folder'), false);
2202
+ const reversed = run({ status: 'ok', patches: [{ file: 'chunk-qle.mjs', expectedOccurrences: 1 }] }, true);
2203
+ assert.equal(reversed.data.a.hooksModule.module.id, 'mod-mermaid');
2204
+ assert.deepEqual(reversed.data.b.hooksModule.scan.events, ['session.start', 'prompt.context']);
2205
+ assert.equal(Object.hasOwn(reversed.data.a.hooksModule, 'folder'), false);
2206
+ assert.equal(reversed.stderr, '');
2207
+ });
2208
+
2209
+ test('hooks: cycle-hoist coexists with layer1 qle and import.meta.require transforms', async () => {
2210
+ const loader = await import('./bunfs-esm-loader.mjs');
2211
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bunfs-hooks-cycle1-'));
2212
+ const target = path.join(tmp, 'target.mjs');
2213
+ const file = path.join(tmp, 'source.mjs');
2214
+ fs.writeFileSync(path.join(tmp, 'guard.mjs'), 'export {};'); fs.writeFileSync(path.join(tmp, 'vm.mjs'), 'export {};'); fs.writeFileSync(path.join(tmp, 'ws.mjs'), 'export {};');
2215
+ fs.writeFileSync(target, 'export const target=1;');
2216
+ fs.writeFileSync(file, 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};\nvar target=import.meta.require("/$bunfs/root/target.mjs");\nvar cp=import.meta.require("child_process");\nexport {qle,target,cp};');
2217
+ try {
2218
+ loader.initialize({ processOwnedDir: tmp, sourceBin: '/dummy/bin', childProcessGuardPath: path.join(tmp, 'guard.mjs'), vmGuardPath: path.join(tmp, 'vm.mjs'), wsStubPath: path.join(tmp, 'ws.mjs'), cycleHoists: [{ file: 'source.mjs', targetModule: 'target.mjs', expectedOccurrences: 1, assertProperties: [] }], hooksMetadata: { status: 'ok', patches: [{ file: 'source.mjs', expectedOccurrences: 1 }] } });
2219
+ const result = await loader.load(pathToFileURL(file).href, {}, async () => ({}));
2220
+ const hoist = 'import * as __bunfsHoisted_0 from ' + JSON.stringify(pathToFileURL(target).href) + ';';
2221
+ assert.ok(result.source.includes('(!0)?')); assert.ok(result.source.includes(hoist)); assert.ok(result.source.includes('__bunfsMetaRequire("child_process")')); assert.ok(!result.source.includes('import.meta.require("/$bunfs/root/target.mjs")')); assert.ok(result.source.indexOf(hoist) < result.source.indexOf('var qle='));
2222
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
2223
+ });
2224
+
2225
+ test('hooks: cycle-hoist coexists with layer2 shim in implementation order', async () => {
2226
+ const loader = await import('./bunfs-esm-loader.mjs');
2227
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bunfs-hooks-cycle2-'));
2228
+ const target = path.join(tmp, 'target.mjs'); const file = path.join(tmp, 'source.mjs');
2229
+ fs.writeFileSync(path.join(tmp, 'guard.mjs'), 'export {};'); fs.writeFileSync(path.join(tmp, 'vm.mjs'), 'export {};'); fs.writeFileSync(path.join(tmp, 'ws.mjs'), 'export {};'); fs.writeFileSync(target, 'export const target=1;');
2230
+ fs.writeFileSync(file, 'var qle=(e,o,r)=>uu()?ar(o,r(),e):{module:o,folder:e};\nvar target=import.meta.require("/$bunfs/root/target.mjs");\nvar cp=import.meta.require("child_process");\nconst dir=import.meta.dir;\nexport {qle,target,cp,dir};');
2231
+ try {
2232
+ loader.initialize({ processOwnedDir: tmp, sourceBin: '/dummy/bin', childProcessGuardPath: path.join(tmp, 'guard.mjs'), vmGuardPath: path.join(tmp, 'vm.mjs'), wsStubPath: path.join(tmp, 'ws.mjs'), cycleHoists: [{ file: 'source.mjs', targetModule: 'target.mjs', expectedOccurrences: 1, assertProperties: [] }], hooksMetadata: { status: 'ok', patches: [{ file: 'source.mjs', expectedOccurrences: 2 }] } });
2233
+ const result = await loader.load(pathToFileURL(file).href, {}, async () => ({}));
2234
+ const hoist = 'import * as __bunfsHoisted_0 from ' + JSON.stringify(pathToFileURL(target).href) + ';'; const shim = 'import.meta.dir ??= import.meta.dirname;\n';
2235
+ assert.ok(result.source.startsWith(hoist)); assert.ok(result.source.includes(shim)); assert.ok(result.source.includes('__bunfsMetaRequire("child_process")')); assert.ok(result.source.indexOf(hoist) < result.source.indexOf(shim)); assert.ok(result.source.indexOf(shim) < result.source.indexOf('var qle='));
2236
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
2237
+ });
2238
+
2239
+ test('load() delegates outside processOwnedDir unchanged without evaluating hooks state', async () => {
2240
+ const loader = await import('./bunfs-esm-loader.mjs'); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bunfs-hooks-owned-')); const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'bunfs-hooks-outside-')); const file = path.join(outside, 'outside.mjs');
2241
+ fs.writeFileSync(file, 'import.meta.dir\nexport const value=1;'); const warnings = []; const origError = console.error; console.error = (message) => warnings.push(message);
2242
+ try {
2243
+ loader.initialize({ processOwnedDir: tmp, sourceBin: '/dummy/bin', childProcessGuardPath: path.join(tmp, 'guard.mjs'), vmGuardPath: path.join(tmp, 'vm.mjs'), wsStubPath: path.join(tmp, 'ws.mjs'), hooksMetadata: { status: 'ok', patches: [{ file: '../invalid.js', expectedOccurrences: 1 }] } });
2244
+ const delegated = { format: 'module', source: 'delegated source', shortCircuit: true }; let calls = 0;
2245
+ const result = await loader.load(pathToFileURL(file).href, {}, async () => { calls++; return delegated; });
2246
+ assert.equal(calls, 1); assert.strictEqual(result, delegated); assert.equal(result.source, 'delegated source'); assert.deepEqual(warnings, []);
2247
+ } finally { console.error = origError; fs.rmSync(tmp, { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); }
2248
+ });