From 1e171806f873fd4b916cb1c852ae4cb8ebad5ccd Mon Sep 17 00:00:00 2001 From: Okiki Ojo Date: Fri, 13 Feb 2026 02:06:01 -0500 Subject: [PATCH] refactor: rename disposables and abortSignal to scope and abort for clarity in resource management Signed-off-by: Okiki Ojo --- core/build.ts | 4 ++-- core/context.ts | 22 ++++++++++++++++------ core/plugins/http.ts | 10 +++++----- core/plugins/tar.ts | 4 ++-- core/types.ts | 34 ++++++++++++++++++++++++++++++---- 5 files changed, 55 insertions(+), 19 deletions(-) diff --git a/core/build.ts b/core/build.ts index ea5087f..5ac02f2 100644 --- a/core/build.ts +++ b/core/build.ts @@ -91,8 +91,8 @@ export async function build(opts: BuildConfig = {}, filesystem: Promise; - [Symbol.asyncDispose](): Promise; }; export async function context(opts: BuildConfig = {}, filesystem = TheFileSystem): Promise { @@ -28,6 +27,11 @@ export async function context(opts: BuildConfig = {}, filesystem = TheFileSystem dispatchEvent(INIT_LOADING); // -- Per-build resource lifecycle ------------------------------------------- + // Create (or reuse) per-build resources, and ensure abort fires on dispose. + // + // Note: + // - We intentionally connect `abort.abort()` to `scope` disposal so that + // background work can stop when the build finishes. const disposables = new AsyncDisposableStack(); const abortController = new AbortController(); disposables.defer(() => abortController.abort()); @@ -36,8 +40,9 @@ export async function context(opts: BuildConfig = {}, filesystem = TheFileSystem filesystem: Context.opaque(await filesystem), assets: [], config: Context.opaque(createConfig("build", opts)), - disposables: Context.opaque(disposables), - abortSignal: Context.opaque(abortController.signal), + + scope: Context.opaque(disposables), + abort: Context.opaque(abortController), failedExtensionChecks: new Set(), failedManifestUrls: new Set(), @@ -115,9 +120,14 @@ export async function context(opts: BuildConfig = {}, filesystem = TheFileSystem state: StateContext, ...context_result, + // Enable `using ctx = await context(...)` for automatic cleanup + [Symbol.dispose]() { + void dispose(this as BuildContext); + }, + // Enable `await using ctx = await context(...)` for automatic cleanup [Symbol.asyncDispose]() { - return dispose(this as unknown as BuildContext); + return dispose(this as BuildContext); }, } } catch (e) { @@ -208,7 +218,7 @@ export async function dispose(build_ctx: BuildContext): Promise { await build_ctx?.dispose?.(); // Dispose per-build resources (aborts background fetches, etc.) - const disposables = fromContext("disposables", build_ctx.state); + const disposables = fromContext("scope", build_ctx.state); if (disposables) { await disposables.disposeAsync(); } diff --git a/core/plugins/http.ts b/core/plugins/http.ts index a21d082..f4c2470 100644 --- a/core/plugins/http.ts +++ b/core/plugins/http.ts @@ -164,8 +164,8 @@ export async function fetchAssets( const matches = Array.from(code.matchAll(rgx)) as RegExpMatchArray[]; const promises = matches.map(async ([, assetURL]) => { - const signal = fromContext("abortSignal", StateContext); - const { content: asset, url } = await fetchPkg(urlJoin(parentURL, assetURL), { signal }); + const abort = fromContext("abort", StateContext); + const { content: asset, url } = await fetchPkg(urlJoin(parentURL, assetURL), { signal: abort.signal }); // Store asset in virtual file system for bundle analyzer if (FileSystem) { @@ -231,7 +231,7 @@ export async function determineExtension( ? fromContext("failedExtensionChecks", StateContext) : null; const failedSet = failedExtChecks ?? new Set(); - const signal = StateContext ? fromContext("abortSignal", StateContext) : undefined; + const abort = StateContext ? fromContext("abort", StateContext) : undefined; let firstError: Error | undefined; @@ -247,10 +247,10 @@ export async function determineExtension( // Background refresh with extensionless URLs can 404 if the CDN doesn't consistently // redirect/resolve extensionless paths. if (headersOnly) { - const { url, contentType } = await fetchPkgHeaders(testUrl, { cacheMode: 'reload', signal }); + const { url, contentType } = await fetchPkgHeaders(testUrl, { cacheMode: 'reload', signal: abort?.signal }); return { url, contentType }; } else { - const { url, contentType, content } = await fetchPkg(testUrl, { cacheMode: 'normal', signal }); + const { url, contentType, content } = await fetchPkg(testUrl, { cacheMode: 'normal', signal: abort?.signal }); return { url, contentType, content }; } } catch (e) { diff --git a/core/plugins/tar.ts b/core/plugins/tar.ts index 8d7b804..f8e0340 100644 --- a/core/plugins/tar.ts +++ b/core/plugins/tar.ts @@ -525,8 +525,8 @@ export async function fetchAndExtractTarball( if (/^https?:\/\//.test(source)) { // HTTP: fetch from network / shared cache. dispatchEvent(LOGGER_INFO, `Fetching tarball candidate: ${source}`); - const signal = fromContext("abortSignal", StateContext); - const result = await fetchWithCache(source, { signal }); + const abort = fromContext("abort", StateContext); + const result = await fetchWithCache(source, { signal: abort?.signal }); response = result.response; // Build descriptive log message diff --git a/core/types.ts b/core/types.ts index 5442d0f..a5e6d68 100644 --- a/core/types.ts +++ b/core/types.ts @@ -79,18 +79,44 @@ export interface LocalState extends TarballState, record { filesystem: IFileSystem, /** - * Per-build resource disposal stack. + * Per-build resource scope. + * + * Anything that must be torn down at the end of the build (workers, + * wasm runtimes, in-flight background work, etc.) should be registered here. * * Registers cleanup callbacks (abort controllers, WASM handles, workers, * etc.) that run when the build finishes or the context is disposed. * Resources are released in **LIFO** order. * + * @example + * ```ts + * // Plugin-side cleanup + * const scope = fromContext('scope', StateContext); + * const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }); + * + * scope.defer(function () { + * worker.terminate(); + * }); + * ``` + * + * @example + * ```ts + * // Adopt a non-disposable value with a disposer + * scope.adopt(wasmRuntime, function (rt) { + * rt.close(); + * }); + * ``` + * * @see https://github.com/tc39/proposal-explicit-resource-management */ - disposables: AsyncDisposableStack, + scope: AsyncDisposableStack, /** - * Abort signal scoped to this build’s lifetime. + * Abort controller scoped to this build’s lifetime. + * Put simply, it allows you to cancel individual builds. + * + * Use this for fetches or long-running work that should stop when the build + * is canceled/disposed. * * Threaded through background fetch operations so they are cancelled * when the build finishes. Prevents resource leaks from fire-and-forget @@ -98,7 +124,7 @@ export interface LocalState extends TarballState, record { * * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal */ - abortSignal: AbortSignal, + abort: AbortController, /** * Versions -- knotmirror 0.0.1