init.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Initialize ASAR support in fs module.
  2. import { wrapFsWithAsar } from './asar-fs-wrapper';
  3. wrapFsWithAsar(require('fs'));
  4. // See ElectronRendererClient::DidCreateScriptContext.
  5. if ((globalThis as any).blinkfetch) {
  6. const keys = ['fetch', 'Response', 'FormData', 'Request', 'Headers'];
  7. for (const key of keys) {
  8. (globalThis as any)[key] = (globalThis as any)[`blink${key}`];
  9. }
  10. }
  11. // Hook child_process.fork.
  12. import cp = require('child_process'); // eslint-disable-line import/first
  13. const originalFork = cp.fork;
  14. cp.fork = (modulePath, args?, options?: cp.ForkOptions) => {
  15. // Parse optional args.
  16. if (args == null) {
  17. args = [];
  18. } else if (typeof args === 'object' && !Array.isArray(args)) {
  19. options = args as cp.ForkOptions;
  20. args = [];
  21. }
  22. // Fallback to original fork to report arg type errors.
  23. if (typeof modulePath !== 'string' || !Array.isArray(args) ||
  24. (typeof options !== 'object' && typeof options !== 'undefined')) {
  25. return originalFork(modulePath, args, options);
  26. }
  27. // When forking a child script, we setup a special environment to make
  28. // the electron binary run like upstream Node.js.
  29. options = options ?? {};
  30. options.env = Object.create(options.env || process.env);
  31. options.env!.ELECTRON_RUN_AS_NODE = '1';
  32. // On mac the child script runs in helper executable.
  33. if (!options.execPath && process.platform === 'darwin') {
  34. options.execPath = process.helperExecPath;
  35. }
  36. return originalFork(modulePath, args, options);
  37. };
  38. // Prevent Node from adding paths outside this app to search paths.
  39. import path = require('path'); // eslint-disable-line import/first
  40. const Module = require('module') as NodeJS.ModuleInternal;
  41. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep;
  42. const originalNodeModulePaths = Module._nodeModulePaths;
  43. Module._nodeModulePaths = function (from) {
  44. const paths: string[] = originalNodeModulePaths(from);
  45. const fromPath = path.resolve(from) + path.sep;
  46. // If "from" is outside the app then we do nothing.
  47. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  48. return paths.filter(function (candidate) {
  49. return candidate.startsWith(resourcesPathWithTrailingSlash);
  50. });
  51. } else {
  52. return paths;
  53. }
  54. };