type-utils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const { nativeImage, NativeImage } = process.electronBinding('native_image')
  2. export function isPromise (val: any) {
  3. return (
  4. val &&
  5. val.then &&
  6. val.then instanceof Function &&
  7. val.constructor &&
  8. val.constructor.reject &&
  9. val.constructor.reject instanceof Function &&
  10. val.constructor.resolve &&
  11. val.constructor.resolve instanceof Function
  12. )
  13. }
  14. const serializableTypes = [
  15. Boolean,
  16. Number,
  17. String,
  18. Date,
  19. Error,
  20. RegExp,
  21. ArrayBuffer
  22. ]
  23. export function isSerializableObject (value: any) {
  24. return value === null || ArrayBuffer.isView(value) || serializableTypes.some(type => value instanceof type)
  25. }
  26. const objectMap = function (source: Object, mapper: (value: any) => any) {
  27. const sourceEntries = Object.entries(source)
  28. const targetEntries = sourceEntries.map(([key, val]) => [key, mapper(val)])
  29. return Object.fromEntries(targetEntries)
  30. }
  31. export function serialize (value: any): any {
  32. if (value instanceof NativeImage) {
  33. return {
  34. buffer: value.toBitmap(),
  35. size: value.getSize(),
  36. __ELECTRON_SERIALIZED_NativeImage__: true
  37. }
  38. } else if (Array.isArray(value)) {
  39. return value.map(serialize)
  40. } else if (isSerializableObject(value)) {
  41. return value
  42. } else if (value instanceof Object) {
  43. return objectMap(value, serialize)
  44. } else {
  45. return value
  46. }
  47. }
  48. export function deserialize (value: any): any {
  49. if (value && value.__ELECTRON_SERIALIZED_NativeImage__) {
  50. return nativeImage.createFromBitmap(value.buffer, value.size)
  51. } else if (Array.isArray(value)) {
  52. return value.map(deserialize)
  53. } else if (isSerializableObject(value)) {
  54. return value
  55. } else if (value instanceof Object) {
  56. return objectMap(value, deserialize)
  57. } else {
  58. return value
  59. }
  60. }