qiankun proxySand 沙箱

时间:2022-07-26
本文章向大家介绍qiankun proxySand 沙箱,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

qiankun 内为微应用实现了沙箱机制, 以实现js隔离的目的, 沙箱的重点在于初始化时对全局对象的copy 及代理

使用

const sand = new ProxySand(name)
sand.active() // 启动
sand.inacitve() // 关闭

属性

  • name 沙箱名
  • type 沙箱类型
    • Proxy proxy沙箱
    • Snapshot
    • LegacyProxy 旧沙箱实现
  • sandboxRunning 沙箱是否运行中
  • proxy 全局对象的proxy副本, 沙箱实体
  • active 启动沙箱
  • inactive 关闭沙箱

实现

沙箱的实现过程都在 constructor 实例的创建中

设置初始值

 this.name = name;
 this.type = SandBoxType.Proxy;
 const { updatedValueSet } = this;

 const self = this;
 const rawWindow = window;

复制window

const { fakeWindow, propertiesWithGetter } = createFakeWindow(rawWindow);

createFakeWindow

  • getOwnPropertyDescriptor 返回对象指定的属性配置
  • defineProperty 给对象添加一个属性并指定该属性的配置
  • hasOwnProperty 返回一个布尔值 ,表示某个对象是否含有指定的属性,而且此属性非原型链继承的
  • freeze 冻结对象:其他代码不能删除或更改任何属性
const rawObjectDefineProperty = Object.defineProperty;

function createFakeWindow(global: Window) {

  const propertiesWithGetter = new Map<PropertyKey, boolean>();
  const fakeWindow = {} as FakeWindow;


  Object.getOwnPropertyNames(global) // 获取全局对象属性
    .filter(p => { // 筛选不可修改属性
      const descriptor = Object.getOwnPropertyDescriptor(global, p);
      return !descriptor?.configurable;
    })
    .forEach(p => {

      // 获取属性配置
      const descriptor = Object.getOwnPropertyDescriptor(global, p);
        
      if (descriptor) {
          
        // 是否有get属性
        const hasGetter = Object.prototype.hasOwnProperty.call(descriptor, 'get');

        // 修改部分特殊属性为可修改
        if (
          p === 'top' ||
          p === 'parent' ||
          p === 'self' ||
          p === 'window' ||
          (process.env.NODE_ENV === 'test' && (p === 'mockTop' || p === 'mockSafariTop'))
        ) {
            
          // 属性可delete
          descriptor.configurable = true;   
     
          if (!hasGetter) {
            // 属性可修改
            descriptor.writable = true;
          }
        }

        // 记录可访问属性
        if (hasGetter) propertiesWithGetter.set(p, true);

        // 将属性绑定到新对象上,并冻结
        rawObjectDefineProperty(fakeWindow, p, Object.freeze(descriptor));
      }

    });

  return {
    fakeWindow,
    propertiesWithGetter,
  };
}

这里只将可修改属性绑定到fakeWindow上, 对于不可修改属性将直接使用window属性

创建window代理

// 目标标识映射   
const descriptorTargetMap = new Map<PropertyKey, SymbolTarget>();

    // fakeWindow 只绑定了部分window上的不可修改属性
    const hasOwnProperty = (key: PropertyKey) => fakeWindow.hasOwnProperty(key) || rawWindow.hasOwnProperty(key);
    
   
    const proxy = new Proxy(fakeWindow, {
        
       // 设置值
      set(target: FakeWindow, p: PropertyKey, value: any): boolean {

        // 沙箱是否运行中
        if (self.sandboxRunning) {
          
          target[p] = value;
          
          // set 缓存数据
          updatedValueSet.add(p);
          
          // 如果属性为 System, __cjsWrapper 模块加载器,将属性绑定到window上
          interceptSystemJsProps(p, value);
          return true;
        }
        
        if (process.env.NODE_ENV === 'development') {
          console.warn(`[qiankun] Set window.${p.toString()} while sandbox destroyed or inactive in ${name}!`);
        }

        // 在 strict-mode 下,Proxy 的 handler.set 返回 false 会抛出 TypeError,在沙箱卸载的情况下应该忽略错误
        return true;
      },
    
          

      // 获取值
      get(target: FakeWindow, p: PropertyKey): any {
        
        
        if (p === Symbol.unscopables) return unscopables;

        // widow, self 返回全局代理
        if (p === 'window' || p === 'self') {
          return proxy;
        }

        if (
          p === 'top' ||
          p === 'parent' ||
          (process.env.NODE_ENV === 'test' && (p === 'mockTop' || p === 'mockSafariTop'))
        ) {
          // if your master app in an iframe context, allow these props escape the sandbox
          // iframe 嵌套
          if (rawWindow === rawWindow.parent) {
            return proxy;
          }
          return (rawWindow as any)[p];
        }

        // 返回包装后的 hasOwnProperty
        if (p === 'hasOwnProperty') {
          return hasOwnProperty;
        }
        
        // 当访问作为文档时,标记要文档的符号。createElement可以知道是由哪个沙箱调用的动态追加补丁程序
        if (p === 'document') {
          
          // 为document挂载代理对象
          document[attachDocProxySymbol] = proxy;
            
          // 将删除函数放入微队列中
          nextTick(() => delete document[attachDocProxySymbol]);
          return document;
        }

        // 判断属性
        const value = propertiesWithGetter.has(p) ? (rawWindow as any)[p] : (target as any)[p] || (rawWindow as any)[p];
        return getTargetValue(rawWindow, value);
      },

      
      has(target: FakeWindow, p: string | number | symbol): boolean {
        return p in unscopables || p in target || p in rawWindow;
      },
        
      // 获取属性描述
      getOwnPropertyDescriptor(target: FakeWindow, p: string | number | symbol): PropertyDescriptor | undefined {
  
        if (target.hasOwnProperty(p)) {
          const descriptor = Object.getOwnPropertyDescriptor(target, p);
          // 缓存属性配置, 设置属性配置时使用
          descriptorTargetMap.set(p, 'target');
          return descriptor;
        }

        if (rawWindow.hasOwnProperty(p)) {
          const descriptor = Object.getOwnPropertyDescriptor(rawWindow, p);
         // 缓存属性配置, 设置属性配置时使用
          descriptorTargetMap.set(p, 'rawWindow');
          return descriptor;
        }

        return undefined;
      },

      // 返回属性列表
      ownKeys(target: FakeWindow): PropertyKey[] {
        return uniq(Reflect.ownKeys(rawWindow).concat(Reflect.ownKeys(target)));
      },
        
      // 设置属性配置
      defineProperty(target: Window, p: PropertyKey, attributes: PropertyDescriptor): boolean {
        const from = descriptorTargetMap.get(p);
          
        switch (from) {
          case 'rawWindow':
            return Reflect.defineProperty(rawWindow, p, attributes);
          default:
            return Reflect.defineProperty(target, p, attributes);
        }
      },
        
      // 属性删除
      deleteProperty(target: FakeWindow, p: string | number | symbol): boolean {
        if (target.hasOwnProperty(p)) {
          // @ts-ignore
          delete target[p];
          updatedValueSet.delete(p);

          return true;
        }

        return true;
      },
    });