From d51fda9e145e1481b5f0c27647c4b2d189074de6 Mon Sep 17 00:00:00 2001
From: Matt Mastracci <matthew@mastracci.com>
Date: Mon, 18 Dec 2023 08:48:52 -0700
Subject: [PATCH] fix(ext/napi): don't close handle scopes in NAPI as the
 pointers are invalid (#21629)

`napi_open_handle_scope` was returning a bogus handle_scope and we were
trying to close it in `napi_close_handle_scope`.

This is a bit of a challenge to test, but the following testcase comes
from #21601 and appears to be fixed by this.

```
import { decode } from "https://deno.land/std@0.209.0/encoding/base64.ts";
import sharp from "npm:sharp";

const img = 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEWq09/P7Lz1AAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==';
Deno.test("async", async () => {
  const id = setTimeout(() => Deno.exit(1), 1000);
  await sharp(decode(img)).toBuffer();
  await sharp(decode(img)).toBuffer();
  clearTimeout(id);
});
```
---
 cli/napi/js_native_api.rs | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/cli/napi/js_native_api.rs b/cli/napi/js_native_api.rs
index 7c9b3d4c7c..1d71aebbe0 100644
--- a/cli/napi/js_native_api.rs
+++ b/cli/napi/js_native_api.rs
@@ -1361,13 +1361,15 @@ fn napi_close_escapable_handle_scope(
 #[napi_sym::napi_sym]
 fn napi_close_handle_scope(
   env: *mut Env,
-  scope: napi_handle_scope,
+  _scope: napi_handle_scope,
 ) -> napi_status {
   let env = &mut *env;
   if env.open_handle_scopes == 0 {
     return napi_handle_scope_mismatch;
   }
-  let _scope = &mut *(scope as *mut v8::HandleScope);
+  // TODO: We are not opening a handle scope, therefore we cannot close it
+  // TODO: this is also not implemented in napi_open_handle_scope
+  // let _scope = &mut *(scope as *mut v8::HandleScope);
   env.open_handle_scopes -= 1;
   napi_ok
 }
@@ -2381,6 +2383,7 @@ fn napi_open_handle_scope(
 ) -> napi_status {
   let env = &mut *env;
 
+  // TODO: this is also not implemented in napi_close_handle_scope
   // *result = &mut env.scope() as *mut _ as napi_handle_scope;
   env.open_handle_scopes += 1;
   napi_ok