GoogleChromeLabs / GoogleChromeLabs/comlink
Add support for async transferHandle serializer/deserializer
- Dominant language
- TypeScript
- Stars
- 12.8k
- Forks
- 435
- PR merge metrics
- No merged PRs in 30d
Description
Im trying to create a transferHandle for Origin Private File System (OPFS) file handles since they are not cloneable in all browsers. This is the approach I tried:
```typescript
/**
* Check if the given value is a FileHandle and if it needs to be serialized.
* @param value
* @returns
*/
function canHandle(value: unknown): value is FileSystemFileHandle {
const isFileHandle = value instanceof FileSystemFileHandle
if (!isFileHandle) {
return false;
}
try {
// if we can clone the value, there is no need to serialize it
structuredClone(value);
return false;
} catch {
// if we can't clone the value, we need to serialize it
}
return true;
}
transferHandlers.set('FileHandle', {
canHandle,
serialize: async (ev) => {
const root = await navigator.storage.getDirectory();
return [await root.resolve(ev), []];
},
deserialize: async (path) => {
let directory = await navigator.storage.getDirectory();
const fileName = path.pop();
for (const part of path) {
directory = await directory.getDirectoryHandle(part, { create: true });
}
return directory.getDirectoryHandle(fileName, { create: true });
}
} satisfies TransferHandler);
```
However, I've run into an issue where the serializer and deserializer functions are not compatible with Promises. This is causing the transferHandle to not work as expected.
I'm wondering if there is another way to solve this issue or if I need to do the serialization manually. Any help or suggestions would be greatly appreciated.
Contributor guide
Assessment
This issue has not been assessed yet.