var that = this;
function __skpm_run (key, context) {
  that.context = context;

var exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/sourceManage/sourceManage.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/@skpm/fs/index.js":
/*!****************************************!*\
  !*** ./node_modules/@skpm/fs/index.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// TODO: async. Should probably be done with NSFileHandle and some notifications
// TODO: file descriptor. Needs to be done with NSFileHandle
var Buffer = __webpack_require__(/*! buffer */ "buffer").Buffer;
var utils = __webpack_require__(/*! ./utils */ "./node_modules/@skpm/fs/utils.js");
var parseStat = utils.parseStat;
var fsError = utils.fsError;
var fsErrorForPath = utils.fsErrorForPath;
var encodingFromOptions = utils.encodingFromOptions;
var NOT_IMPLEMENTED = utils.NOT_IMPLEMENTED;

module.exports.constants = {
  F_OK: 0,
  R_OK: 4,
  W_OK: 2,
  X_OK: 1,
};

module.exports.access = NOT_IMPLEMENTED("access");

module.exports.accessSync = function (path, mode) {
  mode = mode | 0;
  var fileManager = NSFileManager.defaultManager();

  switch (mode) {
    case 0:
      canAccess = module.exports.existsSync(path);
      break;
    case 1:
      canAccess = Boolean(Number(fileManager.isExecutableFileAtPath(path)));
      break;
    case 2:
      canAccess = Boolean(Number(fileManager.isWritableFileAtPath(path)));
      break;
    case 3:
      canAccess =
        Boolean(Number(fileManager.isExecutableFileAtPath(path))) &&
        Boolean(Number(fileManager.isWritableFileAtPath(path)));
      break;
    case 4:
      canAccess = Boolean(Number(fileManager.isReadableFileAtPath(path)));
      break;
    case 5:
      canAccess =
        Boolean(Number(fileManager.isReadableFileAtPath(path))) &&
        Boolean(Number(fileManager.isExecutableFileAtPath(path)));
      break;
    case 6:
      canAccess =
        Boolean(Number(fileManager.isReadableFileAtPath(path))) &&
        Boolean(Number(fileManager.isWritableFileAtPath(path)));
      break;
    case 7:
      canAccess =
        Boolean(Number(fileManager.isReadableFileAtPath(path))) &&
        Boolean(Number(fileManager.isWritableFileAtPath(path))) &&
        Boolean(Number(fileManager.isExecutableFileAtPath(path)));
      break;
  }

  if (!canAccess) {
    throw new Error("Can't access " + String(path));
  }
};

module.exports.appendFile = NOT_IMPLEMENTED("appendFile");

module.exports.appendFileSync = function (file, data, options) {
  if (!module.exports.existsSync(file)) {
    return module.exports.writeFileSync(file, data, options);
  }

  var handle = NSFileHandle.fileHandleForWritingAtPath(file);
  handle.seekToEndOfFile();

  var encoding = encodingFromOptions(options, "utf8");

  var nsdata = Buffer.from(
    data,
    encoding === "NSData" || encoding === "buffer" ? undefined : encoding
  ).toNSData();

  handle.writeData(nsdata);
};

module.exports.chmod = NOT_IMPLEMENTED("chmod");

module.exports.chmodSync = function (path, mode) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  fileManager.setAttributes_ofItemAtPath_error(
    {
      NSFilePosixPermissions: mode,
    },
    path,
    err
  );

  if (err.value() !== null) {
    throw fsErrorForPath(path, undefined, err.value());
  }
};

module.exports.chown = NOT_IMPLEMENTED("chown");
module.exports.chownSync = NOT_IMPLEMENTED("chownSync");

module.exports.close = NOT_IMPLEMENTED("close");
module.exports.closeSync = NOT_IMPLEMENTED("closeSync");

module.exports.copyFile = NOT_IMPLEMENTED("copyFile");

module.exports.copyFileSync = function (path, dest, flags) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  fileManager.copyItemAtPath_toPath_error(path, dest, err);

  if (err.value() !== null) {
    throw fsErrorForPath(path, false, err.value());
  }
};

module.exports.createReadStream = NOT_IMPLEMENTED("createReadStream");
module.exports.createWriteStream = NOT_IMPLEMENTED("createWriteStream");

module.exports.exists = NOT_IMPLEMENTED("exists");

module.exports.existsSync = function (path) {
  var fileManager = NSFileManager.defaultManager();
  return Boolean(Number(fileManager.fileExistsAtPath(path)));
};

module.exports.fchmod = NOT_IMPLEMENTED("fchmod");
module.exports.fchmodSync = NOT_IMPLEMENTED("fchmodSync");
module.exports.fchown = NOT_IMPLEMENTED("fchown");
module.exports.fchownSync = NOT_IMPLEMENTED("fchownSync");
module.exports.fdatasync = NOT_IMPLEMENTED("fdatasync");
module.exports.fdatasyncSync = NOT_IMPLEMENTED("fdatasyncSync");
module.exports.fstat = NOT_IMPLEMENTED("fstat");
module.exports.fstatSync = NOT_IMPLEMENTED("fstatSync");
module.exports.fsync = NOT_IMPLEMENTED("fsync");
module.exports.fsyncSync = NOT_IMPLEMENTED("fsyncSync");
module.exports.ftruncate = NOT_IMPLEMENTED("ftruncate");
module.exports.ftruncateSync = NOT_IMPLEMENTED("ftruncateSync");
module.exports.futimes = NOT_IMPLEMENTED("futimes");
module.exports.futimesSync = NOT_IMPLEMENTED("futimesSync");

module.exports.lchmod = NOT_IMPLEMENTED("lchmod");
module.exports.lchmodSync = NOT_IMPLEMENTED("lchmodSync");
module.exports.lchown = NOT_IMPLEMENTED("lchown");
module.exports.lchownSync = NOT_IMPLEMENTED("lchownSync");

module.exports.link = NOT_IMPLEMENTED("link");

module.exports.linkSync = function (existingPath, newPath) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  fileManager.linkItemAtPath_toPath_error(existingPath, newPath, err);

  if (err.value() !== null) {
    throw fsErrorForPath(existingPath, undefined, err.value());
  }
};

module.exports.lstat = NOT_IMPLEMENTED("lstat");

module.exports.lstatSync = function (path) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var result = fileManager.attributesOfItemAtPath_error(path, err);

  if (err.value() !== null) {
    throw fsErrorForPath(path, undefined, err.value());
  }

  return parseStat(result);
};

module.exports.mkdir = NOT_IMPLEMENTED("mkdir");

module.exports.mkdirSync = function (path, options) {
  var mode = 0o777;
  var recursive = false;
  if (options && options.mode) {
    mode = options.mode;
  }
  if (options && options.recursive) {
    recursive = options.recursive;
  }
  if (typeof options === "number") {
    mode = options;
  }
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error(
    path,
    recursive,
    {
      NSFilePosixPermissions: mode,
    },
    err
  );

  if (err.value() !== null) {
    throw new Error(err.value());
  }
};

module.exports.mkdtemp = NOT_IMPLEMENTED("mkdtemp");

module.exports.mkdtempSync = function (path) {
  function makeid() {
    var text = "";
    var possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 6; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }
  var tempPath = path + makeid();
  module.exports.mkdirSync(tempPath);
  return tempPath;
};

module.exports.open = NOT_IMPLEMENTED("open");
module.exports.openSync = NOT_IMPLEMENTED("openSync");

module.exports.read = NOT_IMPLEMENTED("read");

module.exports.readdir = NOT_IMPLEMENTED("readdir");

module.exports.readdirSync = function (path, options) {
  var encoding = encodingFromOptions(options, "utf8");
  var fileManager = NSFileManager.defaultManager();
  var paths = fileManager.subpathsAtPath(path);
  var arr = [];
  for (var i = 0; i < paths.length; i++) {
    var pathName = paths[i];
    arr.push(encoding === "buffer" ? Buffer.from(pathName) : String(pathName));
  }
  return arr;
};

module.exports.readFile = NOT_IMPLEMENTED("readFile");

module.exports.readFileSync = function (path, options) {
  var encoding = encodingFromOptions(options, "buffer");
  var fileManager = NSFileManager.defaultManager();
  var data = fileManager.contentsAtPath(path);
  if (!data) {
    throw fsErrorForPath(path, false);
  }

  var buffer = Buffer.from(data);

  if (encoding === "buffer") {
    return buffer;
  } else if (encoding === "NSData") {
    return buffer.toNSData();
  } else {
    return buffer.toString(encoding);
  }
};

module.exports.readlink = NOT_IMPLEMENTED("readlink");

module.exports.readlinkSync = function (path) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var result = fileManager.destinationOfSymbolicLinkAtPath_error(path, err);

  if (err.value() !== null) {
    throw fsErrorForPath(path, undefined, err.value());
  }

  return String(result);
};

module.exports.readSync = NOT_IMPLEMENTED("readSync");

module.exports.realpath = NOT_IMPLEMENTED("realpath");
module.exports.realpath.native = NOT_IMPLEMENTED("realpath.native");

module.exports.realpathSync = function (path) {
  return String(
    NSString.stringWithString(path).stringByResolvingSymlinksInPath()
  );
};

module.exports.realpathSync.native = NOT_IMPLEMENTED("realpathSync.native");

module.exports.rename = NOT_IMPLEMENTED("rename");

module.exports.renameSync = function (oldPath, newPath) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  fileManager.moveItemAtPath_toPath_error(oldPath, newPath, err);

  var error = err.value();

  if (error !== null) {
    // if there is already a file, we need to overwrite it
    if (
      String(error.domain()) === "NSCocoaErrorDomain" &&
      Number(error.code()) === 516
    ) {
      var err2 = MOPointer.alloc().init();
      fileManager.replaceItemAtURL_withItemAtURL_backupItemName_options_resultingItemURL_error(
        NSURL.fileURLWithPath(newPath),
        NSURL.fileURLWithPath(oldPath),
        null,
        NSFileManagerItemReplacementUsingNewMetadataOnly,
        null,
        err2
      );
      if (err2.value() !== null) {
        throw fsErrorForPath(oldPath, undefined, err2.value());
      }
    } else {
      throw fsErrorForPath(oldPath, undefined, error);
    }
  }
};

module.exports.rmdir = NOT_IMPLEMENTED("rmdir");

module.exports.rmdirSync = function (path) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var isDirectory = module.exports.lstatSync(path).isDirectory();
  if (!isDirectory) {
    throw fsError("ENOTDIR", {
      path: path,
      syscall: "rmdir",
    });
  }
  fileManager.removeItemAtPath_error(path, err);

  if (err.value() !== null) {
    throw fsErrorForPath(path, true, err.value(), "rmdir");
  }
};

module.exports.stat = NOT_IMPLEMENTED("stat");

// the only difference with lstat is that we resolve symlinks
//
// > lstat() is identical to stat(), except that if pathname is a symbolic
// > link, then it returns information about the link itself, not the file
// > that it refers to.
// http://man7.org/linux/man-pages/man2/lstat.2.html
module.exports.statSync = function (path) {
  return module.exports.lstatSync(module.exports.realpathSync(path));
};

module.exports.symlink = NOT_IMPLEMENTED("symlink");

module.exports.symlinkSync = function (target, path) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var result = fileManager.createSymbolicLinkAtPath_withDestinationPath_error(
    path,
    target,
    err
  );

  if (err.value() !== null) {
    throw new Error(err.value());
  }
};

module.exports.truncate = NOT_IMPLEMENTED("truncate");

module.exports.truncateSync = function (path, len) {
  var hFile = NSFileHandle.fileHandleForUpdatingAtPath(sFilePath);
  hFile.truncateFileAtOffset(len || 0);
  hFile.closeFile();
};

module.exports.unlink = NOT_IMPLEMENTED("unlink");

module.exports.unlinkSync = function (path) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var isDirectory = module.exports.lstatSync(path).isDirectory();
  if (isDirectory) {
    throw fsError("EPERM", {
      path: path,
      syscall: "unlink",
    });
  }
  var result = fileManager.removeItemAtPath_error(path, err);

  if (err.value() !== null) {
    throw fsErrorForPath(path, false, err.value());
  }
};

module.exports.unwatchFile = NOT_IMPLEMENTED("unwatchFile");

module.exports.utimes = NOT_IMPLEMENTED("utimes");

module.exports.utimesSync = function (path, aTime, mTime) {
  var err = MOPointer.alloc().init();
  var fileManager = NSFileManager.defaultManager();
  var result = fileManager.setAttributes_ofItemAtPath_error(
    {
      NSFileModificationDate: aTime,
    },
    path,
    err
  );

  if (err.value() !== null) {
    throw fsErrorForPath(path, undefined, err.value());
  }
};

module.exports.watch = NOT_IMPLEMENTED("watch");
module.exports.watchFile = NOT_IMPLEMENTED("watchFile");

module.exports.write = NOT_IMPLEMENTED("write");

module.exports.writeFile = NOT_IMPLEMENTED("writeFile");

module.exports.writeFileSync = function (path, data, options) {
  var encoding = encodingFromOptions(options, "utf8");

  var nsdata = Buffer.from(
    data,
    encoding === "NSData" || encoding === "buffer" ? undefined : encoding
  ).toNSData();

  nsdata.writeToFile_atomically(path, true);
};

module.exports.writeSync = NOT_IMPLEMENTED("writeSync");


/***/ }),

/***/ "./node_modules/@skpm/fs/utils.js":
/*!****************************************!*\
  !*** ./node_modules/@skpm/fs/utils.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports.parseStat = function parseStat(result) {
  return {
    dev: String(result.NSFileDeviceIdentifier),
    // ino: 48064969, The file system specific "Inode" number for the file.
    mode: result.NSFileType | result.NSFilePosixPermissions,
    nlink: Number(result.NSFileReferenceCount),
    uid: String(result.NSFileOwnerAccountID),
    gid: String(result.NSFileGroupOwnerAccountID),
    // rdev: 0, A numeric device identifier if the file is considered "special".
    size: Number(result.NSFileSize),
    // blksize: 4096, The file system block size for i/o operations.
    // blocks: 8, The number of blocks allocated for this file.
    atimeMs:
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000,
    mtimeMs:
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000,
    ctimeMs:
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000,
    birthtimeMs:
      Number(result.NSFileCreationDate.timeIntervalSince1970()) * 1000,
    atime: new Date(
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000 + 0.5
    ), // the 0.5 comes from the node source. Not sure why it's added but in doubt...
    mtime: new Date(
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000 + 0.5
    ),
    ctime: new Date(
      Number(result.NSFileModificationDate.timeIntervalSince1970()) * 1000 + 0.5
    ),
    birthtime: new Date(
      Number(result.NSFileCreationDate.timeIntervalSince1970()) * 1000 + 0.5
    ),
    isBlockDevice: function () {
      return result.NSFileType === NSFileTypeBlockSpecial;
    },
    isCharacterDevice: function () {
      return result.NSFileType === NSFileTypeCharacterSpecial;
    },
    isDirectory: function () {
      return result.NSFileType === NSFileTypeDirectory;
    },
    isFIFO: function () {
      return false;
    },
    isFile: function () {
      return result.NSFileType === NSFileTypeRegular;
    },
    isSocket: function () {
      return result.NSFileType === NSFileTypeSocket;
    },
    isSymbolicLink: function () {
      return result.NSFileType === NSFileTypeSymbolicLink;
    },
  };
};

var ERRORS = {
  EPERM: {
    message: "operation not permitted",
    errno: -1,
  },
  ENOENT: {
    message: "no such file or directory",
    errno: -2,
  },
  EACCES: {
    message: "permission denied",
    errno: -13,
  },
  ENOTDIR: {
    message: "not a directory",
    errno: -20,
  },
  EISDIR: {
    message: "illegal operation on a directory",
    errno: -21,
  },
};

function fsError(code, options) {
  var error = new Error(
    code +
      ": " +
      ERRORS[code].message +
      ", " +
      (options.syscall || "") +
      (options.path ? " '" + options.path + "'" : "")
  );

  Object.keys(options).forEach(function (k) {
    error[k] = options[k];
  });

  error.code = code;
  error.errno = ERRORS[code].errno;

  return error;
}

module.exports.fsError = fsError;

module.exports.fsErrorForPath = function fsErrorForPath(
  path,
  shouldBeDir,
  err,
  syscall
) {
  var fileManager = NSFileManager.defaultManager();
  var doesExist = fileManager.fileExistsAtPath(path);
  if (!doesExist) {
    return fsError("ENOENT", {
      path: path,
      syscall: syscall || "open",
    });
  }
  var isReadable = fileManager.isReadableFileAtPath(path);
  if (!isReadable) {
    return fsError("EACCES", {
      path: path,
      syscall: syscall || "open",
    });
  }
  if (typeof shouldBeDir !== "undefined") {
    var isDirectory = __webpack_require__(/*! ./index */ "./node_modules/@skpm/fs/index.js").lstatSync(path).isDirectory();
    if (isDirectory && !shouldBeDir) {
      return fsError("EISDIR", {
        path: path,
        syscall: syscall || "read",
      });
    } else if (!isDirectory && shouldBeDir) {
      return fsError("ENOTDIR", {
        path: path,
        syscall: syscall || "read",
      });
    }
  }
  return new Error(err || "Unknown error while manipulating " + path);
};

module.exports.encodingFromOptions = function encodingFromOptions(
  options,
  defaultValue
) {
  return options && options.encoding
    ? String(options.encoding)
    : options
    ? String(options)
    : defaultValue;
};

module.exports.NOT_IMPLEMENTED = function NOT_IMPLEMENTED(name) {
  return function () {
    throw new Error(
      "fs." +
        name +
        " is not implemented yet. If you feel like implementing it, any contribution will be gladly accepted on https://github.com/skpm/fs"
    );
  };
};


/***/ }),

/***/ "./node_modules/@skpm/timers/immediate.js":
/*!************************************************!*\
  !*** ./node_modules/@skpm/timers/immediate.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals coscript, sketch */
var timeout = __webpack_require__(/*! ./timeout */ "./node_modules/@skpm/timers/timeout.js")

function setImmediate(func, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
  return timeout.setTimeout(func, 0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
}

function clearImmediate(id) {
  return timeout.clearTimeout(id)
}

module.exports = {
  setImmediate: setImmediate,
  clearImmediate: clearImmediate
}


/***/ }),

/***/ "./node_modules/@skpm/timers/test-if-fiber.js":
/*!****************************************************!*\
  !*** ./node_modules/@skpm/timers/test-if-fiber.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function () {
  return typeof coscript !== 'undefined' && coscript.createFiber
}


/***/ }),

/***/ "./node_modules/@skpm/timers/timeout.js":
/*!**********************************************!*\
  !*** ./node_modules/@skpm/timers/timeout.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals coscript, sketch */
var fiberAvailable = __webpack_require__(/*! ./test-if-fiber */ "./node_modules/@skpm/timers/test-if-fiber.js")

var setTimeout
var clearTimeout

var fibers = []

if (fiberAvailable()) {
  var fibers = []

  setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    // fibers takes care of keeping coscript around
    var id = fibers.length
    fibers.push(coscript.scheduleWithInterval_jsFunction(
      (delay || 0) / 1000,
      function () {
        func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
      }
    ))
    return id
  }

  clearTimeout = function (id) {
    var timeout = fibers[id]
    if (timeout) {
      timeout.cancel() // fibers takes care of keeping coscript around
      fibers[id] = undefined // garbage collect the fiber
    }
  }
} else {
  setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    coscript.shouldKeepAround = true
    var id = fibers.length
    fibers.push(true)
    coscript.scheduleWithInterval_jsFunction(
      (delay || 0) / 1000,
      function () {
        if (fibers[id]) { // if not cleared
          func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
        }
        clearTimeout(id)
        if (fibers.every(function (_id) { return !_id })) { // if everything is cleared
          coscript.shouldKeepAround = false
        }
      }
    )
    return id
  }

  clearTimeout = function (id) {
    fibers[id] = false
  }
}

module.exports = {
  setTimeout: setTimeout,
  clearTimeout: clearTimeout
}


/***/ }),

/***/ "./node_modules/cocoascript-class/lib/index.js":
/*!*****************************************************!*\
  !*** ./node_modules/cocoascript-class/lib/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SuperCall = undefined;
exports.default = ObjCClass;

var _runtime = __webpack_require__(/*! ./runtime.js */ "./node_modules/cocoascript-class/lib/runtime.js");

exports.SuperCall = _runtime.SuperCall;

// super when returnType is id and args are void
// id objc_msgSendSuper(struct objc_super *super, SEL op, void)

const SuperInit = (0, _runtime.SuperCall)(NSStringFromSelector("init"), [], { type: "@" });

// Returns a real ObjC class. No need to use new.
function ObjCClass(defn) {
  const superclass = defn.superclass || NSObject;
  const className = (defn.className || defn.classname || "ObjCClass") + NSUUID.UUID().UUIDString();
  const reserved = new Set(['className', 'classname', 'superclass']);
  var cls = MOClassDescription.allocateDescriptionForClassWithName_superclass_(className, superclass);
  // Add each handler to the class description
  const ivars = [];
  for (var key in defn) {
    const v = defn[key];
    if (typeof v == 'function' && key !== 'init') {
      var selector = NSSelectorFromString(key);
      cls.addInstanceMethodWithSelector_function_(selector, v);
    } else if (!reserved.has(key)) {
      ivars.push(key);
      cls.addInstanceVariableWithName_typeEncoding(key, "@");
    }
  }

  cls.addInstanceMethodWithSelector_function_(NSSelectorFromString('init'), function () {
    const self = SuperInit.call(this);
    ivars.map(name => {
      Object.defineProperty(self, name, {
        get() {
          return getIvar(self, name);
        },
        set(v) {
          (0, _runtime.object_setInstanceVariable)(self, name, v);
        }
      });
      self[name] = defn[name];
    });
    // If there is a passsed-in init funciton, call it now.
    if (typeof defn.init == 'function') defn.init.call(this);
    return self;
  });

  return cls.registerClass();
};

function getIvar(obj, name) {
  const retPtr = MOPointer.new();
  (0, _runtime.object_getInstanceVariable)(obj, name, retPtr);
  return retPtr.value().retain().autorelease();
}

/***/ }),

/***/ "./node_modules/cocoascript-class/lib/runtime.js":
/*!*******************************************************!*\
  !*** ./node_modules/cocoascript-class/lib/runtime.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SuperCall = SuperCall;
exports.CFunc = CFunc;
const objc_super_typeEncoding = '{objc_super="receiver"@"super_class"#}';

// You can store this to call your function. this must be bound to the current instance.
function SuperCall(selector, argTypes, returnType) {
  const func = CFunc("objc_msgSendSuper", [{ type: '^' + objc_super_typeEncoding }, { type: ":" }, ...argTypes], returnType);
  return function (...args) {
    const struct = make_objc_super(this, this.superclass());
    const structPtr = MOPointer.alloc().initWithValue_(struct);
    return func(structPtr, selector, ...args);
  };
}

// Recursively create a MOStruct
function makeStruct(def) {
  if (typeof def !== 'object' || Object.keys(def).length == 0) {
    return def;
  }
  const name = Object.keys(def)[0];
  const values = def[name];

  const structure = MOStruct.structureWithName_memberNames_runtime(name, Object.keys(values), Mocha.sharedRuntime());

  Object.keys(values).map(member => {
    structure[member] = makeStruct(values[member]);
  });

  return structure;
}

function make_objc_super(self, cls) {
  return makeStruct({
    objc_super: {
      receiver: self,
      super_class: cls
    }
  });
}

// Due to particularities of the JS bridge, we can't call into MOBridgeSupport objects directly
// But, we can ask key value coding to do the dirty work for us ;)
function setKeys(o, d) {
  const funcDict = NSMutableDictionary.dictionary();
  funcDict.o = o;
  Object.keys(d).map(k => funcDict.setValue_forKeyPath(d[k], "o." + k));
}

// Use any C function, not just ones with BridgeSupport
function CFunc(name, args, retVal) {
  function makeArgument(a) {
    if (!a) return null;
    const arg = MOBridgeSupportArgument.alloc().init();
    setKeys(arg, {
      type64: a.type
    });
    return arg;
  }
  const func = MOBridgeSupportFunction.alloc().init();
  setKeys(func, {
    name: name,
    arguments: args.map(makeArgument),
    returnValue: makeArgument(retVal)
  });
  return func;
}

/*
@encode(char*) = "*"
@encode(id) = "@"
@encode(Class) = "#"
@encode(void*) = "^v"
@encode(CGRect) = "{CGRect={CGPoint=dd}{CGSize=dd}}"
@encode(SEL) = ":"
*/

function addStructToBridgeSupport(key, structDef) {
  // OK, so this is probably the nastiest hack in this file.
  // We go modify MOBridgeSupportController behind its back and use kvc to add our own definition
  // There isn't another API for this though. So the only other way would be to make a real bridgesupport file.
  const symbols = MOBridgeSupportController.sharedController().valueForKey('symbols');
  if (!symbols) throw Error("Something has changed within bridge support so we can't add our definitions");
  // If someone already added this definition, don't re-register it.
  if (symbols[key] !== null) return;
  const def = MOBridgeSupportStruct.alloc().init();
  setKeys(def, {
    name: key,
    type: structDef.type
  });
  symbols[key] = def;
};

// This assumes the ivar is an object type. Return value is pretty useless.
const object_getInstanceVariable = exports.object_getInstanceVariable = CFunc("object_getInstanceVariable", [{ type: "@" }, { type: '*' }, { type: "^@" }], { type: "^{objc_ivar=}" });
// Again, ivar is of object type
const object_setInstanceVariable = exports.object_setInstanceVariable = CFunc("object_setInstanceVariable", [{ type: "@" }, { type: '*' }, { type: "@" }], { type: "^{objc_ivar=}" });

// We need Mocha to understand what an objc_super is so we can use it as a function argument
addStructToBridgeSupport('objc_super', { type: objc_super_typeEncoding });

/***/ }),

/***/ "./node_modules/promise-polyfill/lib/index.js":
/*!****************************************************!*\
  !*** ./node_modules/promise-polyfill/lib/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setTimeout, setImmediate) {

/**
 * @this {Promise}
 */
function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(
    function(value) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    },
    function(reason) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        // @ts-ignore
        return constructor.reject(reason);
      });
    }
  );
}

// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;

function isArray(x) {
  return Boolean(x && typeof x.length !== 'undefined');
}

function noop() {}

// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
  return function() {
    fn.apply(thisArg, arguments);
  };
}

/**
 * @constructor
 * @param {Function} fn
 */
function Promise(fn) {
  if (!(this instanceof Promise))
    throw new TypeError('Promises must be constructed via new');
  if (typeof fn !== 'function') throw new TypeError('not a function');
  /** @type {!number} */
  this._state = 0;
  /** @type {!boolean} */
  this._handled = false;
  /** @type {Promise|undefined} */
  this._value = undefined;
  /** @type {!Array<!Function>} */
  this._deferreds = [];

  doResolve(fn, this);
}

function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
  Promise._immediateFn(function() {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}

function resolve(self, newValue) {
  try {
    // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
    if (newValue === self)
      throw new TypeError('A promise cannot be resolved with itself.');
    if (
      newValue &&
      (typeof newValue === 'object' || typeof newValue === 'function')
    ) {
      var then = newValue.then;
      if (newValue instanceof Promise) {
        self._state = 3;
        self._value = newValue;
        finale(self);
        return;
      } else if (typeof then === 'function') {
        doResolve(bind(then, newValue), self);
        return;
      }
    }
    self._state = 1;
    self._value = newValue;
    finale(self);
  } catch (e) {
    reject(self, e);
  }
}

function reject(self, newValue) {
  self._state = 2;
  self._value = newValue;
  finale(self);
}

function finale(self) {
  if (self._state === 2 && self._deferreds.length === 0) {
    Promise._immediateFn(function() {
      if (!self._handled) {
        Promise._unhandledRejectionFn(self._value);
      }
    });
  }

  for (var i = 0, len = self._deferreds.length; i < len; i++) {
    handle(self, self._deferreds[i]);
  }
  self._deferreds = null;
}

/**
 * @constructor
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  this.promise = promise;
}

/**
 * Take a potentially misbehaving resolver function and make sure
 * onFulfilled and onRejected are only called once.
 *
 * Makes no guarantees about asynchrony.
 */
function doResolve(fn, self) {
  var done = false;
  try {
    fn(
      function(value) {
        if (done) return;
        done = true;
        resolve(self, value);
      },
      function(reason) {
        if (done) return;
        done = true;
        reject(self, reason);
      }
    );
  } catch (ex) {
    if (done) return;
    done = true;
    reject(self, ex);
  }
}

Promise.prototype['catch'] = function(onRejected) {
  return this.then(null, onRejected);
};

Promise.prototype.then = function(onFulfilled, onRejected) {
  // @ts-ignore
  var prom = new this.constructor(noop);

  handle(this, new Handler(onFulfilled, onRejected, prom));
  return prom;
};

Promise.prototype['finally'] = finallyConstructor;

Promise.all = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.all accepts an array'));
    }

    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(
              val,
              function(val) {
                res(i, val);
              },
              reject
            );
            return;
          }
        }
        args[i] = val;
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
};

Promise.resolve = function(value) {
  if (value && typeof value === 'object' && value.constructor === Promise) {
    return value;
  }

  return new Promise(function(resolve) {
    resolve(value);
  });
};

Promise.reject = function(value) {
  return new Promise(function(resolve, reject) {
    reject(value);
  });
};

Promise.race = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.race accepts an array'));
    }

    for (var i = 0, len = arr.length; i < len; i++) {
      Promise.resolve(arr[i]).then(resolve, reject);
    }
  });
};

// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
  // @ts-ignore
  (typeof setImmediate === 'function' &&
    function(fn) {
      // @ts-ignore
      setImmediate(fn);
    }) ||
  function(fn) {
    setTimeoutFunc(fn, 0);
  };

Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  if (typeof console !== 'undefined' && console) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  }
};

module.exports = Promise;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["setTimeout"], __webpack_require__(/*! ./node_modules/@skpm/timers/immediate.js */ "./node_modules/@skpm/timers/immediate.js")["setImmediate"]))

/***/ }),

/***/ "./node_modules/sketch-polyfill-fetch/lib/form-data.js":
/*!*************************************************************!*\
  !*** ./node_modules/sketch-polyfill-fetch/lib/form-data.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var Buffer
try {
  Buffer = __webpack_require__(/*! buffer */ "buffer").Buffer
} catch (err) {}
var util
try {
  util = __webpack_require__(/*! util */ "util")
} catch (err) {}

var boundary = "Boundary-" + NSUUID.UUID().UUIDString()

module.exports = function FormData() {
  var data = NSMutableData.data()
  return {
    _boundary: boundary,
    _isFormData: true,
    _data: data,
    append: function(field, value) {
      data.appendData(
        NSString.alloc()
          .initWithString("--" + boundary + "\r\n")
          .dataUsingEncoding(NSUTF8StringEncoding)
      )
      data.appendData(
        NSString.alloc()
          .initWithString("Content-Disposition: form-data; name=\"" + field + "\"")
          .dataUsingEncoding(NSUTF8StringEncoding)
      )
      if (util ? util.isString(value) : typeof value === 'string') {
        data.appendData(
          NSString.alloc()
            .initWithString("\r\n\r\n" + value)
            .dataUsingEncoding(NSUTF8StringEncoding)
        )
      } else if (value && value.fileName && value.data && value.mimeType) {
        var nsdata
        if (Buffer && Buffer.isBuffer(value.data)) {
          nsdata = value.data.toNSData()
        } else if (value.data.isKindOfClass && value.data.isKindOfClass(NSData) == 1) {
          nsdata = value.data
        } else {
          throw new Error('unknown data type')
        }
        data.appendData(
          NSString.alloc()
            .initWithString("; filename=\"" + value.fileName + "\"\r\nContent-Type: " + value.mimeType + "\r\n\r\n")
            .dataUsingEncoding(NSUTF8StringEncoding)
        )
        data.appendData(nsdata)
      } else {
        throw new Error('unknown value type')
      }
      data.appendData(
        NSString.alloc()
          .initWithString("\r\n")
          .dataUsingEncoding(NSUTF8StringEncoding)
      )
    }
  }
}


/***/ }),

/***/ "./node_modules/sketch-polyfill-fetch/lib/index.js":
/*!*********************************************************!*\
  !*** ./node_modules/sketch-polyfill-fetch/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Promise) {/* globals NSJSONSerialization NSJSONWritingPrettyPrinted NSDictionary NSHTTPURLResponse NSString NSASCIIStringEncoding NSUTF8StringEncoding coscript NSURL NSMutableURLRequest NSMutableData NSURLConnection */
var Buffer;
try {
  Buffer = __webpack_require__(/*! buffer */ "buffer").Buffer;
} catch (err) {}

function response(httpResponse, data) {
  var keys = [];
  var all = [];
  var headers = {};
  var header;

  for (var i = 0; i < httpResponse.allHeaderFields().allKeys().length; i++) {
    var key = httpResponse
      .allHeaderFields()
      .allKeys()
      [i].toLowerCase();
    var value = String(httpResponse.allHeaderFields()[key]);
    keys.push(key);
    all.push([key, value]);
    header = headers[key];
    headers[key] = header ? header + "," + value : value;
  }

  return {
    ok: ((httpResponse.statusCode() / 200) | 0) == 1, // 200-399
    status: Number(httpResponse.statusCode()),
    statusText: String(
      NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode())
    ),
    useFinalURL: true,
    url: String(httpResponse.URL().absoluteString()),
    clone: response.bind(this, httpResponse, data),
    text: function() {
      return new Promise(function(resolve, reject) {
        const str = String(
          NSString.alloc().initWithData_encoding(data, NSASCIIStringEncoding)
        );
        if (str) {
          resolve(str);
        } else {
          reject(new Error("Couldn't parse body"));
        }
      });
    },
    json: function() {
      return new Promise(function(resolve, reject) {
        var str = String(
          NSString.alloc().initWithData_encoding(data, NSUTF8StringEncoding)
        );
        if (str) {
          // parse errors are turned into exceptions, which cause promise to be rejected
          var obj = JSON.parse(str);
          resolve(obj);
        } else {
          reject(
            new Error(
              "Could not parse JSON because it is not valid UTF-8 data."
            )
          );
        }
      });
    },
    blob: function() {
      return Promise.resolve(data);
    },
    arrayBuffer: function() {
      return Promise.resolve(Buffer.from(data));
    },
    headers: {
      keys: function() {
        return keys;
      },
      entries: function() {
        return all;
      },
      get: function(n) {
        return headers[n.toLowerCase()];
      },
      has: function(n) {
        return n.toLowerCase() in headers;
      }
    }
  };
}

// We create one ObjC class for ourselves here
var DelegateClass;

function fetch(urlString, options) {
  if (
    typeof urlString === "object" &&
    (!urlString.isKindOfClass || !urlString.isKindOfClass(NSString))
  ) {
    options = urlString;
    urlString = options.url;
  }
  options = options || {};
  if (!urlString) {
    return Promise.reject("Missing URL");
  }
  var fiber;
  try {
    fiber = coscript.createFiber();
  } catch (err) {
    coscript.shouldKeepAround = true;
  }
  return new Promise(function(resolve, reject) {
    var url = NSURL.alloc().initWithString(urlString);
    var request = NSMutableURLRequest.requestWithURL(url);
    request.setHTTPMethod(options.method || "GET");

    Object.keys(options.headers || {}).forEach(function(i) {
      request.setValue_forHTTPHeaderField(options.headers[i], i);
    });

    if (options.body) {
      var data;
      if (typeof options.body === "string") {
        var str = NSString.alloc().initWithString(options.body);
        data = str.dataUsingEncoding(NSUTF8StringEncoding);
      } else if (Buffer && Buffer.isBuffer(options.body)) {
        data = options.body.toNSData();
      } else if (
        options.body.isKindOfClass &&
        options.body.isKindOfClass(NSData) == 1
      ) {
        data = options.body;
      } else if (options.body._isFormData) {
        var boundary = options.body._boundary;
        data = options.body._data;
        data.appendData(
          NSString.alloc()
            .initWithString("--" + boundary + "--\r\n")
            .dataUsingEncoding(NSUTF8StringEncoding)
        );
        request.setValue_forHTTPHeaderField(
          "multipart/form-data; boundary=" + boundary,
          "Content-Type"
        );
      } else {
        var error;
        data = NSJSONSerialization.dataWithJSONObject_options_error(
          options.body,
          NSJSONWritingPrettyPrinted,
          error
        );
        if (error != null) {
          return reject(error);
        }
        request.setValue_forHTTPHeaderField(
          "" + data.length(),
          "Content-Length"
        );
      }
      request.setHTTPBody(data);
    }

    if (options.cache) {
      switch (options.cache) {
        case "reload":
        case "no-cache":
        case "no-store": {
          request.setCachePolicy(1); // NSURLRequestReloadIgnoringLocalCacheData
        }
        case "force-cache": {
          request.setCachePolicy(2); // NSURLRequestReturnCacheDataElseLoad
        }
        case "only-if-cached": {
          request.setCachePolicy(3); // NSURLRequestReturnCacheDataElseLoad
        }
      }
    }

    if (!options.credentials) {
      request.setHTTPShouldHandleCookies(false);
    }

    var finished = false;

    var connection = NSURLSession.sharedSession().dataTaskWithRequest_completionHandler(
      request,
      __mocha__.createBlock_function(
        'v32@?0@"NSData"8@"NSURLResponse"16@"NSError"24',
        function(data, res, error) {
          if (fiber) {
            fiber.cleanup();
          } else {
            coscript.shouldKeepAround = false;
          }
          if (error) {
            finished = true;
            return reject(error);
          }
          return resolve(response(res, data));
        }
      )
    );

    connection.resume();

    if (fiber) {
      fiber.onCleanup(function() {
        if (!finished) {
          connection.cancel();
        }
      });
    }
  });
}

module.exports = fetch;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/promise-polyfill/lib/index.js */ "./node_modules/promise-polyfill/lib/index.js")))

/***/ }),

/***/ "./src/globalConfig.js":
/*!*****************************!*\
  !*** ./src/globalConfig.js ***!
  \*****************************/
/*! exports provided: timeStamp, enableAdaptive, enableWebInspector, gc_sidebar_base_url, gc_sidebar_domain, gc_uxfm_domain, gc_uxfm_ip, gc_sidebar_server_ip, gc_sidebar_path_name, gc_adaptive_base_host, gc_adaptive_domain */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeStamp", function() { return timeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableAdaptive", function() { return enableAdaptive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableWebInspector", function() { return enableWebInspector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_base_url", function() { return gc_sidebar_base_url; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_domain", function() { return gc_sidebar_domain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_uxfm_domain", function() { return gc_uxfm_domain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_uxfm_ip", function() { return gc_uxfm_ip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_server_ip", function() { return gc_sidebar_server_ip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_path_name", function() { return gc_sidebar_path_name; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_adaptive_base_host", function() { return gc_adaptive_base_host; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_adaptive_domain", function() { return gc_adaptive_domain; });
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/*
 * 所有的url连接配置都在这里, 连本地和特定电脑的自己看下本地部署情况,去函数里面调整, 生产环境暂时没有配置, 后续补充
 */
 // import logUtil from './ux/src/utils/logUtil';

var timeStamp = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('timeStamp'); // 环境标签

var ENV_LOCAL = 'local'; // 本地环境

var ENV_SOMEONE = 'someone'; // 某台机器环境

var ENV_DEV = 'dev'; // 开发环境

var ENV_DEV_NO_PORTAL = 'dev_no_portal'; // 开发环境, 无代理

var ENV_BETA = 'beta'; // 测试环境

var ENV_PROD = 'prod'; // 正式环境
//= ================这里面不是url,配置OC打开的webview能否开启"检查元素"的功能=========================

var enableWebInspector = true; // 默认在测试环境和正式环境下关闭, 其他情况打开

switch ("beta") {
  case ENV_BETA:
  case ENV_PROD:
    enableWebInspector = false;
    break;

  default:
    enableWebInspector = true;
    break;
} //= ================正式环境屏蔽响应式功能=========================


var enableAdaptive = true;

if ("beta" == ENV_PROD) {
  enableAdaptive = true;
} //= ===================================下面的是url===============================================
// 开发环境


var DOMAIN_DEV = 'http://dev.huawei.com:8086'; // 需要配置host
// const DOMAIN_DEV = 'http://uxs-beta.rnd.huawei.com:8086';   //需要配置host

var IP_DEV = 'http://10.244.193.53:8086'; // 开发环境, 无代理的路径

var DOMAIN_DEV_NO_PORTAL = 'http://dev.huawei.com:8086'; // 需要配置host

var IP_DEV_NO_PORTAL = 'http://10.244.193.53:8086'; // beta(测试)环境
// const DOMAIN_BETA = 'http://uxc-beta.rnd.huawei.com';
// const IP_BETA = 'http://10.178.231.200';
// const DOMAIN_BETA = 'http://hongtool.harmonyos.com:8086';

var DOMAIN_BETA = 'http://hongtool.huawei.com:8086';
var IP_BETA = 'http://10.33.151.182:8086'; // 生产环境, 待定

var DOMAIN_PROD = 'http://designtool.rnd.huawei.com';
var IP_PROD = 'http://100.101.149.247'; // 本地环境

var DOMAIN_LOCAL = 'http://local.huawei.com'; // 需要本地配置host

var IP_LOCAL = 'http://127.0.0.1'; //= =====================下面是siderbar里面相关的配置=========================
// sidebar上面前端页面的url前缀
// let gc_sidebar_base_url = `${DOMAIN_DEV}/sketchcloud/`; //默认开发环境sketchcloud_test

var gc_sidebar_base_url = "".concat(DOMAIN_DEV, "/"); // 默认开发环境sketchcloud_test
// sidebar上的后台服务url前缀
// let gc_sidebar_domain = `${DOMAIN_DEV}/sketchcloud`;

var gc_sidebar_domain = "".concat(DOMAIN_DEV); // sidebar上的后台服务url前缀(ip方式, 注意不要代理服务器的ip)

var gc_sidebar_server_ip = "".concat(IP_DEV); // sidebar上的后台服务url里面在中间拼接的路径串

var gc_sidebar_path_name = 'sketchcloud'; // url里拼接的字符串内容

var to_sidebar_name = '/sketchcloud'; /// /////dev
// let to_sidebar_name = '';////////beta
// uxfm 的后台服务地址

var gc_uxfm_domain = "".concat(DOMAIN_DEV); // uxfm 的后台服务ip地址

var gc_uxfm_ip = "".concat(IP_DEV); //= ====================下面是adaptive相关的配置==============================
// 自适应的url前缀

var gc_adaptive_base_host = "".concat(DOMAIN_DEV, "/sketchcloud/uxSketch"); // 自适应的url前缀(ip方式, 注意不要代理服务器的ip)

var gc_adaptive_domain = "".concat(IP_DEV).concat(to_sidebar_name, "/uxSketch"); //= ===================================下面的是url处理逻辑===========================================

switch ("beta") {
  case ENV_LOCAL:
    // 本地环境
    localEnv();
    break;

  case ENV_SOMEONE:
    // 其他某个人的环境, 需要连接的自己在这边调
    someoneEnv();
    break;

  case ENV_DEV:
    // 开发环境
    devEnv();
    break;

  case ENV_BETA:
    // beta(测试)环境
    betaEnv();
    break;

  case ENV_PROD:
    // 正式(生产)环境
    prodEnv();
    break;

  default:
    // 默认在开发环境
    break;
} // 这里使用时候需要视部署情况手动调整


function localEnv() {
  var serviceEnv = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ENV_DEV_NO_PORTAL;
  to_sidebar_name = '/sketchcloud'; // sidebar上面前端页面的url前缀, 视本地情况自己改

  gc_sidebar_base_url = "http://junjie.huawei.com:4300".concat(to_sidebar_name, "/"); // 自适应的url前缀, 视本地情况自己改

  gc_adaptive_base_host = "http://junjie.huawei.com:4301/sketchcloud/uxSketch"; // 自适应的url前缀(ip方式, 注意不要代理服务器的ip), 视本地情况自己改

  gc_adaptive_domain = "".concat(IP_LOCAL).concat(to_sidebar_name, "/uxSketch"); // sidebar的后台服务, 默认连开发环境, 可以自己调整(ENV_DEV_NO_PORTAL, ENV_DEV等, 去82行左右调整函数传参)

  initSidebarServiceEnv(serviceEnv);
} // 这里使用时候需要视部署情况手动调整


function someoneEnv() {
  var serviceEnv = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ENV_DEV_NO_PORTAL;
  to_sidebar_name = '/sketchcloud';
  var JUNJIE_DOMAIN_DEV = 'http://junjie.huawei.com'; // sidebar上面前端页面的url前缀, 视情况自己改

  gc_sidebar_base_url = "".concat(JUNJIE_DOMAIN_DEV, ":4300").concat(to_sidebar_name, "/"); // 自适应的url前缀, 视情况自己改

  gc_adaptive_base_host = "".concat(JUNJIE_DOMAIN_DEV, ":4301/sketchcloud/uxSketch"); // 自适应的url前缀(ip方式, 注意不要代理服务器的ip), 视情况自己改

  gc_adaptive_domain = "".concat(IP_DEV).concat(to_sidebar_name, "/uxSketch"); // sidebar的后台服务, 默认连开发环境, 可以自己调整(ENV_DEV_NO_PORTAL, ENV_DEV等, 去87行左右调整函数传参)

  initSidebarServiceEnv(serviceEnv);
}

function devEnv() {
  to_sidebar_name = '/sketchcloud';
  gc_sidebar_base_url = "".concat(DOMAIN_DEV, "/sketchcloud/");
  gc_adaptive_base_host = "".concat(DOMAIN_DEV, "/sketchcloud/uxSketch");
  gc_adaptive_domain = "".concat(IP_DEV, "/sketchcloud/uxSketch");
  initSidebarServiceEnv(ENV_DEV);
}

function betaEnv() {
  to_sidebar_name = ''; // gc_sidebar_base_url = `${DOMAIN_BETA}/sketchcloud/`;
  // gc_adaptive_base_host = `${DOMAIN_BETA}/sketchcloud/uxSketch`;
  // gc_adaptive_domain = `${IP_BETA}/sketchcloud/uxSketch`;

  gc_sidebar_base_url = "".concat(DOMAIN_BETA, "/"); // gc_adaptive_base_host = `${DOMAIN_BETA}/uxSketch`;

  gc_adaptive_base_host = "".concat(DOMAIN_BETA, "/uxSketch");
  gc_adaptive_domain = "".concat(IP_BETA, "/uxSketch");
  initSidebarServiceEnv(ENV_BETA);
}

function prodEnv() {
  to_sidebar_name = '';
  gc_sidebar_base_url = "".concat(DOMAIN_PROD, "/sketchcloud/");
  gc_adaptive_base_host = "".concat(DOMAIN_PROD, "/sketchcloud/uxSketch");
  gc_adaptive_domain = "".concat(IP_PROD, "/sketchcloud/uxSketch");
  initSidebarServiceEnv(ENV_PROD);
}

function initSidebarServiceEnv(envTag) {
  switch (envTag) {
    case ENV_LOCAL:
      localSidebarServiceEnv();
      break;

    case ENV_DEV:
      gc_sidebar_domain = "".concat(DOMAIN_DEV).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_DEV);
      gc_uxfm_ip = "".concat(IP_DEV);
      gc_sidebar_server_ip = "".concat(IP_DEV);
      gc_sidebar_path_name = "sketchcloud";
      break;

    case ENV_DEV_NO_PORTAL:
      // 这里多了一个无代理的开发环境
      gc_sidebar_domain = "".concat(DOMAIN_DEV_NO_PORTAL).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_DEV_NO_PORTAL);
      gc_uxfm_ip = "".concat(IP_DEV_NO_PORTAL);
      gc_sidebar_server_ip = "".concat(IP_DEV_NO_PORTAL);
      gc_sidebar_path_name = "sketchcloud";
      break;

    case ENV_BETA:
      // gc_sidebar_domain = `${DOMAIN_BETA}/sketchcloud`;
      gc_sidebar_domain = "".concat(DOMAIN_BETA).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_BETA);
      gc_uxfm_ip = "".concat(IP_BETA);
      gc_sidebar_server_ip = "".concat(IP_BETA);
      gc_sidebar_path_name = '';
      break;

    case ENV_PROD:
      gc_sidebar_domain = "".concat(DOMAIN_PROD).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_PROD);
      gc_uxfm_ip = "".concat(IP_PROD);
      gc_sidebar_server_ip = "".concat(IP_PROD);
      gc_sidebar_path_name = "sketchcloud";
      break;

    default:
      break;
  }
} // 本地sidebar后台接口服务的环境配置, 一般只有后台开发要用这里, 注意结合前面的配置设置


function localSidebarServiceEnv() {
  gc_sidebar_domain = "".concat(DOMAIN_LOCAL).concat(to_sidebar_name);
  gc_uxfm_domain = "".concat(DOMAIN_LOCAL).concat(to_sidebar_name);
  gc_sidebar_server_ip = "".concat(IP_LOCAL);
  gc_sidebar_path_name = "sketchcloud";
} // let info = {
//   'enableWebInspector': enableWebInspector,
//   'gc_sidebar_base_url': gc_sidebar_base_url,
//   'gc_sidebar_domain': gc_sidebar_domain,
//   'gc_uxfm_domain': gc_uxfm_domain,
//   'gc_uxfm_ip': gc_uxfm_ip,
//   'gc_sidebar_server_ip': gc_sidebar_server_ip,
//   'gc_sidebar_path_name': gc_sidebar_path_name,
//   'gc_adaptive_base_host': gc_adaptive_base_host,
//   'gc_adaptive_domain': gc_adaptive_domain
// };
// logUtil.log({sketch_env_info: info});




/***/ }),

/***/ "./src/sourceManage/sourceManage.js":
/*!******************************************!*\
  !*** ./src/sourceManage/sourceManage.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_lang_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lang.js */ "./src/util/lang.js");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sketch/dom */ "sketch/dom");
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(sketch_dom__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var sketch_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! sketch/ui */ "sketch/ui");
/* harmony import */ var sketch_ui__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(sketch_ui__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var sketch_polyfill_fetch__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! sketch-polyfill-fetch */ "./node_modules/sketch-polyfill-fetch/lib/index.js");
/* harmony import */ var sketch_polyfill_fetch__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(sketch_polyfill_fetch__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var sketch_polyfill_fetch_lib_form_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! sketch-polyfill-fetch/lib/form-data */ "./node_modules/sketch-polyfill-fetch/lib/form-data.js");
/* harmony import */ var sketch_polyfill_fetch_lib_form_data__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(sketch_polyfill_fetch_lib_form_data__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _util_config_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/config.js */ "./src/util/config.js");
/* harmony import */ var _util_baseUrl__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/baseUrl */ "./src/util/baseUrl.js");
/* harmony import */ var _skpm_fs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @skpm/fs */ "./node_modules/@skpm/fs/index.js");
/* harmony import */ var _skpm_fs__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_skpm_fs__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _util_util_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/util.js */ "./src/util/util.js");
/* harmony import */ var _util_token__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/token */ "./src/util/token.js");
/* harmony import */ var _globalConfig_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../globalConfig.js */ "./src/globalConfig.js");
/* harmony import */ var _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../ux/src/customWebView/smWebview */ "./src/ux/src/customWebView/smWebview.js");
/* harmony import */ var _ux_src_customWebView_positionAndSize__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../ux/src/customWebView/positionAndSize */ "./src/ux/src/customWebView/positionAndSize.js");















var Document = __webpack_require__(/*! sketch/dom */ "sketch/dom").Document;

var Artboard = __webpack_require__(/*! sketch/dom */ "sketch/dom").Artboard;

var Group = __webpack_require__(/*! sketch/dom */ "sketch/dom").Group;

var ShapePath = __webpack_require__(/*! sketch/dom */ "sketch/dom").ShapePath;

var Style = __webpack_require__(/*! sketch/dom */ "sketch/dom").Style;

var SharedStyle = __webpack_require__(/*! sketch/dom */ "sketch/dom").SharedStyle;

var Text = __webpack_require__(/*! sketch/dom */ "sketch/dom").Text;

var BROWSER_ID = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["loadUrlForUrlManager"])('id').sourceManage;

function _onRun(context) {
  var flagShow = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["canShow"])();

  if (!flagShow) {
    return;
  }

  var srccmd = context.uxssrccmd || 'sourceManage';
  srccmd = srccmd + '';
  var jmpFlag = srccmd != 'sourceManage'; //= ==================================================================================================

  var document = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getSelectedDocument();
  var width = 530;
  var height = 556;
  var index = 1;
  var identifier = BROWSER_ID;
  var newFileName = '';
  var newPath = '';
  var newName = '';
  var groupIdName = '';
  console.log('---newName', newName);
  console.log('---groupIdName', groupIdName);
  var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["hostForUrlManager"])();
  var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["loadUrlForUrlManager"])(host);
  var urlPath = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["loadUrlForUrlManager"])('url');
  var hostUrl = first.gc_sidebar_base_url;
  var url1 = urlPath.sourceManage; // let url = baseUrl + 'sketchcloudweb/sourceManage.html';

  var url = hostUrl + url1; // 这里是关于定位broswer window的代码!

  var position = _ux_src_customWebView_positionAndSize__WEBPACK_IMPORTED_MODULE_13__["default"].getPosition(index, width, height);
  var title = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('设计系统');
  var options = {
    url: url,
    width: width,
    height: height,
    identifier: identifier,
    alwaysOnTop: true,
    x: position.x,
    y: position.y,
    title: title,
    frame: true
  };
  var libraries = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getLibraries().filter(function (l) {
    return l.valid && (l.libraryType == 'Remote' || l.libraryType == 'RemoteThirdParty' || l.libraryType == 4) && l.name.indexOf('res') >= 0;
  });
  var libraryName = '';
  libraries.forEach(function (lib) {
    libraryName += lib.name + '/';
  });
  libraryName = libraryName ? libraryName.slice(0, libraryName.length - 1) : libraryName;

  options.readyToShow = function () {
    var code = NSLocale.currentLocale().languageCode();
    var langCmd = 'setLang("' + code + '")';
    _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, langCmd);
    var skTheme = sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.getTheme();
    var themeCmd = 'getSketchTheme("' + skTheme + '");';
    _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, themeCmd);
    readToShowData();
    _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'sendLibraries(' + JSON.stringify(libraryName) + ')');

    if (jmpFlag) {
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setShowLibraryFlagSketch()');
    }

    var allLibrariesString = getLibraries();
    var returnInfo = {
      data: JSON.parse(allLibrariesString)
    };
    _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
  };

  options.callBackList = {
    'loginOut': function loginOut(data) {
      var tempSize = _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].getSize(BROWSER_ID);

      if (parseInt(tempSize[0]) !== 320 || parseInt(tempSize[1]) !== 454) {
        _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].setSize(BROWSER_ID, 320, 454, true);
      }
    },
    'closed': function closed() {
      Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["sendToSidebar"])(context, 'sourceManage', false);
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].close(BROWSER_ID);
    },
    'updateSelect': function updateSelect(data) {
      // const dpiArr = ['radius', 'fontSize'];
      // if (dpiArr.indexOf(data.attr) >= 0) {
      //   let settings = Settings.settingForKey('setting');
      //   let magnification = parseInt(settings.DPI) || 4;
      // }
      _updateSelect(data);
    },
    'setSourceManageTitle': function setSourceManageTitle(title) {
      if (title === 'NaN资源面板') {
        title = '设计系统';
      }

      title = '设计系统';
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].setTitle(BROWSER_ID, title);
    },
    'saveToken2Sketch': function saveToken2Sketch(data) {
      _util_token__WEBPACK_IMPORTED_MODULE_10__["default"].setToken(data.token);
      _util_token__WEBPACK_IMPORTED_MODULE_10__["default"].updateOcInfo();
    },
    'setSketchWebviewSize': function setSketchWebviewSize(data) {
      var tempSize = _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].getSize(BROWSER_ID);

      if (parseInt(tempSize[0]) !== data.width || parseInt(tempSize[1]) !== data.height) {
        _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].setSize(BROWSER_ID, data.width, data.height);
      }
    },
    'updateDeviceInfo': function updateDeviceInfo(data) {
      console.log('data =====deviceInfo', data);
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].setSize(BROWSER_ID, 530, 556);
    },
    'openOutsideDown': function openOutsideDown(data) {
      var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
      var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId;
      var themeInfo = loginInfo && loginInfo.themeInfo;
      var deviceId = themeInfo && themeInfo.deviceInfo && themeInfo.deviceInfo.id;
      var libraryId = themeInfo && themeInfo.libraryInfo && themeInfo.libraryInfo.id;
      var brandId = themeInfo && themeInfo.brandInfo && themeInfo.brandInfo.id;
      var themeId = themeInfo && themeInfo.themeInfo && themeInfo.themeInfo.id;
      var path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_7__["baseUrl"] + 'assets/html/login.html?t=' + new Date().getTime() + "&platformId=".concat(platformId, "&deviceId=").concat(deviceId, "&libraryId=").concat(libraryId, "&brandId=").concat(brandId, "&themeId=").concat(themeId);
      NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(path));
    },
    'exportTheme': function exportTheme(params) {
      var doc = docFromParams(params.data);
      var info = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('extThemeInfo');
      var prefix = info.themePrefix;
      var suffix = info.themeSuffix;
      var name = prefix + '_' + 'VisualRes' + '_' + suffix + '.sketch';
      var path = NSHomeDirectory() + '/Documents/' + name;
      doc.save(path, {
        saveMode: Document.SaveMode.SaveAs
      });
    },
    'reload': function reload() {
      onRun(context);
    },
    'getLang': function getLang() {
      var code = NSLocale.currentLocale().languageCode();
      var langCmd = 'setLang("' + code + '")';
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, langCmd);
    },
    'setLibraryName': function setLibraryName(s) {
      var document = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getSelectedDocument();
      var libraryName = s.libraryName;
      var library = libraries.find(function (l) {
        return l.valid && l.name === libraryName;
      });

      if (!library) {
        return;
      }

      var themeId = s.themeId;
      var deviceId = s.deviceId;
      var styles = [];
      var layerStyles = library && library.getImportableLayerStyleReferencesForDocument(document);
      var textStyles = library && library.getImportableTextStyleReferencesForDocument(document);
      layerStyles.forEach(function (layerStyle) {
        var importStyle = layerStyle.import();
        var groupName = importStyle.name.split('/')[0] || 'other';
        var styleObj = {};
        styleObj.name = importStyle.name;
        styleObj.fill = importStyle.style.fills[0] && importStyle.style.fills[0].color;
        styleObj.groupName = groupName;
        styleObj.libraryName = libraryName;
        styleObj.themeId = themeId;
        styleObj.deviceId = deviceId;
        styleObj.type = 'layerStyle';
        styles.push(styleObj);
      });
      textStyles.forEach(function (textStyle) {
        var importStyle = textStyle.import();
        var groupName = importStyle.name.split('/')[1] || 'other';
        var styleObj = {};
        styleObj.name = importStyle.name;
        styleObj.fill = importStyle.style.textColor;
        styleObj.fontWeight = 'regular';
        styleObj.fontSize = importStyle.style.fontSize;
        styleObj.lineHeight = importStyle.style.lineHeight === null ? 'automatic' : (importStyle.style.lineHeight / importStyle.style.fontSize).toFixed(1) + 'x';
        styleObj.groupName = groupName;
        styleObj.libraryName = libraryName;
        styleObj.themeId = themeId;
        styleObj.deviceId = deviceId;
        styleObj.type = 'textStyle';
        var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
        var userInfo = loginInfo && loginInfo.userInfo;
        var platformId = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;

        if (platformId === 1) {
          if (importStyle.style.fontWeight === 4) {
            styleObj.fontWeight = 'regular';
          } else if (importStyle.style.fontWeight === 7) {
            styleObj.fontWeight = 'medium';
          }
        } else if (platformId === 2) {
          if (importStyle.style.fontFamily === 'PingFang SC') {
            if (importStyle.style.fontWeight === 5) {
              styleObj.fontWeight = 'Regular';
            } else if (importStyle.style.fontWeight === 6) {
              styleObj.fontWeight = 'Medium';
            } else if (importStyle.style.fontWeight === 8) {
              styleObj.fontWeight = 'Semibold';
            } else if (importStyle.style.fontWeight === 6) {
              styleObj.fontWeight = 'Bold Condensed';
            }
          } else if (importStyle.style.fontFamily === 'Roboto') {
            if (importStyle.style.fontWeight === 5) {
              styleObj.fontWeight = 'Regular';
            } else if (importStyle.style.fontWeight === 6) {
              styleObj.fontWeight = 'Medium';
            } else if (importStyle.style.fontWeight === 6) {
              styleObj.fontWeight = 'Semibold';
            } else if (importStyle.style.fontWeight === 9) {
              styleObj.fontWeight = 'Bold Condensed';
            }
          } else if (importStyle.style.fontFamily === 'Huawei Sans') {
            if (importStyle.style.fontWeight === 5) {
              styleObj.fontWeight = 'Regular';
            } else if (importStyle.style.fontWeight === 9) {
              styleObj.fontWeight = 'Bold Condensed';
            }
          } else if (importStyle.style.fontFamily === 'Huawei Sans Medium') {
            styleObj.fontWeight = 'Medium';
          }
        }

        styles.push(styleObj);
      });
      var styleString = JSON.stringify(styles);
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'sendStyle(' + styleString + ')');
    },
    'getUploadSketch': function getUploadSketch() {
      var panel = NSOpenPanel.openPanel();
      panel.setAllowsMultipleSelection(0);
      panel.setCanChooseDirectories(0);
      panel.setCanChooseFiles(1);
      panel.setFloatingPanel(1);
      var result = panel.runModalForDirectory_file_types(nil, nil, ['sketch']); // let result = panel.runModal();

      if (result !== NSOKButton) {
        return 0;
      }

      if (panel.URLs().count() < 1) {
        return 0;
      } // let formData = new FormData({});


      var path = panel.URLs().objectAtIndex(0).path();
      newPath = path;
      var pathArr = path.split('/');
      var fileName = pathArr[pathArr.length - 1];
      newFileName = fileName;
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setUploadSketch(' + JSON.stringify(fileName) + ')');
    },
    'uploadSketch': function uploadSketch(s) {
      var groupId = s.groupId;
      var sketchDesc = s.sketchDesc;
      var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
      var userInfo = loginInfo && loginInfo.userInfo;
      var formData = new sketch_polyfill_fetch_lib_form_data__WEBPACK_IMPORTED_MODULE_5___default.a({});
      var path = newPath;
      var platformId = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;
      formData.append('file', {
        data: NSData.alloc().initWithContentsOfFile(path),
        fileName: newFileName,
        mimeType: 'application/json'
      });
      formData.append('platformId', '' + platformId);
      formData.append('groupId', '' + groupId);
      formData.append('description', '' + sketchDesc);
      var url = _util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].serverIP() + '/' + _util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].pathName() + '/sketchcloud/sketch/uploadSketch';
      sketch_polyfill_fetch__WEBPACK_IMPORTED_MODULE_4___default()(url, {
        method: 'POST',
        headers: {
          Authorization: 'Bearer ' + userInfo.access_token,
          'Content-Type': 'multipart/form-data',
          Access: 'Client'
        },
        body: formData
      }).then(function (response) {
        return response.json();
      }).then(function (text) {
        var sketchInfo = text && text.content;

        if (text && text.code === '200') {
          _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setSketchInfo(' + JSON.stringify(sketchInfo) + ')');
        } else if (text && text.code === '401') {
          var errorInfo = {
            success: false,
            message: '暂无权限'
          };
          _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setSketchInfo(' + JSON.stringify(errorInfo) + ')');
        } else {
          sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.message('请求超时,请关闭该页面！');
        }
      }).catch(function (e) {
        sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.message('请求超时，请关闭！');
      });
    },
    'downloadSketch': function downloadSketch(s) {
      // let loginInfo = Settings.settingForKey('loginInfo');
      // let userInfo = loginInfo && loginInfo.userInfo;
      // let platformId = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;
      var sketchId = s.id + '';
      var name = s.name; // let groupId = s.groupId;
      // let path = encodeURI(config.serverIP() + '/sketchcloud/view/sketch/' + platformId + '/' + groupId + '/' + name);

      var panel = NSOpenPanel.openPanel();
      var device = s.platformVersionName;
      panel.setAllowsMultipleSelection(0);
      panel.setCanChooseDirectories(1);
      panel.setCanChooseFiles(0);
      panel.setFloatingPanel(1);
      var formData = new sketch_polyfill_fetch_lib_form_data__WEBPACK_IMPORTED_MODULE_5___default.a({});
      formData.append('sketchId', sketchId);

      if (panel.runModal() !== NSOKButton) {
        return 0;
      } else {
        var finalUrl = '';

        if (_util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].pathName() == '') {
          finalUrl = s.nspPath;
        } else {
          // finalUrl = config.serverIP() + '/' + config.pathName() + '/sketchcloud/sketch/downloadSketchClient';
          finalUrl = first.gc_sidebar_server_ip + '/' + _util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].pathName() + '/sketchcloud/sketch/downloadSketchClient';
        } // let url = config.serverIP() + '/' + config.pathName() + '/sketchcloud/sketch/downloadSketchClient';
        // let nspPath = s.nspPath;


        var message = '';
        sketch_polyfill_fetch__WEBPACK_IMPORTED_MODULE_4___default()(finalUrl).then(function (response) {
          return response.blob();
        }).then(function (text) {
          var templateUrl = panel.URLs().objectAtIndex(0).path().replace('file://', '') + '/' + name;

          if (text) {
            _skpm_fs__WEBPACK_IMPORTED_MODULE_8___default.a.writeFileSync(templateUrl, text, 'NSData');
            message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('下载成功');
            var downloadInfo = {
              success: true,
              message: message
            };
            Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["postToStatistics"])('101', device);
            _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setdownLoadInfo(' + JSON.stringify(downloadInfo) + ')');
          } else {
            message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('下载错误');
            var _downloadInfo = {
              success: false,
              message: message
            };
            _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setdownLoadInfo(' + JSON.stringify(_downloadInfo) + ')');
          }
        }).catch(function (e) {
          message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('下载超时');
          var downloadInfo = {
            success: false,
            message: message
          };
          _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'setdownLoadInfo(' + JSON.stringify(downloadInfo) + ')'); // NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(path));
        });
      }
    },
    'syncSketch': function syncSketch(s) {
      // let loginInfo = Settings.settingForKey('loginInfo');
      // let userInfo = loginInfo && loginInfo.userInfo;
      var returnInfo = {
        syncSketchFlag: s.syncSketchFlag
      };
      var device = s.platformVersionName; // let platformId = (parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1) + '';

      var platformId = s.platformId + '';
      var groupId = s.groupId + '';
      var name = s.name;
      var nameArray = name && name.split('.sketch');
      var name1 = nameArray && nameArray.length && nameArray[0];
      newName = name1;
      groupIdName = groupId;
      s.newName = name1;
      s.groupIdName = groupId;
      var Library = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.Library;
      var libraries = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getLibraries().filter(function (l) {
        var path = '';

        try {
          path = l.valid && l.getDocument() && l.getDocument().path;
        } catch (err) {
          path = '';
        }

        if (path === '') {
          return false;
        } // http://10.22.125.201:8080/view/sketch/1/2/EMUI%2010.0%20component%20library.xml


        var pathArr = path && path.split('/');
        var libGroupId = pathArr && pathArr.length && pathArr[pathArr.length - 2];
        var libPlatformId = pathArr && pathArr.length && pathArr[pathArr.length - 3]; // let resultA = l.valid && l.name === name1 && l.libraryType === 'Remote' && libGroupId === groupId && libPlatformId === platformId && path && path.indexOf(config.serverIP()) >= 0;

        return l.valid && l.name === name1 && (l.libraryType === 'Remote' || l.libraryType === 'RemoteThirdParty' || l.libraryType === 4) && libGroupId === groupId && libPlatformId === platformId && path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].serverIP()) >= 0; // return l.valid && l.name === name1 && (l.libraryType === 'Remote' || l.libraryType === 'RemoteThirdParty' || l.libraryType === 4)
        //     && path && path.indexOf(config.serverIP()) >= 0;
      });
      var LibrariesString = getLibraries(s);
      console.log(LibrariesString);

      if (libraries && libraries.length) {
        libraries[0].remove();
        var allLibrariesString = getLibraries(s);
        var flage = false;
        differenceLibraryType(s, flage);
        returnInfo.data = JSON.parse(allLibrariesString);
        _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
      } else {
        // platformId和groupId如果不匹配就会报  err错误
        // let urlPre = config.serverIP();
        var urlPre = first.gc_sidebar_server_ip;

        if (_globalConfig_js__WEBPACK_IMPORTED_MODULE_11__["gc_sidebar_path_name"] !== '') {
          urlPre += '/' + _globalConfig_js__WEBPACK_IMPORTED_MODULE_11__["gc_sidebar_path_name"];
        }

        var testURI = encodeURI(urlPre + '/view/sketch/' + platformId + '/' + groupId + '/' + name1 + '.xml');
        Library.getRemoteLibraryWithRSS(testURI, function (err, library) {
          // let url = config.serverIP();
          var message = '';

          if (err) {
            console.log('Library.getRemoteLibraryWithRSS', err.message);
            returnInfo.success = false;
            message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('添加失败，未知原因');
            returnInfo.message = message;

            if (err.message && err.message.indexOf('请求超时') >= 0) {
              message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('请求超时，请稍后再试');
              returnInfo.message = message;
            } else if (err.message && err.message.indexOf('Could not load document') >= 0) {
              message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('网络请求异常，导致无法加载,请稍后再试');
              returnInfo.message = message; // let library = sketch.getLibraries().filter(l => l.name === name1 && l.libraryType === 'Remote');
              // if (library && library.length && !library[0].valid) {
              //   library[0].remove();
              // }
            }

            var _allLibrariesString = getLibraries();

            returnInfo.data = JSON.parse(_allLibrariesString);
            _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
          } else if (library) {
            if (library.valid) {
              var _allLibrariesString2 = getLibraries();

              var _flage = true;
              returnInfo.data = JSON.parse(_allLibrariesString2);
              Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["postToStatistics"])('101', device);
              differenceLibraryType(s, _flage);
              _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
            } else if (!library.enabled) {
              returnInfo.success = false;
              message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('该库已存在');
              returnInfo.message = message;

              var _allLibrariesString3 = getLibraries();

              var _flage2 = true;
              returnInfo.data = JSON.parse(_allLibrariesString3);
              Object(_util_util_js__WEBPACK_IMPORTED_MODULE_9__["postToStatistics"])('101', device);
              differenceLibraryType(s, _flage2);
              _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
            } else {
              returnInfo.success = false;
              message = _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('Library与当前Sketch版本不兼容，请更新版本再试');
              returnInfo.message = message;

              var _allLibrariesString4 = getLibraries(s);

              returnInfo.data = JSON.parse(_allLibrariesString4);
              _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
            }
          } else {
            console.log(s);
          }
        });
      }
    },
    'deleteSketch': function deleteSketch(s) {
      var nameArray = s && s.name && s.name.split('.sketch');
      var name = nameArray && nameArray.length && nameArray[0];
      var groupId = s.groupId + '';
      var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
      var platformId = (loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId || 1) + '';
      var libraries = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getLibraries().filter(function (l) {
        var path = l.valid && l.getDocument() && l.getDocument().path;
        var pathArr = path && path.split('/');
        var libGroupId = pathArr && pathArr.length && pathArr[pathArr.length - 2];
        var libPlatformId = pathArr && pathArr.length && pathArr[pathArr.length - 3];
        return l.valid && l.name === name && (l.libraryType == 'Remote' || l.libraryType == 'RemoteThirdParty' || l.libraryType == 4) && libGroupId === groupId && libPlatformId === platformId && path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].serverIP()) >= 0;
      });
      libraries && libraries.length && libraries[0].remove();
      var allLibrariesString = getLibraries();
      var returnInfo = {
        data: JSON.parse(allLibrariesString)
      };
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'notifySketchFile(' + JSON.stringify(returnInfo) + ')');
    }
  };
  _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].SMPanel(options);

  function readToShowData() {
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('userInfoName') || {};

    if (!loginInfo) {
      _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].close(BROWSER_ID);
      sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('没有主题信息，请先进行设置'));
    }

    loginInfo.measureInfo = null;
    sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo1', loginInfo);
    var theme = sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.getTheme();
    loginInfo.theme = theme;
    loginInfo.uxsToken = _util_token__WEBPACK_IMPORTED_MODULE_10__["default"].getToken();
    console.log('资源面板 sketch====》webview', loginInfo); // loginInfo = Settings.settingForKey('UserInfo');

    _ux_src_customWebView_smWebview__WEBPACK_IMPORTED_MODULE_12__["default"].executeJavaScript(BROWSER_ID, 'browserWindowNotifyPanelLoginInfo(' + JSON.stringify(loginInfo) + ')');
  }

  function _updateSelect(data) {
    console.log('xxx...liuy==' + JSON.stringify(data));
    document = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getSelectedDocument() || document;
    var selection = document.selectedLayers;
    var layers = selection.layers;
    var selectedCount = selection.length;

    if (selectedCount === 0) {
      sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('请选择至少一个图层'));
    }

    var value = data.value;
    var attr = data.attr;
    var docData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.documentSettingForKey(document, attr) || {};
    docData[data.name] = docData[data.name] || {};
    docData[data.name].value = value;
    docData[data.name].objectID = docData[data.name].objectID || [];
    var docArr = docData[data.name].objectID;

    for (var i = 0; i < layers.length; i++) {
      var success = false;

      if (attr === 'color') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setColor(layers[i], value);
      } else if (attr === 'border') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setBorder(layers[i], value);
      } else if (attr === 'shadow') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setShadow(layers[i], value);
      } else if (attr === 'fontSize') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setFontSize(layers[i], value);
      } else if (attr === 'fontLineSpacing') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setLineHeight(layers[i], value);
      } else if (attr === 'fontFamilies') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setFontWeight(layers[i], value);
      } else if (attr === 'radius') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setRadius(layers[i], value);
      } else if (attr === 'alphas') {
        success = _util_util_js__WEBPACK_IMPORTED_MODULE_9__["setStyle"].setOpacity(layers[i], value);
      }

      if (success) {
        if (attr === 'color' || attr === 'border' || attr === 'shadow' || attr === 'alphas') {
          var name = layers[i].name;

          if (name && name.indexOf('<颜色>') < 0) {
            // name = '<颜色>' + name;
            name = '<' + _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('颜色') + '>' + name;
            layers[i].name = name;
          }
        }

        if (attr === 'fontSize' || attr === 'fontLineSpacing' || attr === 'fontFamilies') {
          var _name = layers[i].name;

          if (_name && _name.indexOf('<字体>') < 0) {
            _name = '<' + _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('字体') + '>' + _name;
            layers[i].name = _name;
          }
        }

        if (attr === 'radius') {
          var _name2 = layers[i].name;

          if (_name2 && _name2.indexOf('<圆角>') < 0) {
            _name2 = '<' + _util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('圆角') + '>' + _name2;
            layers[i].name = _name2;
          }
        }

        document.sketchObject.reloadInspector();
        sketch_ui__WEBPACK_IMPORTED_MODULE_3___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_0__["default"].LSTR('应用样式成功'));
        var itData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layers[i], attr);
        var id = layers[i].id + ''; // 判断是否存在旧的数据，删除

        deleteOldData(id, itData, docData);
        var parent = layers[i].parent;

        if (parent && parent.type === 'Group') {
          var groupData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(parent, attr) || {};

          if (groupData[data.name]) {
            groupData[data.name].value = data.value;
            var objectID = groupData[data.name].objectID;

            if (objectID.indexOf(id) < 0) {
              objectID.push(id);
            }
          } else {
            groupData[data.name] = {
              value: data.value,
              objectID: [id]
            };
          }

          deleteOldData(id, itData, groupData);
          id = parent.id + '_' + id;
          sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setLayerSettingForKey(parent, attr, groupData);
        }

        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setLayerSettingForKey(layers[i], attr, data);

        if (docArr.length && getArrayIndex(id, docArr) >= 0) {
          continue;
        } else {
          if (!docData[data.name]) {
            docData[data.name] = docData[data.name] || {};
            docData[data.name].value = value;
            docData[data.name].objectID = docData[data.name].objectID || [];
            docArr = docData[data.name].objectID;
          }

          docArr.push(id);
          sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setDocumentSettingForKey(document, attr, docData);
        }
      }
    }
  }

  function deleteOldData(id, itData, docData) {
    var selectData = itData && itData.name && docData[itData.name] && docData[itData.name].objectID;

    if (selectData && selectData.length) {
      selectData.splice(getArrayIndex(id, selectData), 1);

      if (selectData.length === 0) {
        delete docData[itData.name];
      }
    }
  }

  function getArrayIndex(data, arr) {
    var val = -1;
    arr.forEach(function (item, index) {
      if (item === data) {
        val = index;
        return false;
      }
    });
    return val;
  }

  function differenceLibraryType(s, flags) {
    var type = s.type;
    var name = s.name;
    var groupId = s.groupId;
    var eachL = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getLibraries();
    var libaryTypeSymbolArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('symbolType');
    var libraryTypeIconsArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('iconsType');
    var libraryTypeStylesArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('sytlesType');

    if (eachL === undefined && eachL.length <= 0) {
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('symbolType', libaryTypeSymbolArray);
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('iconsType', libraryTypeIconsArray);
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('sytlesType', libraryTypeStylesArray);
    }

    if (flags == true) {
      if (type == 'symbols') {
        // 组件库
        var symbosArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('symbolType') || [];
        var libraryObj = {
          name: name,
          groupId: s.groupId,
          platformId: s.platformId,
          sketchId: s.id
        };

        if (symbosArray) {
          for (var i = 0; i < symbosArray.length; i++) {
            // let testGroupid = symbosArray[i].groupId;
            if (name == symbosArray[i].name && groupId == symbosArray[i].groupId) {
              symbosArray.splice(i, 1);
            }
          }
        }

        symbosArray.push(libraryObj);
        libaryTypeSymbolArray = symbosArray;
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('symbolType', symbosArray);
      } else if (type == 'icons') {
        // 图标库
        var iconsArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('iconsType') || [];
        libraryTypeIconsArray = iconsArray;
        var _libraryObj = {
          name: name,
          groupId: s.groupId,
          platformId: s.platformId,
          sketchId: s.id
        };

        if (iconsArray) {
          for (var _i = 0; _i < iconsArray.length; _i++) {
            if (name == iconsArray[_i].name && groupId == iconsArray[_i].groupId) {
              iconsArray.splice(_i, 1);
            }
          }
        }

        iconsArray.push(_libraryObj);
        libraryTypeIconsArray = iconsArray;
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('iconsType', iconsArray);
      } else if (type == 'styles') {
        // 样式库
        var sytlesArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('sytlesType') || [];
        var _libraryObj2 = {
          name: name,
          groupId: s.groupId,
          platformId: s.platformId,
          sketchId: s.id
        };

        if (sytlesArray) {
          for (var _i2 = 0; _i2 < sytlesArray.length; _i2++) {
            if (name == sytlesArray[_i2].name && groupId == sytlesArray[_i2].groupId) {
              sytlesArray.splice(_i2, 1);
            }
          }
        }

        sytlesArray.push(_libraryObj2);
        libraryTypeStylesArray = sytlesArray;
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('sytlesType', sytlesArray);
      }
    } else {
      if (type == 'symbols') {
        libaryTypeSymbolArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('symbolType') || [];

        if (libaryTypeSymbolArray) {
          for (var _i3 = 0; _i3 < libaryTypeSymbolArray.length; _i3++) {
            // let testGroupid = libaryTypeSymbolArray[i].groupId;
            if (name == libaryTypeSymbolArray[_i3].name && groupId == libaryTypeSymbolArray[_i3].groupId) {
              libaryTypeSymbolArray.splice(_i3, 1);
            }
          }
        }

        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('symbolType', libaryTypeSymbolArray);
      } else if (type == 'icons') {
        libraryTypeIconsArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('iconsType') || [];

        if (libraryTypeIconsArray) {
          for (var _i4 = 0; _i4 < libraryTypeIconsArray.length; _i4++) {
            if (name == libraryTypeIconsArray[_i4].name && groupId == libraryTypeIconsArray[_i4].groupId) {
              libraryTypeIconsArray.splice(_i4, 1);
            }
          }
        }

        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('iconsType', libraryTypeIconsArray);
      } else if (type == 'styles') {
        libraryTypeStylesArray = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('sytlesType') || [];

        if (libraryTypeStylesArray) {
          for (var _i5 = 0; _i5 < libraryTypeStylesArray.length; _i5++) {
            if (name == libraryTypeStylesArray[_i5].name && groupId == libaryTypeSymbolArray[_i5].groupId) {
              libraryTypeStylesArray.splice(_i5, 1);
            }
          }
        }

        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('sytlesType', libraryTypeStylesArray);
      }
    }
  }

  function getLibraries(s) {
    // just judge if it is a library, do not need 'l.enabled'
    var allLibraries1 = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.getLibraries().filter(function (l) {
      return l.valid && (l.libraryType === 'Remote' || l.libraryType === 'RemoteThirdParty' || l.libraryType === 4);
    });
    var allLibrariesArray = [];

    if (allLibraries1 && allLibraries1.length) {
      for (var i = 0; i < allLibraries1.length; i++) {
        var path = '';

        try {
          path = allLibraries1[i].getDocument() && allLibraries1[i].getDocument().path;
        } catch (err) {
          path = '';
        } // let path = allLibraries1[i].getDocument() && allLibraries1[i].getDocument().path;


        if (path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_6__["default"].serverIP()) >= 0) {
          var pathArr = path && path.split('/');
          var groupId = pathArr && pathArr.length && pathArr[pathArr.length - 2];
          var platformId = pathArr && pathArr.length && pathArr[pathArr.length - 3];
          var updateTime = allLibraries1[i].lastModifiedAt && new Date(allLibraries1[i].lastModifiedAt).getTime();
          var libraryObj = {
            name: allLibraries1[i].name,
            groupId: groupId,
            platformId: platformId,
            time: updateTime
          };

          if (s && s.newName == libraryObj.name && s.groupIdName == libraryObj.groupId) {
            allLibraries1[i].remove();
            allLibrariesArray.splice(i, 1);
            newName = '';
            groupIdName = '';
          }

          allLibrariesArray.push(libraryObj);
        }
      }
    }

    newName = '';
    groupIdName = '';
    var allLibrariesString = allLibrariesArray && allLibrariesArray.length && JSON.stringify(allLibrariesArray);
    return allLibrariesString;
  }
} // login Info有更新先设置


function onRun(context) {
  _onRun(context);
}

function docFromParams(data) {
  var doc = new Document();
  doColor(data, doc);
  doFont(data, doc);
  return doc;
}

function doColor(data, doc) {
  var colorObj = data.color;
  var page = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.fromNative(doc.sketchObject.currentPage());
  page.name = 'color';
  doColorGroups(colorObj, page, doc); // doAlphas(colorObj, page, doc);
}

function doColorGroups(data, page, doc) {
  var colorGroupsArr = data.colorGroups;

  if (colorGroupsArr) {
    var art = new Artboard();
    art.parent = page;
    art.name = 'colorGroups';

    for (var i = 0; i < colorGroupsArr.length; i++) {
      var grpObj = colorGroupsArr[i];
      var grp = new Group();
      grp.parent = art;
      grp.name = grpObj.name;
      var colorsArr = grpObj.colors;

      for (var _i6 = 0; _i6 < colorsArr.length; _i6++) {
        var colorObj = colorsArr[_i6];
        var shape = new ShapePath({
          name: colorObj.name,
          shapeType: ShapePath.ShapeType.Rectangle
        });
        shape.parent = grp;
        shape.frame.width = 200;
        shape.frame.height = 200;
        var colorVal = colorObj.realValue;

        if (colorVal.length == 9) {
          var a = colorVal.substring(1, 3);
          var rgb = colorVal.substring(3);
          colorVal = '#' + rgb + a;
        }

        shape.style.fills = [{
          color: colorVal,
          fillType: Style.FillType.Color
        }];
        var shStyle = SharedStyle.fromStyle({
          name: colorObj.name,
          style: shape.style,
          document: doc
        });
        shape.sharedStyle = shStyle;
      } // let selGrp = new Group();
      // selGrp.parent = grp;
      // selGrp.name = 'selectors';
      // let selectorsArr = grpObj.selectors;
      // for (let i = 0; i < selectorsArr.length; i++) {
      // }


      adjustColorGroup(grp);
    }

    adjustColorArtboard(art);
    adjustColorPage(page);
  }
}

function doFont(data, doc) {
  var fontObj = data.font;

  if (!fontObj) {
    return;
  }

  var page = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.fromNative(doc.sketchObject.addBlankPage());
  page.name = 'font';
  doFontSize(fontObj, page, doc);
}

function doFontSize(data, page, doc) {
  var szArr = data.fontSize;

  if (!szArr) {
    return;
  }

  var art = new Artboard();
  art.parent = page;
  art.name = 'fontSize';

  for (var i = 0; i < szArr.length; i++) {
    var szObj = szArr[i];
    var elements = szObj.elements;

    if (!elements) {
      continue;
    }

    for (var _i7 = 0; _i7 < elements.length; _i7++) {
      var ftObj = elements[_i7];
      var lTxt = new Text();
      lTxt.parent = art;
      lTxt.name = ftObj.name + '/left';
      lTxt.text = ftObj.name;
      lTxt.style.fontSize = parseInt(ftObj.realValue);
      lTxt.style.alignment = Text.Alignment.left;
      var lShStyle = SharedStyle.fromStyle({
        name: ftObj.name + '/left',
        style: lTxt.style,
        document: doc
      });
      lTxt.sharedStyle = lShStyle;
      var cTxt = new Text();
      cTxt.parent = art;
      cTxt.name = ftObj.name + '/center';
      cTxt.text = ftObj.name;
      cTxt.style.fontSize = parseInt(ftObj.realValue);
      cTxt.style.alignment = Text.Alignment.center;
      var cShStyle = SharedStyle.fromStyle({
        name: ftObj.name + '/center',
        style: cTxt.style,
        document: doc
      });
      cTxt.sharedStyle = cShStyle;
      var rTxt = new Text();
      rTxt.parent = art;
      rTxt.name = ftObj.name + '/right';
      rTxt.text = ftObj.name;
      rTxt.style.fontSize = parseInt(ftObj.realValue);
      rTxt.style.alignment = Text.Alignment.right;
      var rShStyle = SharedStyle.fromStyle({
        name: ftObj.name + '/right',
        style: rTxt.style,
        document: doc
      });
      rTxt.sharedStyle = rShStyle;
    }
  }

  adjustFontArtboard(art);
}

function adjustColorGroup(group) {
  var layers = group.layers;
  var txt = new Text();
  txt.text = group.name;
  txt.style.fontSize = 32;
  txt.parent = group;
  txt.frame.x = 0;
  txt.frame.y = 0;
  var x = 0;
  var y = txt.frame.height + 100;

  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];
    layer.frame.x = x;
    layer.frame.y = y;

    if ((i + 1) % 6) {
      x += layer.frame.width + 100;
    } else {
      x = 0;
      y += layer.frame.height + 100;
    }
  }

  group.adjustToFit();
}

function adjustColorArtboard(art) {
  art.background.enabled = true;
  art.background.color = '#e6e6e6ff';
  var layers = art.layers;
  var y = 0;

  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];
    layer.frame.y = y;
    y += layer.frame.height + 200;
  }

  art.adjustToFit();
  art.frame.width += 256;
  var grp = new Group({
    name: '_/Header and Footer'
  });
  grp.parent = art;
  grp.frame.width = art.frame.width - 256;
  grp.frame.height = 243;
  var txt = new Text();
  txt.text = 'Color style';
  txt.style.fontSize = 120;
  txt.style.fontWeight = 9;
  txt.parent = grp;
  txt.frame.x = 0;
  txt.frame.y = 0;
  var shape = new ShapePath({
    shapeType: ShapePath.ShapeType.Rectangle
  });
  shape.parent = grp;
  shape.style.fills = [{
    color: '#0000001A',
    fillType: Style.FillType.Color
  }];
  shape.frame.x = 0;
  shape.frame.width = grp.frame.width;
  shape.frame.height = 2;
  shape.frame.y = grp.frame.height - 2;
  grp.frame.x = 128;
  grp.frame.y = 128;

  for (var _i8 = 0; _i8 < layers.length; _i8++) {
    var _layer = layers[_i8];
    _layer.frame.x = 128;
    _layer.frame.y += 128 + 243 + 40;
  }

  art.frame.height += 128 + 243 + 200;
}

function adjustColorPage(page) {
  var layers = page.layers;
  var x = 100;

  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];
    layer.frame.x = x;
    layer.frame.y = 200;
    x += layer.frame.width + 200;
  }
}

function adjustFontArtboard(art) {
  art.background.enabled = true;
  art.background.color = '#e6e6e6ff';
  setChildrenFrame(art);
  art.adjustToFit();
  var layers = art.layers;
  art.frame.width += 256;
  var grp = new Group({
    name: '_/Header and Footer'
  });
  grp.parent = art;
  grp.frame.width = art.frame.width - 256;
  grp.frame.height = 243;
  var txt = new Text();
  txt.text = 'Text style';
  txt.style.fontSize = 120;
  txt.style.fontWeight = 9;
  txt.parent = grp;
  txt.frame.x = 0;
  txt.frame.y = 0;
  var shape1 = new ShapePath({
    shapeType: ShapePath.ShapeType.Rectangle
  });
  shape1.parent = grp;
  shape1.style.fills = [{
    color: '#0000001A',
    fillType: Style.FillType.Color
  }];
  shape1.frame.x = 0;
  shape1.frame.width = grp.frame.width;
  shape1.frame.height = 2;
  shape1.frame.y = grp.frame.height - 2;
  grp.frame.x = 128;
  grp.frame.y = 128;

  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];
    layer.frame.x = 128;
    layer.frame.y += 128 + 243 + 40;
  }

  art.frame.height += 128 + 243 + 200;
}

function setChildrenFrame(art) {
  var layers = art.layers;
  var y = 0;
  var i = 0;

  while (i < layers.length) {
    if (i % 3 == 0) {
      var label = new Text();
      label.parent = art;
      label.text = String(layers[i].style.fontSize) + 'px';
      label.style.fontSize = 32;
      label.frame.x = 0;
      label.frame.y = y;
      y += label.frame.height + 40;
    }

    layers[i].frame.x = 0;
    layers[i].frame.y = y;
    layers[i].fixedWidth = true;
    layers[i].frame.width *= 2;
    y += layers[i].frame.height + 40;
    layers[i + 1].frame.x = 0;
    layers[i + 1].frame.y = y;
    layers[i + 1].fixedWidth = true;
    layers[i + 1].frame.width *= 2;
    y += layers[i + 1].frame.height + 40;
    layers[i + 2].frame.x = 0;
    layers[i + 2].frame.y = y;
    layers[i + 2].fixedWidth = true;
    layers[i + 2].frame.width *= 2;
    y += layers[i + 2].frame.height + 128;
    i += 3;
  }

  return layers;
}

/* harmony default export */ __webpack_exports__["default"] = (onRun);

/***/ }),

/***/ "./src/util/baseUrl.js":
/*!*****************************!*\
  !*** ./src/util/baseUrl.js ***!
  \*****************************/
/*! exports provided: baseUrl, baseUrlForMaterial, refreshSearch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "baseUrl", function() { return baseUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "baseUrlForMaterial", function() { return baseUrlForMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refreshSearch", function() { return refreshSearch; });
/* harmony import */ var _globalConfig__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../globalConfig */ "./src/globalConfig.js");

var baseUrl = 'http://sketchcloudtest.rnd.huawei.com/';
var baseUrlForMaterial = '';

if (false) {} else if (false) {} else {
  // 普通的build测试用和dev是一样的 后台地址是测试环境 npm run build
  // production
  // baseUrl = 'http://10.22.125.201:8080/';
  baseUrl = 'http://sketchcloudtest.rnd.huawei.com/';
} // 统一去用打包命令处理


baseUrl = _globalConfig__WEBPACK_IMPORTED_MODULE_0__["gc_sidebar_base_url"];
baseUrlForMaterial = _globalConfig__WEBPACK_IMPORTED_MODULE_0__["gc_adaptive_base_host"];
var refreshSearch = "?t=".concat(_globalConfig__WEBPACK_IMPORTED_MODULE_0__["timeStamp"]); // let refreshSearch = '';



/***/ }),

/***/ "./src/util/config.js":
/*!****************************!*\
  !*** ./src/util/config.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/util.js */ "./src/util/util.js");
// import { gc_sidebar_domain, gc_sidebar_server_ip, gc_sidebar_path_name } from '../globalConfig';

var config = {
  domain: function domain() {
    var path = 'http://designcloud.rnd.huawei.com';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      // path = 'http://10.22.125.201:8080';
      path = 'http://sketchcloudtest.rnd.huawei.com';
    } // 统一去用打包命令处理
    // path = gc_sidebar_domain;


    path = first.gc_sidebar_domain;
    return path;
  },
  serverIP: function serverIP() {
    var ip = 'http://10.64.153.205:80';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      ip = 'http://10.22.125.201:8080';
    } // 统一去用打包命令处理
    // ip = gc_sidebar_server_ip;


    ip = first.gc_sidebar_server_ip;
    return ip;
  },
  pathName: function pathName(flag) {
    var pathName = 'sketchcloud_beta';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      pathName = 'sketchcloud_test';
    }

    if (flag === 'ux') {
      pathName = 'uxarp';
    } // 统一去用打包命令处理
    // pathName = gc_sidebar_path_name;


    pathName = first.gc_sidebar_path_name;
    return pathName;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (config);

/***/ }),

/***/ "./src/util/lang.js":
/*!**************************!*\
  !*** ./src/util/lang.js ***!
  \**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var zhDict = {};
var enDict = {
  '设置': 'Settings',
  '设计系统': 'Design style',
  '资源面板': 'Resource Panel',
  '标注工具栏': 'Annotation toolbar',
  '控件库': 'Symbol library',
  '图标库': 'Icon library',
  '标注间距': 'Annotation spacing',
  '标注尺寸': 'Annotation Size',
  '标注控件': 'Annotation Widgets',
  '标注热区': 'Annotation Hotspot',
  '添加备注': 'Add Comments',
  '标注栅格': 'Annotation Grid',
  '标注原子能力': 'Annotation Adaptive',
  '切片': 'Slice',
  '标注样式': 'Annotation styles',
  '请至少选择一种原子能力': 'Please select at least one kind of adaptive ability',
  '主题切换': 'Switch theme',
  '切换侧边栏': 'Show/Hide sidebar',
  '原子化布局能力开关': 'Atomic layout feature',
  '原子化布局能力已开启': 'Atomic layout feature enabled.',
  '原子化布局能力已关闭': 'Atomic layout feature disabled.',
  '帮助': 'Help',
  '解绑symbol': 'Detach Symbol',
  '注销账号': 'Logout',
  '原子化布局': 'Atomic layout',
  '侧边工具栏': 'Sidebar',
  '请先选中一个Artboard': 'Please select an Artboard',
  '无法关联样式, 请在文件共享中检查样式文件是否已添加': 'Attach to style failed, please check the libraries',
  '圆角过大, 设置失败!': 'Invalid Round Corner: value too big!',
  '注销成功': 'Logout seccuss',
  '请选择一个库': 'Please select a library',
  '请至少选择一种栅格': 'Please select at least one kind of grid',
  '切换主题成功, sketch界面刷新可能会有延迟, 请稍候!': 'Theme changed successfully. There may be a delay for the page to refresh.',
  '请选择至少一个图层': 'Please select one layer at least',
  '请选择一个或两个图层进行间距标注!': 'Please select one or two layers.',
  '请先导入对应的主题库文件': 'Import theme library first',
  '没有平台信息，请先进行设置': 'No platform infomation, please set it in the web page first',
  '无对应的主题库可用': 'No usable style libraries',
  '请选中一个节点': 'Please select a node',
  '固定内部排版成功!': 'Fix inner layout success',
  '清除成功': 'Clean success',
  '恢复默认参数成功': 'Restore default configuration success',
  '已经同步最新的规范栅格': 'Sync with latest grid specification Done',
  '响应式断点设置生效': 'Set adaptive break point success',
  '拷贝响应式变化能力属性成功': 'Copy adaptive properties success',
  '请先拷贝扩展属性': 'Please copy extended properties first',
  '粘贴响应式变化能力属性成功': 'Paste adaptive properties success',
  // '拉伸能力边距异常': 'en_拉伸能力边距异常',
  '请选中且只选中一个图层': 'en_请选中且只选中一个图层',
  '当前选中的元素不是画板内的图层, 无法获取信息': 'en_当前选中的元素不是画板内的图层, 无法获取信息',
  '请选中一个symbol': 'Please select a Symbol',
  '解绑Symbol成功': 'Detach Symbol success',
  '请选择至少一个画板': 'Please select at least one Artboard',
  '恢复默认设置成功': 'Restore default settings success',
  '成功模拟尺寸设置': 'en_成功模拟尺寸设置',
  '图层的扩展属性': 'en_图层的扩展属性',
  '请选择要插入的栅格类型': 'en_请选择要插入的栅格类型',
  '请选择Shape/Text类型进行样式标注': 'Please select the Shape or Text type.',
  // '无法直接标注样式，请尝试选择Style Layer进行标注': 'en_无法直接标注样式，请尝试选择Style Layer进行标注',
  '没有任何属性可以选择': 'en_没有任何属性可以选择',
  '内部shape元素都没有样式': 'en_内部shape元素都没有样式',
  '成功添加响应式布局能力': 'en_成功添加响应式布局能力',
  '请选中一到两个图层': 'en_请选中一到两个图层',
  '所选对象不在Artboard上，无法进行边距标注': 'en_所选对象不在Artboard上，无法进行边距标注',
  '请选择一个或多个对象对应区域标注的栅格容器参数': 'en_请选择一个或多个对象对应区域标注的栅格容器参数',
  '请选择Symbol Instance类型进行控件标注': 'Please select the Symbol Instance type.',
  '拉伸能力边距异常': 'en_拉伸能力边距异常',
  '容差尺寸不可小于0或大于5, 请重新输入': 'en_容差尺寸不可小于0或大于5, 请重新输入',
  '热区占单栅格比例不可小于0或大于1, 请重新输入': 'en_热区占单栅格比例不可小于0或大于1, 请重新输入',
  '热区固定尺寸不可小于0或大于100, 请重新输入': 'en_热区固定尺寸不可小于0或大于100, 请重新输入',
  '输入数据错误, 请输入纯数字': 'en_输入数据错误, 请输入纯数字',
  '不是Group, 不能应用此设置': 'en_不是Group, 不能应用此设置',
  '不是Artboard内的图层, 无法使用此功能': 'en_不是Artboard内的图层, 无法使用此功能',
  '找不到该屏幕下的栅格配置': 'en_找不到该屏幕下的栅格配置',
  '当前画布宽度不能添加分栏栅格': 'en_当前画布宽度不能添加分栏栅格',
  '无法获取对应的栅格配置, 请检查断点设置': 'en_无法获取对应的栅格配置, 请检查断点设置',
  '分栏栅格': 'en_分栏栅格',
  '画布的宽度不够，不能添加分栏栅格': 'en_画布的宽度不够，不能添加分栏栅格',
  '必须先创建Artboard': 'en_必须先创建Artboard',
  '屏幕宽度不满足分栏要求': 'en_屏幕宽度不满足分栏要求',
  '无可导入的Symbol': 'No importable symbols',
  '没有找到可用的库': 'No valid library found',
  '没有找到Symbol': 'No symbol found',
  '只能替换Symbol库里面的Symbol': 'Replace only Symbol in Symbol library',
  '无法直接标注样式，请尝试选择Style Layer进行标注': 'en_无法直接标注样式，请尝试选择Style Layer进行标注',
  '库中无可导入的Icon': 'No import icons in library',
  '文本对象无法完成替换': 'en_文本对象无法完成替换',
  '请检查选中对象是否为图标': 'en_请检查选中对象是否为图标',
  '非Symbol对象无法完成替换': 'en_非Symbol对象无法完成替换',
  '更改属性失败，内部元素已全部固定宽高': 'en_更改属性失败，内部元素已全部固定宽高',
  '只能选中一个对象设置': 'en_只能选中一个对象设置',
  '父容器不能是页面': 'en_父容器不能是页面',
  '画板边距关系应用成功': 'en_画板边距关系应用成功',
  '只能选中两个对象设置': 'en_只能选中两个对象设置',
  '对象间距关系不生效，需设置其任一对象宽度为Pin': 'en_对象间距关系不生效，需设置其任一对象宽度为Pin',
  '选中一个对象只能是已经设置过兄弟关系的group才行': 'en_选中一个对象只能是已经设置过兄弟关系的group才行',
  '间距关系应用成功': 'en_间距关系应用成功',
  '至少选中一个对象': 'en_至少选中一个对象',
  '选中一个对象只能是已经设置过层叠关系的group才行': 'en_选中一个对象只能是已经设置过层叠关系的group才行',
  '底部元素不是Shape或者Image': 'en_底部元素不是Shape或者Image',
  '应用样式成功': 'Style applied successfully.',
  '多个对象': 'Multiple layers',
  '请检查网络环境': 'Please check the network connection',
  '下载成功': 'Download success',
  '下载失败': 'Download failed',
  '下载超时': 'Download timeout',
  '添加失败，未知原因': 'Add failure, unknown cause',
  '请求超时，请稍后再试': 'Request timeout, please try again later',
  '网络请求异常，导致无法加载,请稍后再试': 'Network request exception, resulting in unable to load, try again later',
  'Library与当前Sketch版本不兼容，请更新版本再试': 'Library is not compatible with the current Sketch version, please update the version and try again',
  '该库已存在': 'The library already exists',
  '不透明': 'opacity',
  '颜色': 'Color',
  '字体': 'Font',
  '圆角': 'Round corners',
  'HarmonyOS 设计插件与当前sketch版本不兼容': 'HarmonyOS Design Tool is incompatible with the current Sketch',
  '网络错误': 'Network Error'
};
var allDict = {
  zh: zhDict,
  en: enDict
};
var lang = {
  LSTR: function LSTR(key) {
    var code = NSLocale.currentLocale().languageCode();
    var langDict = allDict[code];
    var str = langDict[key];

    if (!str) {
      return key;
    }

    return str;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (lang);

/***/ }),

/***/ "./src/util/token.js":
/*!***************************!*\
  !*** ./src/util/token.js ***!
  \***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ux/src/utils/ocUtil */ "./src/ux/src/utils/ocUtil.js");
 // import UI from 'sketch/ui';

 // import config from '../util/config.js';

var token = {
  getToken: function getToken() {
    var commonToken = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('commonToken') || '';
    return commonToken;
  },
  setToken: function setToken(token) {
    sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.setSettingForKey('commonToken', token);
  },
  getW3Account: function getW3Account() {
    var commonW3Account = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('commonW3Account') || '';
    return commonW3Account;
  },
  setW3Account: function setW3Account(account) {
    sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.setSettingForKey('commonW3Account', account);
  },
  updateOcInfo: function updateOcInfo() {
    _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__["default"].updateToken(this.getToken());
    _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__["default"].updateW3Account(this.getW3Account());
  } // checkToken: function (okCB, errCB) {
  //   let token = this.getToken();
  //   let headers = {
  //     Access: 'Client',
  //     Authorization: 'Bearer ' + token
  //   };
  //   let obj = {
  //     url: config.domain() + '/sketchcloud/auth/getLoginUserInfo',
  //     headers: headers
  //   };
  //   let httpCB = function (params) {
  //     let respObj = JSON.parse(params);
  //     let code = respObj.code || '';
  //     let content = respObj.content || {};
  //     let tk = content.access_token || '';
  //     if (code != '200' || tk.length < 1) {
  //       errCB();
  //     } else {
  //       okCB();
  //     }
  //   };
  // ocUtil.loadClass('UXNetwork', 'UXNetwork.bundle');
  // UXNetwork.HTTPGet_jsCallback(JSON.stringify(obj), httpCB);

};
/* harmony default export */ __webpack_exports__["default"] = (token);

/***/ }),

/***/ "./src/util/util.js":
/*!**************************!*\
  !*** ./src/util/util.js ***!
  \**************************/
/*! exports provided: canShow, getPanelPosition, getLibraries, getAllLibraries, sendToSidebar, xToHexRGBA, darkCheckerFn, setThemeInfo, setStyle, getResourceInfo, toSidebar, loadUrlForUrlManager, hostForUrlManager, postToStatistics, version, statistics, themeId, searchPath */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(fetch) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canShow", function() { return canShow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelPosition", function() { return getPanelPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLibraries", function() { return getLibraries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAllLibraries", function() { return getAllLibraries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendToSidebar", function() { return sendToSidebar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "xToHexRGBA", function() { return xToHexRGBA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "darkCheckerFn", function() { return darkCheckerFn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setThemeInfo", function() { return setThemeInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStyle", function() { return setStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getResourceInfo", function() { return getResourceInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSidebar", function() { return toSidebar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUrlForUrlManager", function() { return loadUrlForUrlManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostForUrlManager", function() { return hostForUrlManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "postToStatistics", function() { return postToStatistics; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "statistics", function() { return statistics; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "themeId", function() { return themeId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "searchPath", function() { return searchPath; });
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _util_config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/config.js */ "./src/util/config.js");
/* harmony import */ var _lang_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lang.js */ "./src/util/lang.js");


 // import { gc_adaptive_base_host } from '../globalConfig.js';

var UI = __webpack_require__(/*! sketch/ui */ "sketch/ui");

var sketch = __webpack_require__(/*! sketch/dom */ "sketch/dom");

function canShow() {
  var obj = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('newPlatformInfos');
  var Newtheme = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('NewTheme');
  var NewLibraryName = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('NewLibraryName');

  if (!obj || !NewLibraryName || !Newtheme) {
    UI.message(_lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('没有平台信息，请先进行设置'));
    return false;
  }

  return true;
}
var getPanelPosition = function getPanelPosition(context, n, width, height, flag) {
  var windowFrame = context.document.window().frame(); // let x = (windowFrame.origin.x + windowFrame.size.width - 240 - 40 - width) || 400;

  var x = 0;
  var contentView = context.document.documentWindow().contentView();

  if (!contentView) {
    return {};
  }

  var stageView = contentView.subviews().objectAtIndex(0);
  var views = stageView.subviews();

  if (views && views.length) {
    for (var i = 0; i < views.length; i++) {
      if (views[i].identifier() == 'view_canvas') {
        x = views[i].frame().origin.x + views[i].frame().size.width;
        break;
      }
    }
  }

  x = windowFrame.origin.x + x - width || 400;
  var splitView = context.document.splitViewController().splitView();
  var spiltFrame = splitView.frame();
  var y = NSScreen.mainScreen().frame().size.height - (windowFrame.origin.y + spiltFrame.size.height) + height + 40 * n - 16 || 300;

  if (flag === 'reverse') {
    y = NSScreen.mainScreen().frame().size.height - windowFrame.origin.y - 40 * n + 4;
  }

  var position = {
    x: x,
    y: y
  };
  return position;
};
var getLibraries = function getLibraries(sketch) {
  var allLibraries = sketch.getLibraries().filter(function (l) {
    return l.valid && l.enabled && (l.libraryType === 'Remote' || l.libraryType === 4 || l.libraryType === 'RemoteThirdParty');
  });
  var allLibrariesArray = [];

  if (allLibraries && allLibraries.length) {
    for (var i = 0; i < allLibraries.length; i++) {
      var path = allLibraries[i].getDocument() && allLibraries[i].getDocument().path;

      if (path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].serverIP()) >= 0) {
        var pathArr = path && path.split('/');
        var groupId = pathArr && pathArr.length && pathArr[pathArr.length - 2];

        var _platformId = pathArr && pathArr.length && pathArr[pathArr.length - 3];

        var updateTime = allLibraries[i].lastModifiedAt && new Date(allLibraries[i].lastModifiedAt).getTime();
        var libraryObj = {
          name: allLibraries[i].name,
          groupId: groupId,
          platformId: _platformId,
          time: updateTime
        };
        allLibrariesArray.push(libraryObj);
      }
    }
  }

  var allLibrariesString = allLibrariesArray && allLibrariesArray.length && JSON.stringify(allLibrariesArray);
  return allLibrariesString;
};
var getAllLibraries = function getAllLibraries(sketch) {
  var allLibraries = sketch.getLibraries().filter(function (l) {
    return l.valid && l.enabled;
  });
  return allLibraries;
};
var sendToSidebar = function sendToSidebar(context, identifier, selected) {
  var selectedInfo = {
    command: identifier,
    selected: selected
  };
  var contentView = context.document ? context.document.documentWindow() && context.document.documentWindow().contentView() : context.actionContext.document.documentWindow().contentView();

  if (contentView) {
    var stageView = contentView.subviews().objectAtIndex(0);
    var views = stageView.subviews();
    var webview = null;
    views.forEach(function (view, i) {
      if (view.identifier() == 'sketchcloud.sidebar') {
        webview = view;
      }
    });

    if (webview) {
      webview.evaluateJavaScript_completionHandler('sendSelected(' + JSON.stringify(selectedInfo) + ')', null);
    }
  }
};
var xToHexRGBA = function xToHexRGBA(color, opacity) {
  var HexRGBA = color.toUpperCase();

  if (color.indexOf('rgb') >= 0) {
    var rgbaLeft = color && color.split('(')[1];
    var rgbaRight = rgbaLeft && rgbaLeft.split(')')[0];
    var rgbaArray = rgbaRight && rgbaRight.split(',');
    var r = rgbaArray && rgbaArray[0] && toHex(rgbaArray[0]) || 'FF';
    var g = rgbaArray && rgbaArray[1] && toHex(rgbaArray[1]) || 'FF';
    var b = rgbaArray && rgbaArray[2] && toHex(rgbaArray[2]) || 'FF';
    var a = rgbaArray && rgbaArray[3] && toHex(rgbaArray[3] * 255) || 'FF';
    HexRGBA = '#' + r + g + b + a;
  } else if (color.indexOf('#') >= 0) {
    if (color.length === 7) {
      if (opacity) {
        opacity = toHex(opacity * 255);
      }

      HexRGBA = color.toUpperCase() + (opacity || 'FF');
    }
  }

  return HexRGBA;
};
var darkCheckerFn = function darkCheckerFn(fn) {
  var ObjCClass = __webpack_require__(/*! cocoascript-class */ "./node_modules/cocoascript-class/lib/index.js").default;

  var DarkChecker = ObjCClass({
    classname: 'DarkChecker',
    register: function register() {
      var app = NSApplication.sharedApplication();
      app.addObserver_forKeyPath_options_context(this, 'appearance', NSKeyValueChangeNewKey, null);
    },
    'observeValueForKeyPath:ofObject:change:context:': fn,
    deregister: function deregister() {
      NSApplication.sharedApplication().removeObserver_forKeyPath_(this, 'appearance');
    }
  });
  return DarkChecker;
};

function toHex(c) {
  var hex = Math.round(c).toString(16).toUpperCase();
  return hex.length === 1 ? '0' + hex : hex;
}

function setThemeInfo(themeInfo, data) {
  if (data.themeId) {
    themeInfo.themeInfo = {
      id: data.themeId
    };
  } else {
    themeInfo.themeInfo = {
      id: ''
    };
  }

  if (data.brandId) {
    themeInfo.brandInfo = {
      id: data.brandId
    };
  } else {
    themeInfo.brandInfo = {
      id: ''
    };
  }

  if (data.deviceId) {
    themeInfo.deviceInfo = {
      id: data.deviceId
    };
  } else {
    themeInfo.deviceInfo = {
      id: ''
    };
  }

  if (data.libraryId) {
    themeInfo.libraryInfo = {
      id: data.libraryId
    };
  } else {
    themeInfo.libraryInfo = {
      id: ''
    };
  }
}
var setStyle = {
  setColor: function setColor(layer, color) {
    var self = this;
    var success = false;
    color = self.deatil8color(color);
    var duplication_codes = 'x'; // duplication_codes扫描

    if (layer.type === 'Shape' || layer.type === 'ShapePath') {
      if (layer.style.fills[0] && layer.style.fills[0].enabled) {
        layer.style.fills[0].color = color;
        success = true;
      }

      duplication_codes = 'x';
    } else if (layer.type === 'Text') {
      if (layer.style.textColor) {
        layer.style.textColor = color;
        success = true;
      }
    }

    return success;
  },
  setBorder: function setBorder(layer, color) {
    var success = false;
    var self = this;

    if (layer.type === 'Shape' || layer.type === 'ShapePath' || layer.type === 'Text') {
      color = self.deatil8color(color);

      if (layer.style.borders[0] && layer.style.borders[0].enabled) {
        layer.style.borders[0].color = color;
        success = true;
      }
    }

    return success;
  },
  setShadow: function setShadow(layer, color) {
    var success = false;
    var self = this;

    if (layer.style.shadows[0] && layer.style.shadows[0].enabled) {
      color = self.deatil8color(color);
      layer.style.shadows[0].color = color;
      success = true;
    }

    return success;
  },
  setFontSize: function setFontSize(layer, fontSize) {
    var success = false;
    var self = this;

    if (layer.type === 'Text') {
      if (layer.style.fontSize) {
        layer.style.fontSize = fontSize;
        success = true;
        self.setfontFamily(layer);
      }
    }

    return success;
  },
  setFontWeight: function setFontWeight(layer, fontWeight) {
    var success = false;
    var self = this;
    var text = layer.text;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo');
    var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId;
    var themeInfo = loginInfo && loginInfo.themeInfo;
    var themeId = themeInfo && themeInfo.themeInfo && themeInfo.themeInfo.id;

    if (layer.type === 'Text') {
      if (layer.style) {
        self.setfontFamily(layer, fontWeight);

        if (platformId === 1) {
          if (fontWeight === 'regular') {
            layer.style.fontWeight = 4;
            success = true;
          } else if (fontWeight === 'medium') {
            layer.style.fontWeight = 7;
            success = true;
          }
        } else if (platformId === 2 || platformId === 3) {
          success = this.setOtherPlatformFontWeight(fontWeight, layer, success, themeId, self, text);
        } else if (platformId === 4) {
          success = true;
        }
      }
    }

    return success;
  },
  // 设置Platform2和3的字重
  setOtherPlatformFontWeight: function setOtherPlatformFontWeight(fontWeight, layer, success, themeId, self, text) {
    if (fontWeight.indexOf('Regular') >= 0) {
      layer.style.fontWeight = 5;
      success = true;
    } else if (fontWeight.indexOf('Medium') >= 0) {
      if (parseInt(themeId) === 697) {
        var isHan = self.isHan(text);

        if (isHan) {
          layer.style.fontWeight = 6;
          success = true;
        } else {
          layer.style.fontWeight = 5;
          success = true;
        }
      } else if (parseInt(themeId) === 698) {
        layer.style.fontWeight = 6;
        success = true;
      }
    } else if (fontWeight.indexOf('Semibold') >= 0) {
      var _isHan = self.isHan(text);

      if (_isHan) {
        layer.style.fontWeight = 8;
        success = true;
      } else {
        if (parseInt(themeId) === 697) {
          layer.style.fontWeight = 5;
          success = true;
        } else if (parseInt(themeId) === 698) {
          layer.style.fontWeight = 6;
          success = true;
        }
      }
    } else if (fontWeight.indexOf('Bold Condensed') >= 0) {
      var _isHan2 = self.isHan(text);

      if (_isHan2) {
        layer.style.fontWeight = 6;
        success = true;
      } else {
        layer.style.fontWeight = 9;
        layer.style.fontStretch = 'condensed';
        success = true;
      }
    }

    return success;
  },
  setLineHeight: function setLineHeight(layer, lineHeight) {
    var success = false;
    var self = this;
    lineHeight *= layer.style.fontSize;

    if (layer.type === 'Text') {
      if (layer.style) {
        layer.style.lineHeight = lineHeight;
        success = true;
        self.setfontFamily(layer);
      }
    }

    return success;
  },
  setfontFamily: function setfontFamily(layer, fontWeight) {
    var self = this;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo');
    var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId;
    var themeInfo = loginInfo && loginInfo.themeInfo;
    var themeId = themeInfo && themeInfo.themeInfo && themeInfo.themeInfo.id;

    if (layer.type === 'Text') {
      if (layer.style) {
        if (platformId === 1) {
          layer.style.fontFamily = 'HWtext';
        } else if (platformId === 2 || platformId === 3) {
          var text = layer.text;
          var isHan = self.isHan(text);

          if (isHan) {
            layer.style.fontFamily = 'PingFang SC';
          } else {
            if (parseInt(themeId) === 697) {
              if (fontWeight && (fontWeight.indexOf('Medium') >= 0 || fontWeight.indexOf('Semibold') >= 0)) {
                layer.style.fontFamily = 'Huawei Sans Medium';
              } else {
                layer.style.fontFamily = 'Huawei Sans';
              }
            } else if (parseInt(themeId) === 698) {
              layer.style.fontFamily = 'Roboto';
            }
          }
        } else if (platformId === 4) {
          if (fontWeight) {
            if (fontWeight.indexOf('Medium') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-DB-GB';
            } else if (fontWeight.indexOf('Regular') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-R-GB';
            } else if (fontWeight.indexOf('Semibold') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-B-GB';
            } else if (fontWeight.indexOf('细黑') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-L-GB';
            }
          }
        }
      }
    }
  },
  setRadius: function setRadius(layer, radius) {
    var success = false;

    if (layer.type === 'ShapePath' || layer.type === 'Shape') {
      var points = layer.points;
      var width = layer.frame.width;
      var height = layer.frame.height;
      var min = width < height ? width : height;

      if (radius * 2 > min) {
        var text = '⚠️ ' + _lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('圆角过大, 设置失败!');
        UI.message(text);
        return success;
      }

      points.forEach(function (point) {
        point.cornerRadius = radius;
      });
      layer.sketchObject.setFixedRadius(radius);
      success = true;
    }

    return success;
  },
  setOpacity: function setOpacity(layer, opacity) {
    var success = false;

    if (layer.type === 'Shape' || layer.type === 'ShapePath' || layer.type === 'Text') {
      if (layer.style) {
        layer.style.opacity = opacity;
        success = true;
      }
    }

    return success;
  },
  deatil8color: function deatil8color(value) {
    var color = value;

    if (value.indexOf('#') === 0) {
      value = value.slice(1);
      value = value.toUpperCase();

      if (value && value.length === 8) {
        var rgb = value.slice(2);
        var a = value.slice(0, 2);
        color = '#' + rgb + a;
      } else if (value.length === 6) {
        color = '#' + value + 'FF';
      } else {
        color = '#' + value;
      }
    } else if (value.indexOf('rgb') === 0) {
      color = value;
    } else {
      value = value.toUpperCase();

      if (value && value.length === 8) {
        var _rgb = value.slice(2);

        var _a = value.slice(0, 2);

        color = '#' + _rgb + _a;
      } else if (value.length === 6) {
        color = '#' + value + 'FF';
      } else {
        color = '#' + value;
      }
    }

    return color;
  },
  isHan: function isHan(text) {
    var han = /^[\u4e00-\u9fa5]+$/;
    var isHan = false;

    if (text && text.length) {
      for (var i = 0; i < text.length; i++) {
        if (han.test(text[i])) {
          isHan = true;
          break;
        }
      }
    }

    return isHan;
  }
};
function getResourceInfo() {
  var data = {};
  var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo') || {};

  if (loginInfo.userInfo && loginInfo.themeInfo) {
    var resourceUpdateInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('resourceUpdateInfo') || {};
    var userInfo = loginInfo.userInfo;
    var themeInfo = loginInfo.themeInfo || {};

    var _platformId2 = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;

    var accessToken = userInfo && userInfo.access_token;

    var _libraryId = themeInfo.libraryInfo && themeInfo.libraryInfo.id;

    var _themeId = themeInfo.themeInfo && themeInfo.themeInfo.id;

    var createTime = resourceUpdateInfo[_platformId2] && resourceUpdateInfo[_platformId2][_libraryId] && resourceUpdateInfo[_platformId2][_libraryId].createTime;
    data = {
      accessToken: accessToken,
      platformId: _platformId2,
      libraryId: _libraryId,
      createTime: createTime,
      themeId: _themeId,
      domain: _util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].domain(),
      pathName: _util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].pathName()
    };
  }

  return data;
}
var toSidebar = function toSidebar(context, messageData) {
  if (!context) {
    return;
  }

  var contentView = context.document ? context.document.documentWindow() && context.document.documentWindow().contentView() : context.actionContext.document.documentWindow().contentView();

  if (contentView) {
    var stageView = contentView.subviews().objectAtIndex(0);
    var views = stageView.subviews();
    var webview = null;
    views.forEach(function (view, i) {
      if (String(view.identifier()) === 'sketchcloud.sidebarxx') {
        webview = view;
      }
    });

    if (webview) {
      webview.evaluateJavaScript_completionHandler('refreshUpdateTips(' + JSON.stringify(messageData) + ')', null);
    }
  }
};
function loadUrlForUrlManager(type) {
  var bundlePathPrefix = '/Contents/Resources/js/';
  var path = NSString.stringWithString_(coscript.env().scriptURL.path());

  while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
    path = path.stringByDeletingLastPathComponent();
  }

  ;
  var PathJsonStr = NSString.stringWithContentsOfFile_encoding_error(path + bundlePathPrefix + 'urlManager.json', 4, nil);
  var firstDict = JSON.parse(PathJsonStr);
  var urlName = firstDict.url;
  var idName = firstDict.id;
  var devName = firstDict.dev;
  var betaName = firstDict.beta;
  var prodName = firstDict.prod;
  var localName = firstDict.local;
  var someName = firstDict.someOne;

  switch (type) {
    case 'dev':
      return devName;

    case 'beta':
      return betaName;

    case 'prod':
      return prodName;

    case 'local':
      return localName;

    case 'someOne':
      return someName;

    case 'url':
      return urlName;

    case 'id':
      return idName;

    default:
      break;
  }
}
function hostForUrlManager() {
  var bundlePathPrefix = '/Contents/Resources/js/';
  var path = NSString.stringWithString_(coscript.env().scriptURL.path());

  while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
    path = path.stringByDeletingLastPathComponent();
  }

  ;
  var PathJsonStr = NSString.stringWithContentsOfFile_encoding_error(path + bundlePathPrefix + 'urlManager.json', 4, nil);
  var firstDict = JSON.parse(PathJsonStr);
  var currentState = firstDict.current;
  return currentState;
} // 发送打点计数消息给后台

function postToStatistics(code, type) {
  var host = hostForUrlManager();
  var first = loadUrlForUrlManager(host);
  var url = first.gc_uxfm_ip + '/trace/statistics';
  var body = {
    'code': code
  };

  if (code === '102' || code === '202') {
    body = {
      'code': code,
      'function': type
    };
  } else if (code === '101') {
    body = {
      'code': code,
      'device': type
    };
  }

  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(body)
  }).then(function (response) {
    return response.json();
  }).then(function (text) {
    if (text && text.code === '200') {// 请求成功
    } else if (text && text.code === '401') {// 请求失败
    } else {}
  }).catch(function (e) {
    if (code === '202') {
      // 点击sidebar上的功能图标，如果打点服务调不通，提示网络错误
      UI.message(_lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('网络错误'));
    }
  });
}
var version = sketch.version.sketch + '';
var statistics = ''; // export let searchPath = {loginInfo
//     search: function () {

var searchPath = '';
var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo') || {};
var system = loginInfo.system || {};
var platformId = system.platformId || '';
var deviceId = loginInfo.deviceId || '';
var libraryId = loginInfo.libraryId || '';
var brandId = loginInfo.brandId || '';
var themeId = loginInfo.themeId || '';
searchPath = "#/sourceManage?platformId=".concat(platformId, "&deviceId=").concat(deviceId, "&libraryId=").concat(libraryId, "&brandId=").concat(brandId, "&themeId=").concat(themeId); // return search;
//     }
// };


/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/sketch-polyfill-fetch/lib/index.js */ "./node_modules/sketch-polyfill-fetch/lib/index.js")))

/***/ }),

/***/ "./src/ux/src/customWebView/MochaJSDelegate.js":
/*!*****************************************************!*\
  !*** ./src/ux/src/customWebView/MochaJSDelegate.js ***!
  \*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

//
//  MochaJSDelegate.js
//  MochaJSDelegate
//
//  Created by Matt Curtis
//  Copyright (c) 2015. All rights reserved.
//
var MochaJSDelegate = function MochaJSDelegate(selectorHandlerDict) {
  var uniqueClassName = 'MochaJSDelegate_DynamicClass_' + NSUUID.UUID().UUIDString();
  var delegateClassDesc = MOClassDescription.allocateDescriptionForClassWithName_superclass_(uniqueClassName, NSObject);
  delegateClassDesc.registerClass(); // Handler storage

  var handlers = {}; // Define interface

  this.setHandlerForSelector = function (selectorString, func) {
    var handlerHasBeenSet = (selectorString in handlers);
    var selector = NSSelectorFromString(selectorString);
    handlers[selectorString] = func;

    if (!handlerHasBeenSet) {
      /*
        For some reason, Mocha acts weird about arguments:
        https://github.com/logancollins/Mocha/issues/28
        We have to basically create a dynamic handler with a likewise dynamic number of predefined arguments.
      */
      // eslint-disable-next-line no-unused-vars
      var dynamicHandler = function dynamicHandler() {
        var functionToCall = handlers[selectorString];
        if (!functionToCall) return;
        return functionToCall.apply(delegateClassDesc, arguments);
      };

      var args = [];
      var regex = /:/g; // eslint-disable-next-line no-unused-vars

      var match; // eslint-disable-next-line no-cond-assign

      while (match = regex.exec(selectorString)) {
        args.push('arg' + args.length);
      }

      var dynamicFunction = eval('(function(' + args.join(',') + '){ return dynamicHandler.apply(this, arguments); })');
      delegateClassDesc.addInstanceMethodWithSelector_function_(selector, dynamicFunction);
    }
  };

  this.removeHandlerForSelector = function (selectorString) {
    delete handlers[selectorString];
  };

  this.getHandlerForSelector = function (selectorString) {
    return handlers[selectorString];
  };

  this.getAllHandlers = function () {
    return handlers;
  };

  this.getClass = function () {
    return NSClassFromString(uniqueClassName);
  };

  this.getClassInstance = function () {
    return NSClassFromString(uniqueClassName).new();
  }; // Conveience


  if (_typeof(selectorHandlerDict) === 'object') {
    for (var selectorString in selectorHandlerDict) {
      this.setHandlerForSelector(selectorString, selectorHandlerDict[selectorString]);
    }
  }
};

/* harmony default export */ __webpack_exports__["default"] = (MochaJSDelegate);

/***/ }),

/***/ "./src/ux/src/customWebView/fitSubview.js":
/*!************************************************!*\
  !*** ./src/ux/src/customWebView/fitSubview.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function addEdgeConstraint(edge, subview, view, constant) {
  view.addConstraint(NSLayoutConstraint.constraintWithItem_attribute_relatedBy_toItem_attribute_multiplier_constant(subview, edge, NSLayoutRelationEqual, view, edge, 1, constant));
}

module.exports = function fitSubviewToView(subview, view, constants) {
  constants = constants || [];
  subview.setTranslatesAutoresizingMaskIntoConstraints(false);
  addEdgeConstraint(NSLayoutAttributeLeft, subview, view, constants[0] || 0);
  addEdgeConstraint(NSLayoutAttributeTop, subview, view, constants[1] || 0);
  addEdgeConstraint(NSLayoutAttributeRight, subview, view, constants[2] || 0);
  addEdgeConstraint(NSLayoutAttributeBottom, subview, view, constants[3] || 0);
};

/***/ }),

/***/ "./src/ux/src/customWebView/positionAndSize.js":
/*!*****************************************************!*\
  !*** ./src/ux/src/customWebView/positionAndSize.js ***!
  \*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var ICON_SIZE = 40; // const LOGO_SIZE = 32;

var LOGO_SIZE = 40;
var positionAndSize = {
  getPosition: function getPosition(n, width, height) {
    var document = __webpack_require__(/*! sketch/dom */ "sketch/dom").getSelectedDocument();

    var doc = document.sketchObject;
    var windowFrame = doc.window().frame();
    var x = 0;
    var y = 0;
    var contentView = doc.documentWindow().contentView();

    if (!contentView) {
      return {};
    }

    var stageView = contentView.subviews().objectAtIndex(0);
    var views = stageView.subviews();

    if (views && views.length) {
      for (var i = 0; i < views.length; i++) {
        if (views[i].identifier() == 'view_canvas') {
          x = views[i].frame().origin.x + views[i].frame().size.width;
          y = views[i].frame().origin.y + views[i].frame().size.height;
          break;
        }
      }
    }

    x = windowFrame.origin.x + x - width;

    if (n < 0) {
      y = windowFrame.origin.y + (-1 - n) * ICON_SIZE + (n === -1 ? 0 : 1);
    } else {
      y = windowFrame.origin.y + y - height - (n - 1) * ICON_SIZE - LOGO_SIZE - (n === 1 ? 0 : 1);
    }

    var position = {
      x: x,
      y: y
    };
    return position;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (positionAndSize);

/***/ }),

/***/ "./src/ux/src/customWebView/smWebview.js":
/*!***********************************************!*\
  !*** ./src/ux/src/customWebView/smWebview.js ***!
  \***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _MochaJSDelegate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MochaJSDelegate */ "./src/ux/src/customWebView/MochaJSDelegate.js");
/* harmony import */ var _positionAndSize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./positionAndSize */ "./src/ux/src/customWebView/positionAndSize.js");

 // import lang from '../../../util/lang';

var fitSubviewToView = __webpack_require__(/*! ./fitSubview */ "./src/ux/src/customWebView/fitSubview.js");

var UI = __webpack_require__(/*! sketch/ui */ "sketch/ui");

var TITLE_BAR_HEIGHT = 16;
var CLOSE_BTN_X = 8;
COScript.currentCOScript().setShouldKeepAround_(true);
var smWebView = {
  setPositionAndSize: function setPositionAndSize(id, x, y, width, height) {
    var animate = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
    var panel = this.getPanelById(id);

    if (!panel) {
      return null;
    }

    var cocoaBounds = NSMakeRect(x, y, width, height);
    panel.setFrame_display_animate(cocoaBounds, true, animate);
    panel.orderFrontRegardless();
  },
  isWebviewPresent: function isWebviewPresent(id) {
    if (this.getWebviewById(id)) {
      return true;
    }

    return false;
  },
  executeJavaScript: function executeJavaScript(windowObject, jsScript) {
    if (typeof windowObject === 'string') {
      windowObject = this.getWindowObjectById(windowObject);
    }

    if (!windowObject) {
      console.log(' windowObject 不能为空');
      return;
    }

    windowObject.evaluateWebScript(jsScript);
  },
  getPanelById: function getPanelById(id) {
    var threadDictionary = NSThread.mainThread().threadDictionary();

    if (threadDictionary[id]) {
      return threadDictionary[id];
    }
  },
  getWebviewById: function getWebviewById(id) {
    var panel = this.getPanelById(id);

    if (!panel || !panel.contentView) {
      return null;
    }

    var webView = null;
    var subviews = panel.contentView().subviews();

    for (var i = 0; i < subviews.length; i += 1) {
      if (!webView && subviews[i].isKindOfClass(WebView)) {
        webView = subviews[i];
      }
    } // if (!webView) {
    //     throw new Error('The panel needs to have a webview')
    // }


    return webView;
  },
  getWindowObjectById: function getWindowObjectById(id) {
    var webView = this.getWebviewById(id);

    if (!webView) {
      return null;
    }

    var windowObject = webView.windowScriptObject();
    return windowObject;
  },
  show: function show(id) {
    var panel = this.getPanelById(id);

    if (panel) {
      panel.orderFrontRegardless();
    }
  },
  hide: function hide(id) {
    var panel = this.getPanelById(id);

    if (panel) {
      panel.orderOut(null);
    }
  },
  kill: function kill(id) {
    var panel = this.getPanelById(id);

    if (panel) {
      var threadDictionary = NSThread.mainThread().threadDictionary();
      threadDictionary.removeObjectForKey(id);
      panel.close();
    } // COScript.currentCOScript().setShouldKeepAround(false);

  },
  close: function close(id) {
    this.kill(id);
  },
  extend: function extend(options, target) {
    target = target || this;

    for (var key in options) {
      target[key] = options[key];
    }

    return target;
  },
  SMPanel: function SMPanel(options) {
    var self = this;
    options = this.extend(options, {
      width: 240,
      height: 316,
      center: false,
      frame: false,
      floatWindow: true,
      hiddenClose: false,
      readyToShow: null,
      callBackList: {},
      x: 0,
      y: 0
    }); // var result = false;

    var frame = NSMakeRect(options.x, options.y, options.width, options.height);
    var titleBgColor = NSColor.colorWithRed_green_blue_alpha(0.933, 0.933, 0.933, 1);
    var contentBgColor = NSColor.colorWithRed_green_blue_alpha(0.933, 0.933, 0.933, 1);
    var theme = UI.getTheme();

    if (theme == 'dark') {
      titleBgColor = NSColor.colorWithRed_green_blue_alpha(0.22, 0.227, 0.259, 1);
      contentBgColor = NSColor.colorWithRed_green_blue_alpha(0.22, 0.227, 0.259, 1);
    }

    if (options.frame) {
      frame = NSMakeRect(options.x, options.y, options.width, options.height + TITLE_BAR_HEIGHT);
    } // titleBgColor = NSColor.clearColor();
    // contentBgColor = NSColor.clearColor();


    if (options.identifier) {
      var threadDictionary = NSThread.mainThread().threadDictionary();

      if (threadDictionary[options.identifier]) {
        var panel = this.getPanelById(options.identifier);

        if (panel) {
          panel.orderFrontRegardless();
        }

        return;
      }
    }

    var Panel;
    var contentView;

    if (options.frame === false) {
      var styleMask = NSTitledWindowMask;
      styleMask |= NSTexturedBackgroundWindowMask;
      Panel = NSPanel.alloc().initWithContentRect_styleMask_backing_defer(frame, styleMask, NSBackingStoreBuffered, true);
      Panel.titlebarAppearsTransparent = true;
      Panel.titleVisibility = NSWindowTitleHidden;
      Panel.setOpaque(0);
      Panel.isMovableByWindowBackground = true;
      var toolbar2 = NSToolbar.alloc().initWithIdentifier('titlebarStylingToolbar');
      toolbar2.setShowsBaselineSeparator(false);
      Panel.setToolbar(toolbar2);
      contentView = Panel.contentView();
    } else {
      Panel = NSPanel.alloc().init();
      Panel.setFrame_display(frame, false); // Panel.setTitleVisibility(NSWindowTitleHidden);
      // Panel.setTitlebarAppearsTransparent(true);

      Panel.standardWindowButton(NSWindowCloseButton).setHidden(options.hiddenClose);
      Panel.standardWindowButton(NSWindowMiniaturizeButton).setHidden(true);
      Panel.standardWindowButton(NSWindowZoomButton).setHidden(true);
      Panel.setBackgroundColor(contentBgColor);
      contentView = Panel.contentView();
      var titlebarView = contentView.superview().titlebarViewController().view();
      var titlebarContainerView = titlebarView.superview();
      var closeButton = Panel.standardWindowButton(NSWindowCloseButton);
      closeButton.setFrameOrigin(NSMakePoint(CLOSE_BTN_X, CLOSE_BTN_X)); // titlebarContainerView.setFrame(NSMakeRect(0, options.height, options.width, TITLE_BAR_HEIGHT));
      // titlebarView.setFrameSize(NSMakeSize(options.width, TITLE_BAR_HEIGHT));

      titlebarView.setTransparent(true);
      titlebarView.setBackgroundColor(titleBgColor);
      titlebarContainerView.superview().setBackgroundColor(titleBgColor);

      if (options.title) {
        Panel.setTitle(options.title);
      } // contentView.setWantsLayer(true);
      // contentView.layer().setFrame( contentView.frame() );
      // contentView.layer().setCornerRadius(0);
      // contentView.layer().setMasksToBounds(true);

    }

    var panDelegate = new _MochaJSDelegate__WEBPACK_IMPORTED_MODULE_0__["default"]({
      'windowWillClose:': function windowWillClose() {
        console.log('windowWillClose');

        if (options.identifier) {
          // self.hide(options.identifier);
          self.kill(options.identifier);
        }
      }
    });
    Panel.setDelegate(panDelegate.getClassInstance());
    var webView = this.initWebView(options);

    if (options.frame === false) {
      contentView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable);
      fitSubviewToView(contentView, contentView.superview());
      webView.setFrame(contentView.bounds());
      contentView.addSubview(webView);
    } else {
      webView.setFrame(contentView.bounds());
      contentView.addSubview(webView);
    }

    var uri = encodeURI(options.url);
    webView.setMainFrameURL_(uri);

    if (options.floatWindow) {
      Panel.becomeKeyWindow();
      Panel.setLevel(NSFloatingWindowLevel);

      if (options.center) {
        Panel.center();
      }

      Panel.makeKeyAndOrderFront(nil);

      if (options.identifier) {
        threadDictionary[options.identifier] = Panel;
      }
    } else {
      if (options.identifier) {
        threadDictionary[options.identifier] = Panel;
      }

      NSApp.runModalForWindow(Panel);
    } // self.hide(options.identifier);

  },
  setSize: function setSize(id, width, height, animate) {
    var bounds = this.getBounds(id);

    if (bounds) {
      bounds.size.height = height;
      bounds.size.width = width;
      return this.setBounds(id, bounds, animate);
    }
  },
  getSize: function getSize(id) {
    var bounds = this.getBounds(id);

    if (bounds) {
      return [bounds.size.width, bounds.size.height];
    }

    return [0, 0];
  },
  getBounds: function getBounds(id) {
    var panel = this.getPanelById(id);

    if (panel) {
      return panel.frame();
    }

    return null;
  },
  setBounds: function setBounds(id, bounds, animate) {
    var panel = this.getPanelById(id);

    if (panel) {
      var size = bounds.size;
      var cocoaBounds = NSMakeRect(bounds.origin.x, 0, size.width, size.height);
      var screen = NSScreen.screens().firstObject();
      cocoaBounds.origin.y = NSHeight(screen.frame()) - size.height - bounds.origin.y;
      panel.setFrame_display_animate(cocoaBounds, true, animate);
    }
  },
  getPosition: function getPosition(id) {
    var bounds = this.getBounds(id);

    if (bounds) {
      var mainScreenRect = NSScreen.screens().firstObject().frame();
      return [bounds.origin.x, Math.round(NSHeight(mainScreenRect) - bounds.origin.y)];
    }

    return [0, 0];
  },
  setPosition: function setPosition(id, x, y, animate) {
    var bounds = this.getBounds();
    var mainScreenRect = NSScreen.screens().firstObject().frame();

    if (bounds) {
      bounds.origin.x = x;
      bounds.origin.y = Math.round(NSHeight(mainScreenRect) - y);
      return this.setBounds(bounds, animate);
    }
  },
  setTitle: function setTitle(id, title) {
    var panel = this.getPanelById(id);

    if (panel) {
      return panel.setTitle(title);
    }
  },
  registerMethod: function registerMethod(webView) {
    var windowObject = webView.windowScriptObject();
    webView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable);
    var SMAction = ['function postMessage(hash, data){', 'if(data){', 'window.SMData = encodeURI(JSON.stringify(data));', '}', 'window.location.hash = hash;', '}'].join('');
    windowObject.evaluateWebScript(SMAction);
  },
  // 前端通过调用sketch来设置窗口大小
  setWindowSize: function setWindowSize(windowObject, options) {
    var data;
    var self = this;

    try {
      data = JSON.parse(decodeURI(windowObject.valueForKey('SMData')));
    } catch (e) {
      console.log('parse error');
    }

    console.log('setWindowSize' + '--------');
    console.log(data);
    var offsetH = options.frame ? TITLE_BAR_HEIGHT : 0;

    if (data.index >= 1 || data.index <= -1) {
      var position = _positionAndSize__WEBPACK_IMPORTED_MODULE_1__["default"].getPosition(data.index, data.width, data.height + offsetH);
      self.setPositionAndSize(options.identifier, position.x, position.y, data.width, data.height + offsetH);
    } else {
      var panel = self.getPanelById(options.identifier);

      if (panel) {
        var x = panel.frame().origin.x;
        var y = panel.frame().origin.y;
        self.setPositionAndSize(options.identifier, x, y, data.width, data.height + offsetH);
        panel.center();
      }
    }
  },
  initWebView: function initWebView(options) {
    var self = this;
    var webView = WebView.alloc().init();
    this.registerMethod(webView);
    var delegate = new _MochaJSDelegate__WEBPACK_IMPORTED_MODULE_0__["default"]({
      'webView:didFinishLoadForFrame:': function webViewDidFinishLoadForFrame(webViewRemote, webFrame) {
        self.registerMethod(webViewRemote);
        var windowObject = webViewRemote.windowScriptObject();

        if (options.readyToShow) {
          options.readyToShow(windowObject);
        } // self.show(options.identifier);

      },
      'webView:didChangeLocationWithinPageForFrame:': function webViewDidChangeLocationWithinPageForFrame(webViewRemote, webFrame) {
        var windowObject = webViewRemote.windowScriptObject();
        var request = NSURL.URLWithString(webView.mainFrameURL());
        request = request ? request.fragment() : '';
        request = String(request);
        request = request.replace('/', '');

        for (var funKey in options.callBackList) {
          if (funKey == request) {
            var fun = options.callBackList[funKey];
            var data = void 0;

            try {
              data = JSON.parse(decodeURI(windowObject.valueForKey('SMData')));
            } catch (e) {
              console.log('parse error');
            }

            fun(data);
          }
        }

        if (request == 'setWindowSize') {
          self.setWindowSize(windowObject, options);
        }

        windowObject.evaluateWebScript("window.location.hash = '';");
      }
      /* "webView:didFailLoadWithError:forFrame:": (function (webViewRemote, error, frame) {
                if (webViewRemote == null) {
                    return;
                }
                UI.message(lang.LSTR("请检查网络环境1111" + options.identifier));
                self.kill(options.identifier);
                // COScript.currentCOScript().setShouldKeepAround(false);
            }),
            "webView:didFailProvisionalLoadWithError:forFrame:": (function (webViewRemote, error, frame) {
                if (webViewRemote == null) {
                    return;
                }
                UI.message(lang.LSTR("请检查网络环境2222" + options.identifier));
                self.kill(options.identifier);
                // COScript.currentCOScript().setShouldKeepAround(false);
            }) */

    }); // webView.setBackgroundColor(contentBgColor);

    webView.setFrameLoadDelegate_(delegate.getClassInstance());
    webView.setMaintainsBackForwardList(false);
    return webView;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (smWebView);

/***/ }),

/***/ "./src/ux/src/utils/ocUtil.js":
/*!************************************!*\
  !*** ./src/ux/src/utils/ocUtil.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
// import lang from '../../../util/lang.js';
// var UI = require('sketch/ui');
// function _localizeMenu () {
//   let menu = AppController.sharedInstance().pluginsMenuItem().submenu();
//   let uxsMenu = menu.itemWithTitle('UXS').submenu();
//   let items = uxsMenu.itemArray();
//   let count = items.length;
//   for (let i = 0; i < count; i++) {
//     let item = items.objectAtIndex(i);
//     let title = lang.LSTR(item.title());
//     item.setTitle(title);
//     if (item.hasSubmenu()) {
//       let subMenu = item.submenu();
//       let subArr = subMenu.itemArray();
//       let subCount = subArr.length;
//       for (let j = 0; j < subCount; j++) {
//         let subItem = subArr.objectAtIndex(j);
//         let title = lang.LSTR(subItem.title());
//         subItem.setTitle(title);
//       }
//     }
//   }
// }
var bundlePathPrefix = '/Contents/Resources/oc/';
var ocUtil = {
  localizeMenu: function localizeMenu() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.callJSFunc_delay(_localizeMenu, 2);
  },
  getPluginPath: function getPluginPath() {
    var path = NSString.stringWithString_(coscript.env().scriptURL.path());

    while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
      path = path.stringByDeletingLastPathComponent();
    }

    return path;
  },
  loadBundle: function loadBundle(bundleName) {
    var path = this.getPluginPath();
    var bundlePath = path + bundlePathPrefix + bundleName; // console.log("bundlePath:"+bundlePath);

    var bundle = NSBundle.bundleWithPath_(bundlePath);
    bundle.load();
  },
  unloadBundle: function unloadBundle(bundleName) {
    var path = this.getPluginPath();
    var bundlePath = path + bundlePathPrefix + bundleName; // console.log("bundlePath:"+bundlePath);

    var bundle = NSBundle.bundleWithPath_(bundlePath);
    bundle.unload();
  },
  loadClass: function loadClass(className, bundleName) {
    if (NSClassFromString(className) == null) {
      try {
        this.loadBundle(bundleName); // console.log("Load "+bundleName+" success.");
      } catch (e) {// console.log("Load "+bundleName+" fail.");
      }
    } else {// console.log(bundleName+" has been Loaded.");
      }
  },
  hasWindow: function hasWindow() {// this.loadClass("Helper", "Helper.bundle");
    // return Helper.hasWindow();
  },
  closeWindow: function closeWindow() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.closeWindow();

    return true;
  },
  logout: function logout() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.clearWebCache();
    // Helper.updateToken("");

    return true;
  },
  updateToken: function updateToken(token) {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.updateToken(token);
  },
  updateW3Account: function updateW3Account(account) {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.updateW3Account(account);
  }
};
/* harmony default export */ __webpack_exports__["default"] = (ocUtil);

/***/ }),

/***/ "buffer":
/*!*************************!*\
  !*** external "buffer" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("buffer");

/***/ }),

/***/ "sketch/dom":
/*!*****************************!*\
  !*** external "sketch/dom" ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/dom");

/***/ }),

/***/ "sketch/settings":
/*!**********************************!*\
  !*** external "sketch/settings" ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/settings");

/***/ }),

/***/ "sketch/ui":
/*!****************************!*\
  !*** external "sketch/ui" ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/ui");

/***/ }),

/***/ "util":
/*!***********************!*\
  !*** external "util" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("util");

/***/ })

/******/ });
  if (key === 'default' && typeof exports === 'function') {
    exports(context);
  } else {
    exports[key](context);
  }
}
that['onRun'] = __skpm_run.bind(this, 'default')

//# sourceMappingURL=sourceManage.js.map