{"record":{"id":"e9fcccb72233bd7f","repo":"slint-ui/slint","slug":"failed-to-create-weak-reference","errorCode":null,"errorMessage":"Failed to create weak reference","messagePattern":"Failed to create weak reference","errorType":"exception","errorClass":"napi::Error","httpStatus":null,"severity":"error","filePath":"api/node/rust/weak_ref.rs","lineNumber":65,"sourceCode":"///\n/// The reference doesn't prevent garbage collection.\n/// If V8 collects the value,\n/// [`get_unknown`](WeakValueRef::get_unknown) returns `None`.\npub struct WeakValueRef {\n    raw_ref: napi::sys::napi_ref,\n    raw_env: napi::sys::napi_env,\n}\n\nimpl WeakValueRef {\n    /// Create a weak reference to any JS value.\n    pub fn new<'a, T: JsValue<'a>>(env: &Env, value: &T) -> Result<Self> {\n        let raw_env = env.raw();\n        let raw_val = value.raw();\n        let mut raw_ref = std::ptr::null_mut();\n        // Safety: raw_env and raw_val are valid handles from napi-rs.\n        let status = unsafe { napi::sys::napi_create_reference(raw_env, raw_val, 0, &mut raw_ref) };\n        if status != napi::sys::Status::napi_ok {\n            return Err(napi::Error::new(\n                napi::Status::from(status),\n                \"Failed to create weak reference\",\n            ));\n        }\n        Ok(Self { raw_ref, raw_env })\n    }\n\n    /// Get the value back,\n    /// or `None` if it was garbage-collected.\n    pub fn get_unknown(&self) -> Option<Unknown<'_>> {\n        let mut value = std::ptr::null_mut();\n        // Safety: raw_env and raw_ref are valid (created in new, deleted in drop).\n        let status =\n            unsafe { napi::sys::napi_get_reference_value(self.raw_env, self.raw_ref, &mut value) };\n        if status != napi::sys::Status::napi_ok || value.is_null() {\n            return None;\n        }\n        // Safety: value is a live JS handle from the reference.","sourceCodeStart":47,"sourceCodeEnd":83,"githubUrl":"https://github.com/slint-ui/slint/blob/bb937076de3f7919766c1f25e2e969367cf77e9a/api/node/rust/weak_ref.rs#L47-L83","documentation":"The custom weak-reference wrapper in api/node/rust/weak_ref.rs calls the raw N-API napi_create_reference with a 0 (non-owning) refcount. If N-API returns anything other than napi_ok, the constructor throws 'Failed to create weak reference'. This typically indicates a V8/engine-level failure to create the reference rather than a caller error.","triggerScenarios":"Constructing the weak reference wrapper during Node.js shutdown or inside a finalizer where the environment is being torn down; creating a reference for a value in an invalid state at the engine level; mixing environments (using an env/raw value from another thread or isolate).","commonSituations":"Addons performing cleanup during process exit; multithreaded N-API usage without proper environment/threadsafe-function handling; native module loaded into a shutting-down worker.","solutions":["Avoid creating weak references during environment teardown/shutdown; defer or skip the reference creation and handle the missing reference gracefully.","Ensure the value handle and env used to build the reference come from the same, current N-API environment/thread.","Log the napi_status alongside the error to identify the precise engine failure and address the root cause (e.g. wrong env, GC finalizer context)."],"exampleFix":"// before\nlet weak = WeakRef::new(env, value); // may throw at teardown\n// after\nlet weak = match WeakRef::new(env, value) {\n  Ok(w) => Some(w),\n  Err(e) => { log::warn!(\"weak ref unavailable: {e}\"); None }\n};","handlingStrategy":"try-catch","validationCode":"if (process.env.NODE_ENV !== 'shutdown' && !envIsTearingDown) {\n  weak = new WeakRef(env, value);\n}","typeGuard":null,"tryCatchPattern":"let weak;\ntry {\n  weak = new WeakRef(env, value);\n} catch (e) {\n  console.warn('weak reference unavailable:', e.message);\n  weak = null;\n}","preventionTips":["Do not create weak references during environment teardown or finalizers.","Always use the env and value handles from the same thread/isolate.","Log the underlying napi_status for diagnosis.","Design the API so a missing weak reference is a recoverable condition."],"tags":["nodejs","napi","weak-reference","native"],"backgroundTag":"internal-invariant-violation","analyzedSha":"bb937076de3f7919766c1f25e2e969367cf77e9a","analyzedAt":"2026-09-16T01:37:20.251Z","contentChangedAt":"2026-09-16T01:37:20.251Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}