uni.js 49.2 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
export function createUniInstance(weex, plus, __uniConfig, __uniRoutes, UniServiceJSBridge, getApp, getCurrentPages){
fxy060608's avatar
fxy060608 已提交
2
var localStorage = plus.storage
fxy060608's avatar
fxy060608 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

const _toString = Object.prototype.toString;
const hasOwnProperty = Object.prototype.hasOwnProperty;

function isFn (fn) {
  return typeof fn === 'function'
}

function isPlainObject (obj) {
  return _toString.call(obj) === '[object Object]'
}

function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

function toRawType (val) {
  return _toString.call(val).slice(8, -1)
}

function getLen (str = '') {
  /* eslint-disable no-control-regex */
  return ('' + str).replace(/[^\x00-\xff]/g, '**').length
}

/**
 * 框架内 try-catch
 */
function tryCatchFramework (fn) {
  return function () {
    try {
      return fn.apply(fn, arguments)
    } catch (e) {
      // TODO
      console.error(e);
    }
  }
}
/**
 * 开发者 try-catch
 */
function tryCatch (fn) {
  return function () {
    try {
      return fn.apply(fn, arguments)
    } catch (e) {
      // TODO
      console.error(e);
    }
  }
}

fxy060608's avatar
fxy060608 已提交
55 56 57 58 59 60 61 62
const HOOKS = [
  'invoke',
  'success',
  'fail',
  'complete',
  'returnValue'
];

fxy060608's avatar
fxy060608 已提交
63 64 65
const globalInterceptors = {};
const scopedInterceptors = {};

fxy060608's avatar
fxy060608 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
function mergeHook (parentVal, childVal) {
  const res = childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
        ? childVal : [childVal]
    : parentVal;
  return res
    ? dedupeHooks(res)
    : res
}

function dedupeHooks (hooks) {
  const res = [];
  for (let i = 0; i < hooks.length; i++) {
    if (res.indexOf(hooks[i]) === -1) {
      res.push(hooks[i]);
    }
  }
  return res
}

function removeHook (hooks, hook) {
  const index = hooks.indexOf(hook);
  if (index !== -1) {
    hooks.splice(index, 1);
  }
}

function mergeInterceptorHook (interceptor, option) {
  Object.keys(option).forEach(hook => {
    if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
      interceptor[hook] = mergeHook(interceptor[hook], option[hook]);
    }
  });
}

function removeInterceptorHook (interceptor, option) {
  if (!interceptor || !option) {
    return
  }
  Object.keys(option).forEach(hook => {
    if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
      removeHook(interceptor[hook], option[hook]);
    }
  });
}

function addInterceptor (method, option) {
  if (typeof method === 'string' && isPlainObject(option)) {
    mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), option);
  } else if (isPlainObject(method)) {
    mergeInterceptorHook(globalInterceptors, method);
  }
}

function removeInterceptor (method, option) {
  if (typeof method === 'string') {
    if (isPlainObject(option)) {
      removeInterceptorHook(scopedInterceptors[method], option);
    } else {
      delete scopedInterceptors[method];
    }
  } else if (isPlainObject(method)) {
    removeInterceptorHook(globalInterceptors, method);
  }
}

fxy060608's avatar
fxy060608 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
function wrapperHook (hook) {
  return function (data) {
    return hook(data) || data
  }
}

function isPromise (obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}

function queue (hooks, data) {
  let promise = false;
  for (let i = 0; i < hooks.length; i++) {
    const hook = hooks[i];
    if (promise) {
      promise = Promise.then(wrapperHook(hook));
    } else {
      const res = hook(data);
      if (isPromise(res)) {
        promise = Promise.resolve(res);
      }
      if (res === false) {
        return {
          then () {}
        }
      }
    }
  }
  return promise || {
    then (callback) {
      return callback(data)
    }
  }
}

function wrapperOptions (interceptor, options = {}) {
  ['success', 'fail', 'complete'].forEach(name => {
    if (Array.isArray(interceptor[name])) {
      const oldCallback = options[name];
      options[name] = function callbackInterceptor (res) {
        queue(interceptor[name], res).then((res) => {
          /* eslint-disable no-mixed-operators */
          return isFn(oldCallback) && oldCallback(res) || res
        });
      };
    }
  });
  return options
}

function wrapperReturnValue (method, returnValue) {
  const returnValueHooks = [];
  if (Array.isArray(globalInterceptors.returnValue)) {
    returnValueHooks.push(...globalInterceptors.returnValue);
  }
  const interceptor = scopedInterceptors[method];
  if (interceptor && Array.isArray(interceptor.returnValue)) {
    returnValueHooks.push(...interceptor.returnValue);
  }
  returnValueHooks.forEach(hook => {
    returnValue = hook(returnValue) || returnValue;
  });
  return returnValue
}

function getApiInterceptorHooks (method) {
  const interceptor = Object.create(null);
  Object.keys(globalInterceptors).forEach(hook => {
    if (hook !== 'returnValue') {
      interceptor[hook] = globalInterceptors[hook].slice();
    }
  });
  const scopedInterceptor = scopedInterceptors[method];
  if (scopedInterceptor) {
    Object.keys(scopedInterceptor).forEach(hook => {
      if (hook !== 'returnValue') {
        interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
      }
    });
  }
  return interceptor
}

function invokeApi (method, api, options, ...params) {
  const interceptor = getApiInterceptorHooks(method);
  if (interceptor && Object.keys(interceptor).length) {
    if (Array.isArray(interceptor.invoke)) {
      const res = queue(interceptor.invoke, options);
      return res.then((options) => {
        return api(wrapperOptions(interceptor, options), ...params)
      })
    } else {
      return api(wrapperOptions(interceptor, options), ...params)
    }
  }
  return api(options, ...params)
fxy060608's avatar
fxy060608 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243
}

const promiseInterceptor = {
  returnValue (res) {
    if (!isPromise(res)) {
      return res
    }
    return res.then(res => {
      return res[1]
    }).catch(res => {
      return res[0]
    })
  }
};
fxy060608's avatar
fxy060608 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

const SYNC_API_RE =
    /^\$|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;

const CONTEXT_API_RE = /^create|Manager$/;

const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket'];

const CALLBACK_API_RE = /^on/;

function isContextApi (name) {
  return CONTEXT_API_RE.test(name)
}
function isSyncApi (name) {
  return SYNC_API_RE.test(name)
}

function isCallbackApi (name) {
  return CALLBACK_API_RE.test(name)
}

function isTaskApi (name) {
  return TASK_APIS.indexOf(name) !== -1
}

function handlePromise (promise) {
  return promise.then(data => {
    return [null, data]
  })
    .catch(err => [err])
}

function shouldPromise (name) {
  if (
    isContextApi(name) ||
        isSyncApi(name) ||
        isCallbackApi(name)
  ) {
    return false
  }
  return true
}

function promisify (name, api) {
  if (!shouldPromise(name)) {
    return api
  }
  return function promiseApi (options = {}, ...params) {
    if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
      return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
    }
    return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
      invokeApi(name, api, Object.assign({}, options, {
        success: resolve,
        fail: reject
      }), ...params);
      /* eslint-disable no-extend-native */
      if (!Promise.prototype.finally) {
        Promise.prototype.finally = function (callback) {
          const promise = this.constructor;
          return this.then(
            value => promise.resolve(callback()).then(() => value),
            reason => promise.resolve(callback()).then(() => {
              throw reason
            })
          )
        };
      }
    })))
  }
}

const canIUse = [{
  name: 'schema',
  type: String,
  required: true
}];

fxy060608's avatar
fxy060608 已提交
322
var require_context_module_1_0 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
  canIUse: canIUse
});

const base64ToArrayBuffer = [{
  name: 'base64',
  type: String,
  required: true
}];

const arrayBufferToBase64 = [{
  name: 'arrayBuffer',
  type: [ArrayBuffer, Uint8Array],
  required: true
}];

fxy060608's avatar
fxy060608 已提交
338
var require_context_module_1_1 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
  base64ToArrayBuffer: base64ToArrayBuffer,
  arrayBufferToBase64: arrayBufferToBase64
});

function getInt (method) {
  return function (value, params) {
    if (value) {
      params[method] = Math.round(value);
    }
  }
}

const canvasGetImageData = {
  canvasId: {
    type: String,
    required: true
  },
  x: {
    type: Number,
    required: true,
    validator: getInt('x')
  },
  y: {
    type: Number,
    required: true,
    validator: getInt('y')
  },
  width: {
    type: Number,
    required: true,
    validator: getInt('width')
  },
  height: {
    type: Number,
    required: true,
    validator: getInt('height')
  }
};

const canvasPutImageData = {
  canvasId: {
    type: String,
    required: true
  },
  data: {
    type: Uint8ClampedArray,
    required: true
  },
  x: {
    type: Number,
    required: true,
    validator: getInt('x')
  },
  y: {
    type: Number,
    required: true,
    validator: getInt('y')
  },
  width: {
    type: Number,
    required: true,
    validator: getInt('width')
  },
  height: {
    type: Number,
    validator: getInt('height')
  }
};

const fileType = {
  PNG: 'png',
  JPG: 'jpeg'
};

const canvasToTempFilePath = {
  x: {
    type: Number,
    default: 0,
    validator: getInt('x')
  },
  y: {
    type: Number,
    default: 0,
    validator: getInt('y')
  },
  width: {
    type: Number,
    validator: getInt('width')
  },
  height: {
    type: Number,
    validator: getInt('height')
  },
  destWidth: {
    type: Number,
    validator: getInt('destWidth')
  },
  destHeight: {
    type: Number,
    validator: getInt('destHeight')
  },
  canvasId: {
    type: String,
    require: true
  },
  fileType: {
    type: String,
    validator (value, params) {
      value = (value || '').toUpperCase();
      params.fileType = value in fileType ? fileType[value] : fileType.PNG;
    }
  },
  quality: {
    type: Number,
    validator (value, params) {
      value = Math.floor(value);
      params.quality = value > 0 && value < 1 ? value : 1;
    }
  }
};

const drawCanvas = {
  canvasId: {
    type: String,
    require: true
  },
  actions: {
    type: Array,
    require: true
  },
  reserve: {
    type: Boolean,
    default: false
  }
};

fxy060608's avatar
fxy060608 已提交
475
var require_context_module_1_2 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  canvasGetImageData: canvasGetImageData,
  canvasPutImageData: canvasPutImageData,
  canvasToTempFilePath: canvasToTempFilePath,
  drawCanvas: drawCanvas
});

const validator = [{
  name: 'id',
  type: String,
  required: true
}];

const createAudioContext = validator;
const createVideoContext = validator;
const createMapContext = validator;
const createCanvasContext = [{
  name: 'canvasId',
  type: String,
  required: true
}, {
  name: 'componentInstance',
  type: Object
}];

fxy060608's avatar
fxy060608 已提交
500
var require_context_module_1_3 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  createAudioContext: createAudioContext,
  createVideoContext: createVideoContext,
  createMapContext: createMapContext,
  createCanvasContext: createCanvasContext
});

const makePhoneCall = {
  'phoneNumber': {
    type: String,
    required: true,
    validator (phoneNumber) {
      if (!phoneNumber) {
        return `makePhoneCall:fail parameter error: parameter.phoneNumber should not be empty String;`
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
519
var require_context_module_1_4 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
520 521 522 523 524 525 526 527 528 529 530 531 532
  makePhoneCall: makePhoneCall
});

const openDocument = {
  filePath: {
    type: String,
    required: true
  },
  fileType: {
    type: String
  }
};

fxy060608's avatar
fxy060608 已提交
533
var require_context_module_1_5 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  openDocument: openDocument
});

const type = {
  WGS84: 'WGS84',
  GCJ02: 'GCJ02'
};
const getLocation = {
  type: {
    type: String,
    validator (value, params) {
      value = (value || '').toUpperCase();
      params.type = Object.values(type).indexOf(value) < 0 ? type.WGS84 : value;
    },
    default: type.WGS84
  },
  altitude: {
    altitude: Boolean,
    default: false
  }
};
const openLocation = {
  latitude: {
    type: Number,
    required: true
  },
  longitude: {
    type: Number,
    required: true
  },
  scale: {
    type: Number,
    validator (value, params) {
      value = Math.floor(value);
      params.scale = value >= 5 && value <= 18 ? value : 18;
    },
    default: 18
  },
  name: {
    type: String
  },
  address: {
    type: String
  }
};

fxy060608's avatar
fxy060608 已提交
580
var require_context_module_1_6 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  getLocation: getLocation,
  openLocation: openLocation
});

const SIZE_TYPES = ['original', 'compressed'];
const SOURCE_TYPES = ['album', 'camera'];

const chooseImage = {
  'count': {
    type: Number,
    required: false,
    default: 9,
    validator (count, params) {
      if (count <= 0) {
        params.count = 9;
      }
    }
  },
  'sizeType': {
    type: Array,
    required: false,
    default: SIZE_TYPES,
    validator (sizeType, params) {
      // 非必传的参数,不符合预期时处理为默认值。
      const length = sizeType.length;
      if (!length) {
        params.sizeType = SIZE_TYPES;
      } else {
        for (let i = 0; i < length; i++) {
          if (typeof sizeType[i] !== 'string' || !~SIZE_TYPES.indexOf(sizeType[i])) {
            params.sizeType = SIZE_TYPES;
            break
          }
        }
      }
    }
  },
  'sourceType': {
    type: Array,
    required: false,
    default: SOURCE_TYPES,
    validator (sourceType, params) {
      const length = sourceType.length;
      if (!length) {
        params.sourceType = SOURCE_TYPES;
      } else {
        for (let i = 0; i < length; i++) {
          if (typeof sourceType[i] !== 'string' || !~SOURCE_TYPES.indexOf(sourceType[i])) {
            params.sourceType = SOURCE_TYPES;
            break
          }
        }
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
638
var require_context_module_1_7 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  chooseImage: chooseImage
});

const SOURCE_TYPES$1 = ['album', 'camera'];

const chooseVideo = {
  'sourceType': {
    type: Array,
    required: false,
    default: SOURCE_TYPES$1,
    validator (sourceType, params) {
      const length = sourceType.length;
      if (!length) {
        params.sourceType = SOURCE_TYPES$1;
      } else {
        for (let i = 0; i < length; i++) {
          if (typeof sourceType[i] !== 'string' || !~SOURCE_TYPES$1.indexOf(sourceType[i])) {
            params.sourceType = SOURCE_TYPES$1;
            break
          }
        }
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
665
var require_context_module_1_8 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  chooseVideo: chooseVideo
});

function getRealRoute (fromRoute, toRoute) {
  if (!toRoute) {
    toRoute = fromRoute;
    if (toRoute.indexOf('/') === 0) {
      return toRoute
    }
    const pages = getCurrentPages();
    if (pages.length) {
      fromRoute = pages[pages.length - 1].$page.route;
    } else {
      fromRoute = '';
    }
  } else {
    if (toRoute.indexOf('/') === 0) {
      return toRoute
    }
  }
  if (toRoute.indexOf('./') === 0) {
    return getRealRoute(fromRoute, toRoute.substr(2))
  }
  const toRouteArray = toRoute.split('/');
  const toRouteLength = toRouteArray.length;
  let i = 0;
  for (; i < toRouteLength && toRouteArray[i] === '..'; i++) {
    // noop
  }
  toRouteArray.splice(0, i);
  toRoute = toRouteArray.join('/');
  const fromRouteArray = fromRoute.length > 0 ? fromRoute.split('/') : [];
  fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
  return '/' + fromRouteArray.concat(toRouteArray).join('/')
}

const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const BASE64_RE = /^data:[a-z-]+\/[a-z-]+;base64,/;

function addBase (filePath) {
  return filePath
}

function getRealPath (filePath) {
  if (filePath.indexOf('/') === 0) {
    if (filePath.indexOf('//') === 0) {
      filePath = 'https:' + filePath;
    } else {
      return addBase(filePath.substr(1))
    }
  }
  // 网络资源或base64
  if (SCHEME_RE.test(filePath) || BASE64_RE.test(filePath) || filePath.indexOf('blob:') === 0) {
    return filePath
  }

  const pages = getCurrentPages();
  if (pages.length) {
    return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1))
  }

  return filePath
}

const getImageInfo = {
  'src': {
    type: String,
    required: true,
    validator (src, params) {
      params.src = getRealPath(src);
    }
  }
};

fxy060608's avatar
fxy060608 已提交
740
var require_context_module_1_9 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
  getImageInfo: getImageInfo
});

const previewImage = {
  urls: {
    type: Array,
    required: true,
    validator (value, params) {
      var typeError;
      params.urls = value.map(url => {
        if (typeof url === 'string') {
          return getRealPath(url)
        } else {
          typeError = true;
        }
      });
      if (typeError) {
        return 'url is not string'
      }
    }
  },
  current: {
    type: [String, Number],
    validator (value, params) {
      if (typeof value === 'number') {
        params.current = value > 0 && value < params.urls.length ? value : 0;
      } else if (typeof value === 'string' && value) {
        params.current = getRealPath(value);
      }
    },
    default: 0
  }
};

fxy060608's avatar
fxy060608 已提交
775
var require_context_module_1_10 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  previewImage: previewImage
});

const FRONT_COLORS = ['#ffffff', '#000000'];
const setNavigationBarColor = {
  'frontColor': {
    type: String,
    required: true,
    validator (frontColor, params) {
      if (FRONT_COLORS.indexOf(frontColor) === -1) {
        return `invalid frontColor "${frontColor}"`
      }
    }
  },
  'backgroundColor': {
    type: String,
    required: true
  },
  'animation': {
    type: Object,
    default () {
      return {
        duration: 0,
        timingFunc: 'linear'
      }
    },
    validator (animation = {}, params) {
      params.animation = {
        duration: animation.duration || 0,
        timingFunc: animation.timingFunc || 'linear'
      };
    }
  }
};
const setNavigationBarTitle = {
  'title': {
    type: String,
    required: true
  }
};

fxy060608's avatar
fxy060608 已提交
817
var require_context_module_1_11 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  setNavigationBarColor: setNavigationBarColor,
  setNavigationBarTitle: setNavigationBarTitle
});

const downloadFile = {
  url: {
    type: String,
    required: true
  },
  header: {
    type: Object,
    validator (value, params) {
      params.header = value || {};
    }
  }
};

fxy060608's avatar
fxy060608 已提交
835
var require_context_module_1_12 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
  downloadFile: downloadFile
});

const method = {
  OPTIONS: 'OPTIONS',
  GET: 'GET',
  HEAD: 'HEAD',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE',
  TRACE: 'TRACE',
  CONNECT: 'CONNECT'
};
const dataType = {
  JSON: 'JSON'
};
const responseType = {
  TEXT: 'TEXT',
  ARRAYBUFFER: 'ARRAYBUFFER'
};
const request = {
  url: {
    type: String,
    required: true
  },
  data: {
    type: [Object, String, ArrayBuffer],
    validator (value, params) {
      params.data = value || '';
    }
  },
  header: {
    type: Object,
    validator (value, params) {
      params.header = value || {};
    }
  },
  method: {
    type: String,
    validator (value, params) {
      value = (value || '').toUpperCase();
      params.method = Object.values(method).indexOf(value) < 0 ? method.GET : value;
    }
  },
  dataType: {
    type: String,
    validator (value, params) {
      params.dataType = (value || dataType.JSON).toUpperCase();
    }
  },
  responseType: {
    type: String,
    validator (value, params) {
      value = (value || '').toUpperCase();
      params.responseType = Object.values(responseType).indexOf(value) < 0 ? responseType.TEXT : value;
    }
  }
};

fxy060608's avatar
fxy060608 已提交
895
var require_context_module_1_13 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
  request: request
});

const method$1 = {
  OPTIONS: 'OPTIONS',
  GET: 'GET',
  HEAD: 'HEAD',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE',
  TRACE: 'TRACE',
  CONNECT: 'CONNECT'
};
const connectSocket = {
  url: {
    type: String,
    required: true
  },
  header: {
    type: Object,
    validator (value, params) {
      params.header = value || {};
    }
  },
  method: {
    type: String,
    validator (value, params) {
      value = (value || '').toUpperCase();
      params.method = Object.values(method$1).indexOf(value) < 0 ? method$1.GET : value;
    }
  },
  protocols: {
    type: Array,
    validator (value, params) {
      params.protocols = (value || []).filter(str => typeof str === 'string');
    }
  }
};
const sendSocketMessage = {
  data: {
    type: [String, ArrayBuffer]
  }
};
const closeSocket = {
  code: {
    type: Number
  },
  reason: {
    type: String
  }
};

fxy060608's avatar
fxy060608 已提交
948
var require_context_module_1_14 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
  connectSocket: connectSocket,
  sendSocketMessage: sendSocketMessage,
  closeSocket: closeSocket
});

const uploadFile = {
  url: {
    type: String,
    required: true
  },
  filePath: {
    type: String,
    required: true,
    validator (value, params) {
      params.type = getRealPath(value);
    }
  },
  name: {
    type: String,
    required: true
  },
  header: {
    type: Object,
    validator (value, params) {
      params.header = value || {};
    }
  },
  formData: {
    type: Object,
    validator (value, params) {
      params.formData = value || {};
    }
  }
};

fxy060608's avatar
fxy060608 已提交
984
var require_context_module_1_15 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  uploadFile: uploadFile
});

const pageScrollTo = {
  scrollTop: {
    type: Number,
    required: true
  },
  duration: {
    type: Number,
    default: 300,
    validator (duration, params) {
      params.duration = Math.max(0, duration);
    }
  }
};

fxy060608's avatar
fxy060608 已提交
1002
var require_context_module_1_16 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  pageScrollTo: pageScrollTo
});

const service = {
  OAUTH: 'OAUTH',
  SHARE: 'SHARE',
  PAYMENT: 'PAYMENT',
  PUSH: 'PUSH'
};

const getProvider = {
  service: {
    type: String,
    required: true,
    validator (value, params) {
      value = (value || '').toUpperCase();
      if (value && Object.values(service).indexOf(value) < 0) {
        return 'service error'
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
1026
var require_context_module_1_17 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  getProvider: getProvider
});

const showModal = {
  title: {
    type: String,
    default: ''
  },
  content: {
    type: String,
    default: ''
  },
  showCancel: {
    type: Boolean,
    default: true
  },
  cancelText: {
    type: String,
    default: '取消'
  },
  cancelColor: {
    type: String,
    default: '#000000'
  },
  confirmText: {
    type: String,
    default: '确定'
  },
  confirmColor: {
    type: String,
    default: '#007aff'
  },
  visible: {
    type: Boolean,
    default: true
  }
};

const showToast = {
  title: {
    type: String,
    default: ''
  },
  icon: {
    default: 'success',
    validator (icon, params) {
      if (['success', 'loading', 'none'].indexOf(icon) === -1) {
        params.icon = 'success';
      }
    }
  },
  image: {
    type: String,
    default: '',
    validator (image, params) {
      if (image) {
        params.image = getRealPath(image);
      }
    }
  },
  duration: {
    type: Number,
    default: 1500
  },
  mask: {
    type: Boolean,
    default: false
  },
  visible: {
    type: Boolean,
    default: true
  }
};
const showLoading = {
  title: {
    type: String,
    default: ''
  },
  icon: {
    type: String,
    default: 'loading'
  },
  duration: {
    type: Number,
    default: 100000000 // 简单处理 showLoading,直接设置个大值
  },
  mask: {
    type: Boolean,
    default: false
  },
  visible: {
    type: Boolean,
    default: true
  }
};

const showActionSheet = {
  itemList: {
    type: Array,
    required: true,
    validator (itemList, params) {
      if (!itemList.length) {
        return 'parameter.itemList should have at least 1 item'
      }
    }
  },
  itemColor: {
    type: String,
    default: '#000000'
  },
  visible: {
    type: Boolean,
    default: true
  }
};

fxy060608's avatar
fxy060608 已提交
1143
var require_context_module_1_18 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
  showModal: showModal,
  showToast: showToast,
  showLoading: showLoading,
  showActionSheet: showActionSheet
});

function encodeQueryString (url) {
  if (typeof url !== 'string') {
    return url
  }
  const index = url.indexOf('?');

  if (index === -1) {
    return url
  }

  const query = url.substr(index + 1).trim().replace(/^(\?|#|&)/, '');

  if (!query) {
    return url
  }

  url = url.substr(0, index);

  const params = [];

  query.split('&').forEach(param => {
    const parts = param.replace(/\+/g, ' ').split('=');
    const key = parts.shift();
    const val = parts.length > 0
      ? parts.join('=')
      : '';

    params.push(key + '=' + encodeURIComponent(val));
  });

  return params.length ? url + '?' + params.join('&') : url
}

function createValidator (type) {
  return function validator (url, params) {
    // 格式化为绝对路径路由
    url = getRealRoute(url);

    const pagePath = url.split('?')[0];
    // 匹配路由是否存在
    const routeOptions = __uniRoutes.find(({
      path,
      alias
    }) => path === pagePath || alias === pagePath);

    if (!routeOptions) {
      return 'page `' + url + '` is not found'
    }

    // 检测不同类型跳转
    if (type === 'navigateTo' || type === 'redirectTo') {
      if (routeOptions.meta.isTabBar) {
        return `can not ${type} a tabbar page`
      }
    } else if (type === 'switchTab') {
      if (!routeOptions.meta.isTabBar) {
        return 'can not switch to no-tabBar page'
      }
    }

    // tabBar不允许传递参数
    if (routeOptions.meta.isTabBar) {
      url = pagePath;
    }

    // 首页自动格式化为`/`
    if (routeOptions.meta.isEntry) {
      url = url.replace(routeOptions.alias, '/');
    }

    // 参数格式化
    params.url = encodeQueryString(url);
  }
}

fxy060608's avatar
fxy060608 已提交
1225 1226
function createProtocol (type, extras = {}) {
  return Object.assign({
fxy060608's avatar
fxy060608 已提交
1227 1228 1229 1230 1231
    url: {
      type: String,
      required: true,
      validator: createValidator(type)
    }
fxy060608's avatar
fxy060608 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  }, extras)
}

function createAnimationProtocol (animationTypes) {
  return {
    animationType: {
      type: String,
      validator (type) {
        if (type && animationTypes.indexOf(type) === -1) {
          return '`' + type + '` is not supported for `animationType` (supported values are: `' + animationTypes.join(
            '`|`') + '`)'
        }
      }
    },
    animationDuration: {
      type: Number
    }
fxy060608's avatar
fxy060608 已提交
1249 1250
  }
}
fxy060608's avatar
fxy060608 已提交
1251

fxy060608's avatar
fxy060608 已提交
1252 1253 1254 1255
const redirectTo = createProtocol('redirectTo');

const reLaunch = createProtocol('reLaunch');

fxy060608's avatar
fxy060608 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
const navigateTo = createProtocol('navigateTo', createAnimationProtocol(
  [
    'slide-in-right',
    'slide-in-left',
    'slide-in-top',
    'slide-in-bottom',
    'fade-in',
    'zoom-out',
    'zoom-fade-out',
    'pop-in',
    'none'
  ]
));
fxy060608's avatar
fxy060608 已提交
1269 1270 1271

const switchTab = createProtocol('switchTab');

fxy060608's avatar
fxy060608 已提交
1272
const navigateBack = Object.assign({
fxy060608's avatar
fxy060608 已提交
1273 1274 1275 1276 1277 1278 1279
  delta: {
    type: Number,
    validator (delta, params) {
      delta = parseInt(delta) || 1;
      params.delta = Math.min(getCurrentPages().length - 1, delta);
    }
  }
fxy060608's avatar
fxy060608 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
}, createAnimationProtocol(
  [
    'slide-out-right',
    'slide-out-left',
    'slide-out-top',
    'slide-out-bottom',
    'fade-out',
    'zoom-in',
    'zoom-fade-in',
    'pop-out',
    'none'
  ]
));
fxy060608's avatar
fxy060608 已提交
1293

fxy060608's avatar
fxy060608 已提交
1294
var require_context_module_1_19 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  redirectTo: redirectTo,
  reLaunch: reLaunch,
  navigateTo: navigateTo,
  switchTab: switchTab,
  navigateBack: navigateBack
});

const setStorage = {
  'key': {
    type: String,
    required: true
  },
  'data': {
    required: true
  }
};

const setStorageSync = [{
  name: 'key',
  type: String,
  required: true
}, {
  name: 'data',
  required: true
}];

fxy060608's avatar
fxy060608 已提交
1321
var require_context_module_1_20 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
  setStorage: setStorage,
  setStorageSync: setStorageSync
});

const indexValidator = {
  type: Number,
  required: true
};

const setTabBarItem = {
  index: indexValidator,
  text: {
    type: String
  },
  iconPath: {
    type: String
  },
  selectedIconPath: {
    type: String
  }
};

const setTabBarStyle = {
  color: {
    type: String
  },
  selectedColor: {
    type: String
  },
  backgroundColor: {
    type: String
  },
  borderStyle: {
    type: String,
    validator (borderStyle, params) {
      if (borderStyle) {
        params.borderStyle = borderStyle === 'black' ? 'black' : 'white';
      }
    }
  }
};

const hideTabBar = {
  animation: {
    type: Boolean,
    default: false
  }
};

const showTabBar = {
  animation: {
    type: Boolean,
    default: false
  }
};

const hideTabBarRedDot = {
  index: indexValidator
};

const showTabBarRedDot = {
  index: indexValidator
};

const removeTabBarBadge = {
  index: indexValidator
};

const setTabBarBadge = {
  index: indexValidator,
  text: {
    type: String,
    required: true,
    validator (text, params) {
      if (getLen(text) >= 4) {
        params.text = '...';
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
1403
var require_context_module_1_21 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
  setTabBarItem: setTabBarItem,
  setTabBarStyle: setTabBarStyle,
  hideTabBar: hideTabBar,
  showTabBar: showTabBar,
  hideTabBarRedDot: hideTabBarRedDot,
  showTabBarRedDot: showTabBarRedDot,
  removeTabBarBadge: removeTabBarBadge,
  setTabBarBadge: setTabBarBadge
});

const protocol = Object.create(null);
const modules = 
  (function() {
    var map = {
fxy060608's avatar
fxy060608 已提交
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
      './base.js': require_context_module_1_0,
'./base64.js': require_context_module_1_1,
'./canvas.js': require_context_module_1_2,
'./context.js': require_context_module_1_3,
'./device/make-phone-call.js': require_context_module_1_4,
'./file/open-document.js': require_context_module_1_5,
'./location.js': require_context_module_1_6,
'./media/choose-image.js': require_context_module_1_7,
'./media/choose-video.js': require_context_module_1_8,
'./media/get-image-info.js': require_context_module_1_9,
'./media/preview-image.js': require_context_module_1_10,
'./navigation-bar.js': require_context_module_1_11,
'./network/download-file.js': require_context_module_1_12,
'./network/request.js': require_context_module_1_13,
'./network/socket.js': require_context_module_1_14,
'./network/upload-file.js': require_context_module_1_15,
'./page-scroll-to.js': require_context_module_1_16,
'./plugins.js': require_context_module_1_17,
'./popup.js': require_context_module_1_18,
'./route.js': require_context_module_1_19,
'./storage.js': require_context_module_1_20,
'./tab-bar.js': require_context_module_1_21,
fxy060608's avatar
fxy060608 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858

    };
    var req = function req(key) {
      return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
    };
    req.keys = function() {
      return Object.keys(map);
    };
    return req;
  })();

modules.keys().forEach(function (key) {
  Object.assign(protocol, modules(key));
});

function validateParam (key, paramTypes, paramsData) {
  const paramOptions = paramTypes[key];
  const absent = !hasOwn(paramsData, key);
  let value = paramsData[key];

  const booleanIndex = getTypeIndex(Boolean, paramOptions.type);
  if (booleanIndex > -1) {
    if (absent && !hasOwn(paramOptions, 'default')) {
      value = false;
    }
  }
  if (value === undefined) {
    if (hasOwn(paramOptions, 'default')) {
      const paramDefault = paramOptions['default'];
      value = isFn(paramDefault) ? paramDefault() : paramDefault;
      paramsData[key] = value; // 默认值
    }
  }

  return assertParam(paramOptions, key, value, absent, paramsData)
}

function assertParam (
  paramOptions,
  name,
  value,
  absent,
  paramsData
) {
  if (paramOptions.required && absent) {
    return `Missing required parameter \`${name}\``
  }

  if (value == null && !paramOptions.required) {
    const validator = paramOptions.validator;
    if (validator) {
      return validator(value, paramsData)
    }
    return
  }
  let type = paramOptions.type;
  let valid = !type || type === true;
  const expectedTypes = [];
  if (type) {
    if (!Array.isArray(type)) {
      type = [type];
    }
    for (let i = 0; i < type.length && !valid; i++) {
      const assertedType = assertType(value, type[i]);
      expectedTypes.push(assertedType.expectedType || '');
      valid = assertedType.valid;
    }
  }

  if (!valid) {
    return getInvalidTypeMessage(name, value, expectedTypes)
  }

  const validator = paramOptions.validator;
  if (validator) {
    return validator(value, paramsData)
  }
}

const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;

function assertType (value, type) {
  let valid;
  const expectedType = getType(type);
  if (simpleCheckRE.test(expectedType)) {
    const t = typeof value;
    valid = t === expectedType.toLowerCase();
    if (!valid && t === 'object') {
      valid = value instanceof type;
    }
  } else if (expectedType === 'Object') {
    valid = isPlainObject(value);
  } else if (expectedType === 'Array') {
    valid = Array.isArray(value);
  } else {
    valid = value instanceof type;
  }
  return {
    valid,
    expectedType
  }
}

function getType (fn) {
  const match = fn && fn.toString().match(/^\s*function (\w+)/);
  return match ? match[1] : ''
}

function isSameType (a, b) {
  return getType(a) === getType(b)
}

function getTypeIndex (type, expectedTypes) {
  if (!Array.isArray(expectedTypes)) {
    return isSameType(expectedTypes, type) ? 0 : -1
  }
  for (let i = 0, len = expectedTypes.length; i < len; i++) {
    if (isSameType(expectedTypes[i], type)) {
      return i
    }
  }
  return -1
}

function getInvalidTypeMessage (name, value, expectedTypes) {
  let message = `parameter \`${name}\`.` +
		` Expected ${expectedTypes.join(', ')}`;
  const expectedType = expectedTypes[0];
  const receivedType = toRawType(value);
  const expectedValue = styleValue(value, expectedType);
  const receivedValue = styleValue(value, receivedType);
  if (expectedTypes.length === 1 &&
		isExplicable(expectedType) &&
		!isBoolean(expectedType, receivedType)) {
    message += ` with value ${expectedValue}`;
  }
  message += `, got ${receivedType} `;
  if (isExplicable(receivedType)) {
    message += `with value ${receivedValue}.`;
  }
  return message
}

function styleValue (value, type) {
  if (type === 'String') {
    return `"${value}"`
  } else if (type === 'Number') {
    return `${Number(value)}`
  } else {
    return `${value}`
  }
}

const explicitTypes = ['string', 'number', 'boolean'];

function isExplicable (value) {
  return explicitTypes.some(elem => value.toLowerCase() === elem)
}

function isBoolean (...args) {
  return args.some(elem => elem.toLowerCase() === 'boolean')
}

function invokeCallbackHandlerFail (err, apiName, callbackId) {
  const errMsg = `${apiName}:fail ${err}`;
  console.error(errMsg);
  if (callbackId === -1) {
    throw new Error(errMsg)
  }
  if (typeof callbackId === 'number') {
    invokeCallbackHandler(callbackId, {
      errMsg
    });
  }
  return false
}

const callbackApiParamTypes = [{
  name: 'callback',
  type: Function,
  required: true
}];

function validateParams (apiName, paramsData, callbackId) {
  let paramTypes = protocol[apiName];
  if (!paramTypes && isCallbackApi(apiName)) {
    paramTypes = callbackApiParamTypes;
  }
  if (paramTypes) {
    if (Array.isArray(paramTypes) && Array.isArray(paramsData)) {
      const paramTypeObj = Object.create(null);
      const paramsDataObj = Object.create(null);
      const paramsDataLength = paramsData.length;
      paramTypes.forEach((paramType, index) => {
        paramTypeObj[paramType.name] = paramType;
        if (paramsDataLength > index) {
          paramsDataObj[paramType.name] = paramsData[index];
        }
      });
      paramTypes = paramTypeObj;
      paramsData = paramsDataObj;
    }

    if (isFn(paramTypes.beforeValidate)) {
      const err = paramTypes.beforeValidate(paramsData);
      if (err) {
        return invokeCallbackHandlerFail(err, apiName, callbackId)
      }
    }

    const keys = Object.keys(paramTypes);
    for (let i = 0; i < keys.length; i++) {
      if (keys[i] === 'beforeValidate') {
        continue
      }
      const err = validateParam(keys[i], paramTypes, paramsData);
      if (err) {
        return invokeCallbackHandlerFail(err, apiName, callbackId)
      }
    }
  }
  return true
}

let invokeCallbackId = 1;

const invokeCallbacks = {};

function createKeepAliveApiCallback (apiName, callback) {
  const callbackId = invokeCallbackId++;
  const invokeCallbackName = 'api.' + apiName + '.' + callbackId;

  const invokeCallback = function (res) {
    callback(res);
  };

  invokeCallbacks[callbackId] = {
    name: invokeCallbackName,
    keepAlive: true,
    callback: invokeCallback
  };
  return callbackId
}

function createApiCallback (apiName, params = {}, extras = {}) {
  if (!isPlainObject(params)) {
    return {
      params
    }
  }
  params = Object.assign({}, params);

  const apiCallbacks = {};
  for (let name in params) {
    const param = params[name];
    if (isFn(param)) {
      apiCallbacks[name] = tryCatch(param);
      delete params[name];
    }
  }

  const {
    success,
    fail,
    cancel,
    complete
  } = apiCallbacks;

  const hasSuccess = isFn(success);
  const hasFail = isFn(fail);
  const hasCancel = isFn(cancel);
  const hasComplete = isFn(complete);

  if (!hasSuccess && !hasFail && !hasCancel && !hasComplete) { // 无回调
    return {
      params
    }
  }

  const wrapperCallbacks = {};
  for (let name in extras) {
    const extra = extras[name];
    if (isFn(extra)) {
      wrapperCallbacks[name] = tryCatchFramework(extra);
      delete extras[name];
    }
  }

  const {
    beforeSuccess,
    afterSuccess,
    beforeFail,
    afterFail,
    beforeCancel,
    afterCancel,
    afterAll
  } = wrapperCallbacks;

  const callbackId = invokeCallbackId++;
  const invokeCallbackName = 'api.' + apiName + '.' + callbackId;

  const invokeCallback = function (res) {
    res.errMsg = res.errMsg || apiName + ':ok';

    const errMsg = res.errMsg;

    if (errMsg.indexOf(apiName + ':ok') === 0) {
      isFn(beforeSuccess) && beforeSuccess(res);

      hasSuccess && success(res);

      isFn(afterSuccess) && afterSuccess(res);
    } else if (errMsg.indexOf(apiName + ':cancel') === 0) {
      res.errMsg = res.errMsg.replace(apiName + ':cancel', apiName + ':fail cancel');

      hasFail && fail(res);

      isFn(beforeCancel) && beforeCancel(res);

      hasCancel && cancel(res);

      isFn(afterCancel) && afterCancel(res);
    } else if (errMsg.indexOf(apiName + ':fail') === 0) {
      isFn(beforeFail) && beforeFail(res);

      hasFail && fail(res);

      isFn(afterFail) && afterFail(res);
    }

    hasComplete && complete(res);

    isFn(afterAll) && afterAll(res);
  };

  invokeCallbacks[callbackId] = {
    name: invokeCallbackName,
    callback: invokeCallback
  };

  return {
    params,
    callbackId
  }
}

function createInvokeCallback (apiName, params = {}, extras = {}) {
  const {
    params: args,
    callbackId
  } = createApiCallback(apiName, params, extras);

  if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
    return {
      params: args,
      callbackId: false
    }
  }

  return {
    params: args,
    callbackId
  }
}

function invokeCallbackHandler (invokeCallbackId, res) {
  if (typeof invokeCallbackId === 'number') {
    const invokeCallback = invokeCallbacks[invokeCallbackId];
    if (invokeCallback) {
      if (!invokeCallback.keepAlive) {
        delete invokeCallbacks[invokeCallbackId];
      }
      return invokeCallback.callback(res)
    }
  }
  return res
}

function wrapper (name, invokeMethod, extras) {
  if (!isFn(invokeMethod)) {
    return invokeMethod
  }
  return function (...args) {
    if (isSyncApi(name)) {
      if (validateParams(name, args, -1)) {
        return invokeMethod.apply(null, args)
      }
    } else if (isCallbackApi(name)) {
      if (validateParams(name, args, -1)) {
        return invokeMethod(createKeepAliveApiCallback(name, args[0]))
      }
    } else {
      let argsObj = {};
      if (args.length) {
        argsObj = args[0];
      }
      const {
        params,
        callbackId
      } = createInvokeCallback(name, argsObj, extras);
      if (callbackId !== false) {
        let res;
        if (isFn(params)) {
          res = invokeMethod(callbackId);
        } else {
          res = invokeMethod(params, callbackId);
        }
        if (res && !isTaskApi(name)) {
          res = invokeCallbackHandler(callbackId, res);
          if (isPlainObject(res)) {
            res.errMsg = res.errMsg || name + ':ok';
          }
        }
        return res
      }
    }
  }
}

fxy060608's avatar
fxy060608 已提交
1859
UniServiceJSBridge.publishHandler = UniServiceJSBridge.emit;
fxy060608's avatar
fxy060608 已提交
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler;

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

var base64Arraybuffer = createCommonjsModule(function (module, exports) {
/*
 * base64-arraybuffer
 * https://github.com/niklasvh/base64-arraybuffer
 *
 * Copyright (c) 2012 Niklas von Hertzen
 * Licensed under the MIT license.
 */
(function(){

  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  // Use a lookup table to find the index.
  var lookup = new Uint8Array(256);
  for (var i = 0; i < chars.length; i++) {
    lookup[chars.charCodeAt(i)] = i;
  }

  exports.encode = function(arraybuffer) {
    var bytes = new Uint8Array(arraybuffer),
    i, len = bytes.length, base64 = "";

    for (i = 0; i < len; i+=3) {
      base64 += chars[bytes[i] >> 2];
      base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
      base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
      base64 += chars[bytes[i + 2] & 63];
    }

    if ((len % 3) === 2) {
      base64 = base64.substring(0, base64.length - 1) + "=";
    } else if (len % 3 === 1) {
      base64 = base64.substring(0, base64.length - 2) + "==";
    }

    return base64;
  };

  exports.decode =  function(base64) {
    var bufferLength = base64.length * 0.75,
    len = base64.length, i, p = 0,
    encoded1, encoded2, encoded3, encoded4;

    if (base64[base64.length - 1] === "=") {
      bufferLength--;
      if (base64[base64.length - 2] === "=") {
        bufferLength--;
      }
    }

    var arraybuffer = new ArrayBuffer(bufferLength),
    bytes = new Uint8Array(arraybuffer);

    for (i = 0; i < len; i+=4) {
      encoded1 = lookup[base64.charCodeAt(i)];
      encoded2 = lookup[base64.charCodeAt(i+1)];
      encoded3 = lookup[base64.charCodeAt(i+2)];
      encoded4 = lookup[base64.charCodeAt(i+3)];

      bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
      bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
      bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
    }

    return arraybuffer;
  };
})();
});
var base64Arraybuffer_1 = base64Arraybuffer.encode;
var base64Arraybuffer_2 = base64Arraybuffer.decode;

const base64ToArrayBuffer$1 = base64Arraybuffer_2;
const arrayBufferToBase64$1 = base64Arraybuffer_1;

fxy060608's avatar
fxy060608 已提交
1940 1941 1942 1943 1944
var require_context_module_0_0 = /*#__PURE__*/Object.freeze({
  base64ToArrayBuffer: base64ToArrayBuffer$1,
  arrayBufferToBase64: arrayBufferToBase64$1
});

fxy060608's avatar
fxy060608 已提交
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
var platformSchema = {};

// TODO 待处理其他 API 的检测

function canIUse$1 (schema) {
  if (hasOwn(platformSchema, schema)) {
    return platformSchema[schema]
  }
  return true
}

fxy060608's avatar
fxy060608 已提交
1956 1957 1958 1959
var require_context_module_0_1 = /*#__PURE__*/Object.freeze({
  canIUse: canIUse$1
});

fxy060608's avatar
fxy060608 已提交
1960 1961 1962 1963
const interceptors = {
  promiseInterceptor
};

fxy060608's avatar
fxy060608 已提交
1964 1965 1966 1967 1968
var require_context_module_0_2 = /*#__PURE__*/Object.freeze({
  interceptors: interceptors,
  addInterceptor: addInterceptor,
  removeInterceptor: removeInterceptor
});
fxy060608's avatar
fxy060608 已提交
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979

function pageScrollTo$1 (args) {
  const pages = getCurrentPages();
  if (pages.length) {
    UniServiceJSBridge.publishHandler('pageScrollTo', args, pages[pages.length - 1].$page.id);
  }
  return {}
}

let pageId;

fxy060608's avatar
fxy060608 已提交
1980 1981 1982 1983
function setPullDownRefreshPageId (pullDownRefreshPageId) {
  pageId = pullDownRefreshPageId;
}

fxy060608's avatar
fxy060608 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
function startPullDownRefresh () {
  if (pageId) {
    UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
  }
  const pages = getCurrentPages();
  if (pages.length) {
    pageId = pages[pages.length - 1].$page.id;
    UniServiceJSBridge.emit(pageId + '.startPullDownRefresh', {}, pageId);
  }
  return {}
}

function stopPullDownRefresh () {
  if (pageId) {
    UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
    pageId = null;
  } else {
    const pages = getCurrentPages();
    if (pages.length) {
      pageId = pages[pages.length - 1].$page.id;
      UniServiceJSBridge.emit(pageId + '.stopPullDownRefresh', {}, pageId);
    }
  }
  return {}
}

fxy060608's avatar
fxy060608 已提交
2010 2011 2012 2013 2014 2015
var require_context_module_0_3 = /*#__PURE__*/Object.freeze({
  pageScrollTo: pageScrollTo$1,
  setPullDownRefreshPageId: setPullDownRefreshPageId,
  startPullDownRefresh: startPullDownRefresh,
  stopPullDownRefresh: stopPullDownRefresh
});
fxy060608's avatar
fxy060608 已提交
2016

fxy060608's avatar
fxy060608 已提交
2017 2018 2019 2020 2021 2022 2023 2024
function setStorage$1 ({
  key,
  data
} = {}) {
  const value = {
    type: typeof data === 'object' ? 'object' : 'string',
    data: data
  };
fxy060608's avatar
fxy060608 已提交
2025 2026
  localStorage.setItem(key, JSON.stringify(value));
  const keyList = localStorage.getItem('uni-storage-keys');
fxy060608's avatar
fxy060608 已提交
2027
  if (!keyList) {
fxy060608's avatar
fxy060608 已提交
2028
    localStorage.setItem('uni-storage-keys', JSON.stringify([key]));
fxy060608's avatar
fxy060608 已提交
2029 2030 2031 2032
  } else {
    const keys = JSON.parse(keyList);
    if (keys.indexOf(key) < 0) {
      keys.push(key);
fxy060608's avatar
fxy060608 已提交
2033
      localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
fxy060608's avatar
fxy060608 已提交
2034 2035 2036 2037
    }
  }
  return {
    errMsg: 'setStorage:ok'
fxy060608's avatar
fxy060608 已提交
2038 2039 2040
  }
}

fxy060608's avatar
fxy060608 已提交
2041 2042 2043 2044 2045 2046
function setStorageSync$1 (key, data) {
  setStorage$1({
    key,
    data
  });
}
fxy060608's avatar
fxy060608 已提交
2047

fxy060608's avatar
fxy060608 已提交
2048 2049 2050
function getStorage ({
  key
} = {}) {
fxy060608's avatar
fxy060608 已提交
2051
  const data = localStorage.getItem(key);
fxy060608's avatar
fxy060608 已提交
2052 2053 2054 2055 2056 2057
  return data ? {
    data: JSON.parse(data).data,
    errMsg: 'getStorage:ok'
  } : {
    data: '',
    errMsg: 'getStorage:fail'
fxy060608's avatar
fxy060608 已提交
2058 2059 2060
  }
}

fxy060608's avatar
fxy060608 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
function getStorageSync (key) {
  const res = getStorage({
    key
  });
  return res.data
}

function removeStorage ({
  key
} = {}) {
fxy060608's avatar
fxy060608 已提交
2071
  const keyList = localStorage.getItem('uni-storage-keys');
fxy060608's avatar
fxy060608 已提交
2072 2073 2074 2075
  if (keyList) {
    const keys = JSON.parse(keyList);
    const index = keys.indexOf(key);
    keys.splice(index, 1);
fxy060608's avatar
fxy060608 已提交
2076
    localStorage.setItem('uni-storage-keys', JSON.stringify(keys));
fxy060608's avatar
fxy060608 已提交
2077
  }
fxy060608's avatar
fxy060608 已提交
2078
  localStorage.removeItem(key);
fxy060608's avatar
fxy060608 已提交
2079 2080
  return {
    errMsg: 'removeStorage:ok'
fxy060608's avatar
fxy060608 已提交
2081
  }
fxy060608's avatar
fxy060608 已提交
2082
}
fxy060608's avatar
fxy060608 已提交
2083

fxy060608's avatar
fxy060608 已提交
2084 2085 2086 2087 2088
function removeStorageSync (key) {
  removeStorage({
    key
  });
}
fxy060608's avatar
fxy060608 已提交
2089

fxy060608's avatar
fxy060608 已提交
2090
function clearStorage () {
fxy060608's avatar
fxy060608 已提交
2091
  localStorage.clear();
fxy060608's avatar
fxy060608 已提交
2092 2093
  return {
    errMsg: 'clearStorage:ok'
fxy060608's avatar
fxy060608 已提交
2094
  }
fxy060608's avatar
fxy060608 已提交
2095
}
fxy060608's avatar
fxy060608 已提交
2096

fxy060608's avatar
fxy060608 已提交
2097 2098
function clearStorageSync () {
  clearStorage();
fxy060608's avatar
fxy060608 已提交
2099 2100
}

fxy060608's avatar
fxy060608 已提交
2101
function getStorageInfo () { // TODO 暂时先不做大小的转换
fxy060608's avatar
fxy060608 已提交
2102
  const keyList = localStorage.getItem('uni-storage-keys');
fxy060608's avatar
fxy060608 已提交
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
  return keyList ? {
    keys: JSON.parse(keyList),
    currentSize: 0,
    limitSize: 0,
    errMsg: 'getStorageInfo:ok'
  } : {
    keys: '',
    currentSize: 0,
    limitSize: 0,
    errMsg: 'getStorageInfo:fail'
  }
fxy060608's avatar
fxy060608 已提交
2114 2115
}

fxy060608's avatar
fxy060608 已提交
2116 2117 2118 2119 2120 2121
function getStorageInfoSync () {
  const res = getStorageInfo();
  delete res.errMsg;
  return res
}

fxy060608's avatar
fxy060608 已提交
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
var require_context_module_0_4 = /*#__PURE__*/Object.freeze({
  setStorage: setStorage$1,
  setStorageSync: setStorageSync$1,
  getStorage: getStorage,
  getStorageSync: getStorageSync,
  removeStorage: removeStorage,
  removeStorageSync: removeStorageSync,
  clearStorage: clearStorage,
  clearStorageSync: clearStorageSync,
  getStorageInfo: getStorageInfo,
  getStorageInfoSync: getStorageInfoSync
});

fxy060608's avatar
fxy060608 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS = false;
let deviceWidth = 0;
let deviceDPR = 0;

function checkDeviceWidth () {
  const {
    platform,
    pixelRatio,
    windowWidth
  } = uni.getSystemInfoSync();

  deviceWidth = windowWidth;
  deviceDPR = pixelRatio;
  isIOS = platform === 'ios';
fxy060608's avatar
fxy060608 已提交
2151 2152
}

fxy060608's avatar
fxy060608 已提交
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
function upx2px (number, newDeviceWidth) {
  if (deviceWidth === 0) {
    checkDeviceWidth();
  }

  number = Number(number);
  if (number === 0) {
    return 0
  }
  let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
  if (result < 0) {
    result = -result;
  }
  result = Math.floor(result + EPS);
  if (result === 0) {
    if (deviceDPR === 1 || !isIOS) {
      return 1
    } else {
      return 0.5
    }
  }
  return number < 0 ? -result : result
fxy060608's avatar
fxy060608 已提交
2175 2176
}

fxy060608's avatar
fxy060608 已提交
2177
var require_context_module_0_5 = /*#__PURE__*/Object.freeze({
fxy060608's avatar
fxy060608 已提交
2178 2179
  checkDeviceWidth: checkDeviceWidth,
  upx2px: upx2px
fxy060608's avatar
fxy060608 已提交
2180 2181
});

fxy060608's avatar
fxy060608 已提交
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
const api = Object.create(null);
const modules$1 = 
  (function() {
    var map = {
      './base64.js': require_context_module_0_0,
'./can-i-use.js': require_context_module_0_1,
'./interceptor.js': require_context_module_0_2,
'./page-event.js': require_context_module_0_3,
'./storage.js': require_context_module_0_4,
'./upx2px.js': require_context_module_0_5,

    };
    var req = function req(key) {
      return map[key] || (function() { throw new Error("Cannot find module '" + key + "'.") }());
    };
    req.keys = function() {
      return Object.keys(map);
    };
    return req;
  })();

modules$1.keys().forEach(function (key) {
  Object.assign(api, modules$1(key));
});

fxy060608's avatar
fxy060608 已提交
2207 2208 2209 2210 2211 2212 2213 2214
const uni$1 = Object.create(null);

Object.keys(api).forEach(name => {
  uni$1[name] = promisify(name, wrapper(name, api[name]));
});

  return uni$1 
}