| 62 | // Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js |
| 63 | // Extracted as we want to format the result ourselves |
| 64 | export default function collectHandles(): HandleCollectionResult { |
| 65 | const activeHandles = new Map< |
| 66 | number, |
| 67 | {error: Error; isActive: () => boolean} |
| 68 | >(); |
| 69 | const hook = asyncHooks.createHook({ |
| 70 | destroy(asyncId) { |
| 71 | activeHandles.delete(asyncId); |
| 72 | }, |
| 73 | init: function initHook( |
| 74 | asyncId, |
| 75 | type, |
| 76 | triggerAsyncId, |
| 77 | // eslint-disable-next-line @typescript-eslint/no-empty-object-type |
| 78 | resource: {} | NodeJS.Timeout, |
| 79 | ) { |
| 80 | // Skip resources that should not generally prevent the process from |
| 81 | // exiting, not last a meaningfully long time, or otherwise shouldn't be |
| 82 | // tracked. |
| 83 | if ( |
| 84 | [ |
| 85 | 'PROMISE', |
| 86 | 'TIMERWRAP', |
| 87 | 'ELDHISTOGRAM', |
| 88 | 'PerformanceObserver', |
| 89 | 'RANDOMBYTESREQUEST', |
| 90 | 'DNSCHANNEL', |
| 91 | 'ZLIB', |
| 92 | 'SIGNREQUEST', |
| 93 | 'TLSWRAP', |
| 94 | 'TCPWRAP', |
| 95 | ].includes(type) |
| 96 | ) { |
| 97 | return; |
| 98 | } |
| 99 | const error = new ErrorWithStack(type, initHook, 100); |
| 100 | let fromUser = stackIsFromUser(error.stack || ''); |
| 101 | |
| 102 | // If the async resource was not directly created by user code, but was |
| 103 | // triggered by another async resource from user code, track it and use |
| 104 | // the original triggering resource's stack. |
| 105 | if (!fromUser) { |
| 106 | const triggeringHandle = activeHandles.get(triggerAsyncId); |
| 107 | if (triggeringHandle) { |
| 108 | fromUser = true; |
| 109 | error.stack = triggeringHandle.error.stack; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | if (fromUser) { |
| 114 | let isActive: () => boolean; |
| 115 | |
| 116 | // Handle that supports hasRef |
| 117 | if ('hasRef' in resource) { |
| 118 | if (hasWeakRef) { |
| 119 | const ref = new WeakRef(resource); |
| 120 | isActive = () => { |
| 121 | return ref.deref()?.hasRef() ?? false; |