/.test(line)) {
+ matchingLines.push(line)
+ }
+ }
+ }
+ content = matchingLines.join('\n...\n')
+ const result = {
+ name: pageName,
+ url: `/learn/${pagePath}${pageSlug}${sectionUnderscored}`,
+ content,
+ }
+ return result
+ }
+
+ var updateHits = (hits, hitsTotal = 0) => {
+ $scope.safeApply(() => {
+ $scope.hits = hits
+ $scope.hits_total = hitsTotal
+ })
+ }
+
+ $scope.search = function () {
+ $scope.processingSearch = true
+ const query = $scope.searchQueryText
+ if (!query || query.length === 0) {
+ updateHits([])
+ return
+ }
+
+ algoliaSearch.searchWiki(
+ query,
+ {
+ hitsPerPage: $scope.config_hits_per_page,
+ },
+ function (err, response) {
+ $scope.processingSearch = false
+ if (response.hits.length === 0) {
+ updateHits([])
+ } else {
+ const hits = _.map(response.hits, buildHitViewModel)
+ updateHits(hits, response.nbHits)
+ }
+ }
+ )
+ }
+ }
+)
+
+export default App.controller('LearnController', function () {})
diff --git a/services/web/frontend/js/main/new-subscription.js b/services/web/frontend/js/main/new-subscription.js
new file mode 100644
index 0000000000..07f481e70a
--- /dev/null
+++ b/services/web/frontend/js/main/new-subscription.js
@@ -0,0 +1,686 @@
+import _ from 'lodash'
+/* eslint-disable
+ camelcase,
+ max-len,
+ no-return-assign
+*/
+/* global recurly */
+import App from '../base'
+import getMeta from '../utils/meta'
+
+export default App.controller(
+ 'NewSubscriptionController',
+ function ($scope, MultiCurrencyPricing, $http, $location, eventTracking) {
+ window.couponCode = $location.search().cc || ''
+ window.plan_code = $location.search().planCode || ''
+ window.ITMCampaign = $location.search().itm_campaign || ''
+ window.ITMContent = $location.search().itm_content || ''
+
+ if (typeof recurly === 'undefined' || !recurly) {
+ $scope.recurlyLoadError = true
+ return
+ }
+
+ $scope.ui = {
+ addCompanyDetails: false,
+ }
+
+ $scope.recurlyLoadError = false
+ $scope.currencyCode = MultiCurrencyPricing.currencyCode
+ $scope.allCurrencies = MultiCurrencyPricing.plans
+ $scope.availableCurrencies = {}
+ $scope.planCode = window.plan_code
+
+ $scope.switchToStudent = function () {
+ const currentPlanCode = window.plan_code
+ const planCode = currentPlanCode.replace('collaborator', 'student')
+ eventTracking.sendMB('payment-page-switch-to-student', {
+ plan: window.plan_code,
+ })
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-form-switch-to-student',
+ window.plan_code
+ )
+ window.location = `/user/subscription/new?planCode=${planCode}¤cy=${$scope.currencyCode}&cc=${$scope.data.coupon}&itm_campaign=${window.ITMCampaign}&itm_content=${window.ITMContent}`
+ }
+
+ eventTracking.sendMB('payment-page-view', { plan: window.plan_code })
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-form-viewed',
+ window.plan_code
+ )
+
+ $scope.paymentMethod = { value: 'credit_card' }
+
+ $scope.data = {
+ first_name: '',
+ last_name: '',
+ postal_code: '',
+ address1: '',
+ address2: '',
+ state: '',
+ city: '',
+ company: '',
+ vat_number: '',
+ country: getMeta('ol-countryCode'),
+ coupon: window.couponCode,
+ }
+
+ $scope.validation = {}
+
+ $scope.processing = false
+
+ $scope.threeDSecureFlow = false
+ $scope.threeDSecureContainer = document.querySelector(
+ '.three-d-secure-container'
+ )
+ $scope.threeDSecureRecurlyContainer = document.querySelector(
+ '.three-d-secure-recurly-container'
+ )
+
+ recurly.configure({
+ publicKey: getMeta('ol-recurlyApiKey'),
+ style: {
+ all: {
+ fontFamily: '"Open Sans", sans-serif',
+ fontSize: '16px',
+ fontColor: '#7a7a7a',
+ },
+ month: {
+ placeholder: 'MM',
+ },
+ year: {
+ placeholder: 'YY',
+ },
+ cvv: {
+ placeholder: 'CVV',
+ },
+ },
+ })
+
+ const pricing = recurly.Pricing()
+ window.pricing = pricing
+
+ function setupPricing() {
+ pricing
+ .plan(window.plan_code, { quantity: 1 })
+ .address({
+ country: $scope.data.country,
+ })
+ .tax({ tax_code: 'digital', vat_number: '' })
+ .currency($scope.currencyCode)
+ .coupon($scope.data.coupon)
+ .catch(function (err) {
+ if (
+ $scope.currencyCode !== 'USD' &&
+ err.name === 'invalid-currency'
+ ) {
+ $scope.currencyCode = 'USD'
+ setupPricing()
+ } else if (err.name === 'api-error' && err.code === 'not-found') {
+ // not-found here should refer to the coupon code, plan_code should be valid
+ $scope.$applyAsync(() => {
+ $scope.couponError = 'Coupon code is not valid for selected plan'
+ })
+ } else {
+ // Bail out on other errors, form state will not be correct
+ $scope.$applyAsync(() => {
+ $scope.recurlyLoadError = true
+ })
+ throw err
+ }
+ })
+ .done()
+ }
+ setupPricing()
+
+ pricing.on('change', () => {
+ $scope.planName = pricing.items.plan.name
+
+ if (pricing.items.plan.trial) {
+ $scope.trialLength = pricing.items.plan.trial.length
+ }
+
+ $scope.price = $scope.trialLength ? pricing.price.next : pricing.price.now
+ $scope.taxes = pricing.price.taxes
+ $scope.monthlyBilling = pricing.items.plan.period.length === 1
+
+ $scope.availableCurrencies = {}
+ for (const currencyCode in pricing.items.plan.price) {
+ if (MultiCurrencyPricing.plans[currencyCode]) {
+ $scope.availableCurrencies[currencyCode] =
+ MultiCurrencyPricing.plans[currencyCode]
+ }
+ }
+
+ if (
+ pricing.items &&
+ pricing.items.coupon &&
+ pricing.items.coupon.discount &&
+ pricing.items.coupon.discount.type === 'percent'
+ ) {
+ const basePrice = parseInt(pricing.price.base.plan.unit, 10)
+ $scope.coupon = {
+ singleUse: pricing.items.coupon.single_use,
+ normalPrice: basePrice,
+ }
+ if (
+ pricing.items.coupon.applies_for_months > 0 &&
+ pricing.items.coupon.discount.rate &&
+ pricing.items.coupon.applies_for_months
+ ) {
+ $scope.coupon.discountMonths = pricing.items.coupon.applies_for_months
+ $scope.coupon.discountRate = pricing.items.coupon.discount.rate * 100
+ }
+
+ if (pricing.price.taxes[0] && pricing.price.taxes[0].rate) {
+ $scope.coupon.normalPrice += basePrice * pricing.price.taxes[0].rate
+ }
+ } else {
+ $scope.coupon = null
+ }
+ $scope.$apply()
+ })
+
+ $scope.applyCoupon = () => {
+ $scope.couponError = ''
+ pricing
+ .coupon($scope.data.coupon)
+ .catch(err => {
+ if (err.name === 'api-error' && err.code === 'not-found') {
+ $scope.$applyAsync(() => {
+ $scope.couponError = 'Coupon code is not valid for selected plan'
+ })
+ } else {
+ $scope.$applyAsync(() => {
+ $scope.couponError =
+ 'An error occured when verifying the coupon code'
+ })
+ throw err
+ }
+ })
+ .done()
+ }
+
+ $scope.applyVatNumber = () =>
+ pricing
+ .tax({ tax_code: 'digital', vat_number: $scope.data.vat_number })
+ .done()
+
+ $scope.changeCurrency = function (newCurrency) {
+ $scope.currencyCode = newCurrency
+ return pricing
+ .currency(newCurrency)
+ .catch(function (err) {
+ if (
+ $scope.currencyCode !== 'USD' &&
+ err.name === 'invalid-currency'
+ ) {
+ $scope.changeCurrency('USD')
+ } else {
+ throw err
+ }
+ })
+ .done()
+ }
+
+ $scope.inputHasError = function (formItem) {
+ if (formItem == null) {
+ return false
+ }
+
+ return formItem.$touched && formItem.$invalid
+ }
+
+ $scope.isFormValid = function (form) {
+ if ($scope.paymentMethod.value === 'paypal') {
+ return $scope.data.country !== ''
+ } else {
+ return form.$valid
+ }
+ }
+
+ $scope.updateCountry = () =>
+ pricing.address({ country: $scope.data.country }).done()
+
+ $scope.setPaymentMethod = function (method) {
+ $scope.paymentMethod.value = method
+ $scope.validation.errorFields = {}
+ $scope.genericError = ''
+ }
+
+ let cachedRecurlyBillingToken
+ const completeSubscription = function (
+ err,
+ recurlyBillingToken,
+ recurly3DSecureResultToken
+ ) {
+ if (recurlyBillingToken) {
+ // temporary store the billing token as it might be needed when
+ // re-sending the request after SCA authentication
+ cachedRecurlyBillingToken = recurlyBillingToken
+ }
+ $scope.validation.errorFields = {}
+ if (err != null) {
+ eventTracking.sendMB('payment-page-form-error', err)
+ eventTracking.send('subscription-funnel', 'subscription-error')
+ // We may or may not be in a digest loop here depending on
+ // whether recurly could do validation locally, so do it async
+ $scope.$evalAsync(function () {
+ $scope.processing = false
+ $scope.genericError = err.message
+ _.each(
+ err.fields,
+ field => ($scope.validation.errorFields[field] = true)
+ )
+ })
+ } else {
+ const postData = {
+ _csrf: window.csrfToken,
+ recurly_token_id: cachedRecurlyBillingToken.id,
+ recurly_three_d_secure_action_result_token_id:
+ recurly3DSecureResultToken && recurly3DSecureResultToken.id,
+ subscriptionDetails: {
+ currencyCode: pricing.items.currency,
+ plan_code: pricing.items.plan.code,
+ coupon_code: pricing.items.coupon ? pricing.items.coupon.code : '',
+ first_name: $scope.data.first_name,
+ last_name: $scope.data.last_name,
+ isPaypal: $scope.paymentMethod.value === 'paypal',
+ address: {
+ address1: $scope.data.address1,
+ address2: $scope.data.address2,
+ country: $scope.data.country,
+ state: $scope.data.state,
+ zip: $scope.data.postal_code,
+ },
+ ITMCampaign: window.ITMCampaign,
+ ITMContent: window.ITMContent,
+ },
+ }
+
+ if (
+ postData.subscriptionDetails.isPaypal &&
+ $scope.ui.addCompanyDetails
+ ) {
+ postData.subscriptionDetails.billing_info = {}
+ if ($scope.data.company && $scope.data.company !== '') {
+ postData.subscriptionDetails.billing_info.company =
+ $scope.data.company
+ }
+ if ($scope.data.vat_number && $scope.data.vat_number !== '') {
+ postData.subscriptionDetails.billing_info.vat_number =
+ $scope.data.vat_number
+ }
+ }
+
+ eventTracking.sendMB('payment-page-form-submit', {
+ currencyCode: postData.subscriptionDetails.currencyCode,
+ plan_code: postData.subscriptionDetails.plan_code,
+ coupon_code: postData.subscriptionDetails.coupon_code,
+ isPaypal: postData.subscriptionDetails.isPaypal,
+ })
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-form-submitted',
+ postData.subscriptionDetails.plan_code
+ )
+ return $http
+ .post('/user/subscription/create', postData)
+ .then(function () {
+ eventTracking.sendMB('payment-page-form-success')
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-submission-success',
+ postData.subscriptionDetails.plan_code
+ )
+ window.location.href = '/user/subscription/thank-you'
+ })
+ .catch(response => {
+ $scope.processing = false
+ const { data } = response
+ $scope.genericError =
+ (data && data.message) ||
+ 'Something went wrong processing the request'
+
+ if (data.threeDSecureActionTokenId) {
+ initThreeDSecure(data.threeDSecureActionTokenId)
+ }
+ })
+ }
+ }
+
+ $scope.submit = function () {
+ $scope.processing = true
+ if ($scope.paymentMethod.value === 'paypal') {
+ const opts = { description: $scope.planName }
+ recurly.paypal(opts, completeSubscription)
+ } else {
+ const tokenData = _.cloneDeep($scope.data)
+ if (!$scope.ui.addCompanyDetails) {
+ delete tokenData.company
+ delete tokenData.vat_number
+ }
+ recurly.token(tokenData, completeSubscription)
+ }
+ }
+
+ const initThreeDSecure = function (threeDSecureActionTokenId) {
+ // instanciate and configure Recurly 3DSecure flow
+ const risk = recurly.Risk()
+ const threeDSecure = risk.ThreeDSecure({
+ actionTokenId: threeDSecureActionTokenId,
+ })
+
+ // on SCA verification error: show payment UI with the error message
+ threeDSecure.on('error', error => {
+ $scope.genericError = `Error: ${error.message}`
+ $scope.threeDSecureFlow = false
+ $scope.$apply()
+ })
+
+ // on SCA verification success: show payment UI in processing mode and
+ // resubmit the payment with the new token final success or error will be
+ // handled by `completeSubscription`
+ threeDSecure.on('token', recurly3DSecureResultToken => {
+ completeSubscription(null, null, recurly3DSecureResultToken)
+ $scope.genericError = null
+ $scope.threeDSecureFlow = false
+ $scope.processing = true
+ $scope.$apply()
+ })
+
+ // make sure the threeDSecureRecurlyContainer is empty (in case of
+ // retries) and show 3DSecure UI
+ $scope.threeDSecureRecurlyContainer.innerHTML = ''
+ $scope.threeDSecureFlow = true
+ threeDSecure.attach($scope.threeDSecureRecurlyContainer)
+
+ // scroll the UI into view (timeout needed to make sure the element is
+ // visible)
+ window.setTimeout(() => {
+ $scope.threeDSecureContainer.scrollIntoView()
+ }, 0)
+ }
+
+ // list taken from Recurly (see https://docs.recurly.com/docs/countries-provinces-and-states). Country code must exist on Recurly, so update with care
+ $scope.countries = [
+ { code: 'AF', name: 'Afghanistan' },
+ { code: 'AX', name: 'Ã…land Islands' },
+ { code: 'AL', name: 'Albania' },
+ { code: 'DZ', name: 'Algeria' },
+ { code: 'AS', name: 'American Samoa' },
+ { code: 'AD', name: 'Andorra' },
+ { code: 'AO', name: 'Angola' },
+ { code: 'AI', name: 'Anguilla' },
+ { code: 'AQ', name: 'Antarctica' },
+ { code: 'AG', name: 'Antigua and Barbuda' },
+ { code: 'AR', name: 'Argentina' },
+ { code: 'AM', name: 'Armenia' },
+ { code: 'AW', name: 'Aruba' },
+ { code: 'AC', name: 'Ascension Island' },
+ { code: 'AU', name: 'Australia' },
+ { code: 'AT', name: 'Austria' },
+ { code: 'AZ', name: 'Azerbaijan' },
+ { code: 'BS', name: 'Bahamas' },
+ { code: 'BH', name: 'Bahrain' },
+ { code: 'BD', name: 'Bangladesh' },
+ { code: 'BB', name: 'Barbados' },
+ { code: 'BY', name: 'Belarus' },
+ { code: 'BE', name: 'Belgium' },
+ { code: 'BZ', name: 'Belize' },
+ { code: 'BJ', name: 'Benin' },
+ { code: 'BM', name: 'Bermuda' },
+ { code: 'BT', name: 'Bhutan' },
+ { code: 'BO', name: 'Bolivia' },
+ { code: 'BA', name: 'Bosnia and Herzegovina' },
+ { code: 'BW', name: 'Botswana' },
+ { code: 'BV', name: 'Bouvet Island' },
+ { code: 'BR', name: 'Brazil' },
+ { code: 'BQ', name: 'British Antarctic Territory' },
+ { code: 'IO', name: 'British Indian Ocean Territory' },
+ { code: 'VG', name: 'British Virgin Islands' },
+ { code: 'BN', name: 'Brunei' },
+ { code: 'BG', name: 'Bulgaria' },
+ { code: 'BF', name: 'Burkina Faso' },
+ { code: 'BI', name: 'Burundi' },
+ { code: 'CV', name: 'Cabo Verde' },
+ { code: 'KH', name: 'Cambodia' },
+ { code: 'CM', name: 'Cameroon' },
+ { code: 'CA', name: 'Canada' },
+ { code: 'IC', name: 'Canary Islands' },
+ { code: 'CT', name: 'Canton and Enderbury Islands' },
+ { code: 'KY', name: 'Cayman Islands' },
+ { code: 'CF', name: 'Central African Republic' },
+ { code: 'EA', name: 'Ceuta and Melilla' },
+ { code: 'TD', name: 'Chad' },
+ { code: 'CL', name: 'Chile' },
+ { code: 'CN', name: 'China' },
+ { code: 'CX', name: 'Christmas Island' },
+ { code: 'CP', name: 'Clipperton Island' },
+ { code: 'CC', name: 'Cocos [Keeling] Islands' },
+ { code: 'CO', name: 'Colombia' },
+ { code: 'KM', name: 'Comoros' },
+ { code: 'CG', name: 'Congo - Brazzaville' },
+ { code: 'CD', name: 'Congo - Kinshasa' },
+ { code: 'CD', name: 'Congo [DRC]' },
+ { code: 'CG', name: 'Congo [Republic]' },
+ { code: 'CK', name: 'Cook Islands' },
+ { code: 'CR', name: 'Costa Rica' },
+ { code: 'CI', name: 'Côte d’Ivoire' },
+ { code: 'HR', name: 'Croatia' },
+ { code: 'CU', name: 'Cuba' },
+ { code: 'CY', name: 'Cyprus' },
+ { code: 'CZ', name: 'Czech Republic' },
+ { code: 'DK', name: 'Denmark' },
+ { code: 'DG', name: 'Diego Garcia' },
+ { code: 'DJ', name: 'Djibouti' },
+ { code: 'DM', name: 'Dominica' },
+ { code: 'DO', name: 'Dominican Republic' },
+ { code: 'NQ', name: 'Dronning Maud Land' },
+ { code: 'TL', name: 'East Timor' },
+ { code: 'EC', name: 'Ecuador' },
+ { code: 'EG', name: 'Egypt' },
+ { code: 'SV', name: 'El Salvador' },
+ { code: 'GQ', name: 'Equatorial Guinea' },
+ { code: 'ER', name: 'Eritrea' },
+ { code: 'EE', name: 'Estonia' },
+ { code: 'ET', name: 'Ethiopia' },
+ { code: 'FK', name: 'Falkland Islands [Islas Malvinas]' },
+ { code: 'FK', name: 'Falkland Islands' },
+ { code: 'FO', name: 'Faroe Islands' },
+ { code: 'FJ', name: 'Fiji' },
+ { code: 'FI', name: 'Finland' },
+ { code: 'FR', name: 'France' },
+ { code: 'GF', name: 'French Guiana' },
+ { code: 'PF', name: 'French Polynesia' },
+ { code: 'FQ', name: 'French Southern and Antarctic Territories' },
+ { code: 'TF', name: 'French Southern Territories' },
+ { code: 'GA', name: 'Gabon' },
+ { code: 'GM', name: 'Gambia' },
+ { code: 'GE', name: 'Georgia' },
+ { code: 'DE', name: 'Germany' },
+ { code: 'GH', name: 'Ghana' },
+ { code: 'GI', name: 'Gibraltar' },
+ { code: 'GR', name: 'Greece' },
+ { code: 'GL', name: 'Greenland' },
+ { code: 'GD', name: 'Grenada' },
+ { code: 'GP', name: 'Guadeloupe' },
+ { code: 'GU', name: 'Guam' },
+ { code: 'GT', name: 'Guatemala' },
+ { code: 'GG', name: 'Guernsey' },
+ { code: 'GW', name: 'Guinea-Bissau' },
+ { code: 'GN', name: 'Guinea' },
+ { code: 'GY', name: 'Guyana' },
+ { code: 'HT', name: 'Haiti' },
+ { code: 'HM', name: 'Heard Island and McDonald Islands' },
+ { code: 'HN', name: 'Honduras' },
+ { code: 'HK', name: 'Hong Kong' },
+ { code: 'HU', name: 'Hungary' },
+ { code: 'IS', name: 'Iceland' },
+ { code: 'IN', name: 'India' },
+ { code: 'ID', name: 'Indonesia' },
+ { code: 'IR', name: 'Iran' },
+ { code: 'IQ', name: 'Iraq' },
+ { code: 'IE', name: 'Ireland' },
+ { code: 'IM', name: 'Isle of Man' },
+ { code: 'IL', name: 'Israel' },
+ { code: 'IT', name: 'Italy' },
+ { code: 'CI', name: 'Ivory Coast' },
+ { code: 'JM', name: 'Jamaica' },
+ { code: 'JP', name: 'Japan' },
+ { code: 'JE', name: 'Jersey' },
+ { code: 'JT', name: 'Johnston Island' },
+ { code: 'JO', name: 'Jordan' },
+ { code: 'KZ', name: 'Kazakhstan' },
+ { code: 'KE', name: 'Kenya' },
+ { code: 'KI', name: 'Kiribati' },
+ { code: 'KW', name: 'Kuwait' },
+ { code: 'KG', name: 'Kyrgyzstan' },
+ { code: 'LA', name: 'Laos' },
+ { code: 'LV', name: 'Latvia' },
+ { code: 'LB', name: 'Lebanon' },
+ { code: 'LS', name: 'Lesotho' },
+ { code: 'LR', name: 'Liberia' },
+ { code: 'LY', name: 'Libya' },
+ { code: 'LI', name: 'Liechtenstein' },
+ { code: 'LT', name: 'Lithuania' },
+ { code: 'LU', name: 'Luxembourg' },
+ { code: 'MO', name: 'Macau SAR China' },
+ { code: 'MO', name: 'Macau' },
+ { code: 'MK', name: 'Macedonia [FYROM]' },
+ { code: 'MK', name: 'Macedonia' },
+ { code: 'MG', name: 'Madagascar' },
+ { code: 'MW', name: 'Malawi' },
+ { code: 'MY', name: 'Malaysia' },
+ { code: 'MV', name: 'Maldives' },
+ { code: 'ML', name: 'Mali' },
+ { code: 'MT', name: 'Malta' },
+ { code: 'MH', name: 'Marshall Islands' },
+ { code: 'MQ', name: 'Martinique' },
+ { code: 'MR', name: 'Mauritania' },
+ { code: 'MU', name: 'Mauritius' },
+ { code: 'YT', name: 'Mayotte' },
+ { code: 'FX', name: 'Metropolitan France' },
+ { code: 'MX', name: 'Mexico' },
+ { code: 'FM', name: 'Micronesia' },
+ { code: 'MI', name: 'Midway Islands' },
+ { code: 'MD', name: 'Moldova' },
+ { code: 'MC', name: 'Monaco' },
+ { code: 'MN', name: 'Mongolia' },
+ { code: 'ME', name: 'Montenegro' },
+ { code: 'MS', name: 'Montserrat' },
+ { code: 'MA', name: 'Morocco' },
+ { code: 'MZ', name: 'Mozambique' },
+ { code: 'MM', name: 'Myanmar [Burma]' },
+ { code: 'NA', name: 'Namibia' },
+ { code: 'NR', name: 'Nauru' },
+ { code: 'NP', name: 'Nepal' },
+ { code: 'AN', name: 'Netherlands Antilles' },
+ { code: 'NL', name: 'Netherlands' },
+ { code: 'NC', name: 'New Caledonia' },
+ { code: 'NZ', name: 'New Zealand' },
+ { code: 'NI', name: 'Nicaragua' },
+ { code: 'NE', name: 'Niger' },
+ { code: 'NG', name: 'Nigeria' },
+ { code: 'NU', name: 'Niue' },
+ { code: 'NF', name: 'Norfolk Island' },
+ { code: 'KP', name: 'North Korea' },
+ { code: 'VD', name: 'North Vietnam' },
+ { code: 'MP', name: 'Northern Mariana Islands' },
+ { code: 'NO', name: 'Norway' },
+ { code: 'OM', name: 'Oman' },
+ { code: 'QO', name: 'Outlying Oceania' },
+ { code: 'PC', name: 'Pacific Islands Trust Territory' },
+ { code: 'PK', name: 'Pakistan' },
+ { code: 'PW', name: 'Palau' },
+ { code: 'PS', name: 'Palestinian Territories' },
+ { code: 'PZ', name: 'Panama Canal Zone' },
+ { code: 'PA', name: 'Panama' },
+ { code: 'PG', name: 'Papua New Guinea' },
+ { code: 'PY', name: 'Paraguay' },
+ { code: 'YD', name: "People's Democratic Republic of Yemen" },
+ { code: 'PE', name: 'Peru' },
+ { code: 'PH', name: 'Philippines' },
+ { code: 'PN', name: 'Pitcairn Islands' },
+ { code: 'PL', name: 'Poland' },
+ { code: 'PT', name: 'Portugal' },
+ { code: 'PR', name: 'Puerto Rico' },
+ { code: 'QA', name: 'Qatar' },
+ { code: 'RE', name: 'Réunion' },
+ { code: 'RO', name: 'Romania' },
+ { code: 'RU', name: 'Russia' },
+ { code: 'RW', name: 'Rwanda' },
+ { code: 'BL', name: 'Saint Barthélemy' },
+ { code: 'SH', name: 'Saint Helena' },
+ { code: 'KN', name: 'Saint Kitts and Nevis' },
+ { code: 'LC', name: 'Saint Lucia' },
+ { code: 'MF', name: 'Saint Martin' },
+ { code: 'PM', name: 'Saint Pierre and Miquelon' },
+ { code: 'VC', name: 'Saint Vincent and the Grenadines' },
+ { code: 'WS', name: 'Samoa' },
+ { code: 'SM', name: 'San Marino' },
+ { code: 'ST', name: 'São Tomé and PrÃncipe' },
+ { code: 'SA', name: 'Saudi Arabia' },
+ { code: 'SN', name: 'Senegal' },
+ { code: 'CS', name: 'Serbia and Montenegro' },
+ { code: 'RS', name: 'Serbia' },
+ { code: 'SC', name: 'Seychelles' },
+ { code: 'SL', name: 'Sierra Leone' },
+ { code: 'SG', name: 'Singapore' },
+ { code: 'SK', name: 'Slovakia' },
+ { code: 'SI', name: 'Slovenia' },
+ { code: 'SB', name: 'Solomon Islands' },
+ { code: 'SO', name: 'Somalia' },
+ { code: 'ZA', name: 'South Africa' },
+ { code: 'GS', name: 'South Georgia and the South Sandwich Islands' },
+ { code: 'KR', name: 'South Korea' },
+ { code: 'ES', name: 'Spain' },
+ { code: 'LK', name: 'Sri Lanka' },
+ { code: 'SD', name: 'Sudan' },
+ { code: 'SR', name: 'Suriname' },
+ { code: 'SJ', name: 'Svalbard and Jan Mayen' },
+ { code: 'SZ', name: 'Swaziland' },
+ { code: 'SE', name: 'Sweden' },
+ { code: 'CH', name: 'Switzerland' },
+ { code: 'SY', name: 'Syria' },
+ { code: 'TW', name: 'Taiwan' },
+ { code: 'TJ', name: 'Tajikistan' },
+ { code: 'TZ', name: 'Tanzania' },
+ { code: 'TH', name: 'Thailand' },
+ { code: 'TL', name: 'Timor-Leste' },
+ { code: 'TG', name: 'Togo' },
+ { code: 'TK', name: 'Tokelau' },
+ { code: 'TO', name: 'Tonga' },
+ { code: 'TT', name: 'Trinidad and Tobago' },
+ { code: 'TA', name: 'Tristan da Cunha' },
+ { code: 'TN', name: 'Tunisia' },
+ { code: 'TR', name: 'Turkey' },
+ { code: 'TM', name: 'Turkmenistan' },
+ { code: 'TC', name: 'Turks and Caicos Islands' },
+ { code: 'TV', name: 'Tuvalu' },
+ { code: 'UM', name: 'U.S. Minor Outlying Islands' },
+ { code: 'PU', name: 'U.S. Miscellaneous Pacific Islands' },
+ { code: 'VI', name: 'U.S. Virgin Islands' },
+ { code: 'UG', name: 'Uganda' },
+ { code: 'UA', name: 'Ukraine' },
+ { code: 'AE', name: 'United Arab Emirates' },
+ { code: 'GB', name: 'United Kingdom' },
+ { code: 'US', name: 'United States' },
+ { code: 'UY', name: 'Uruguay' },
+ { code: 'UZ', name: 'Uzbekistan' },
+ { code: 'VU', name: 'Vanuatu' },
+ { code: 'VA', name: 'Vatican City' },
+ { code: 'VE', name: 'Venezuela' },
+ { code: 'VN', name: 'Vietnam' },
+ { code: 'WK', name: 'Wake Island' },
+ { code: 'WF', name: 'Wallis and Futuna' },
+ { code: 'EH', name: 'Western Sahara' },
+ { code: 'YE', name: 'Yemen' },
+ { code: 'ZM', name: 'Zambia' },
+ { code: 'ZW', name: 'Zimbabwe' },
+ ]
+ }
+)
diff --git a/services/web/frontend/js/main/oauth/controllers/UserOauthController.js b/services/web/frontend/js/main/oauth/controllers/UserOauthController.js
new file mode 100644
index 0000000000..b6f6f52ccd
--- /dev/null
+++ b/services/web/frontend/js/main/oauth/controllers/UserOauthController.js
@@ -0,0 +1,52 @@
+import App from '../../../base'
+
+export default App.controller(
+ 'UserOauthController',
+ function ($http, $scope, $q) {
+ const _reset = function () {
+ $scope.ui = {
+ hasError: false,
+ errorMessage: '',
+ }
+ $scope.providers = window.oauthProviders
+ $scope.thirdPartyIds = window.thirdPartyIds
+ }
+ const _unlinkError = (providerId, err) => {
+ $scope.providers[providerId].ui.hasError = true
+ $scope.providers[providerId].ui.errorMessage =
+ err && err.data && err.data.message ? err.data.message : 'error'
+ }
+
+ $scope.unlink = providerId => {
+ if (window.ExposedSettings.isOverleaf) {
+ // UI
+ $scope.providers[providerId].ui = {
+ hasError: false,
+ isProcessing: true,
+ }
+ // Data for update
+ const data = {
+ _csrf: window.csrfToken,
+ link: false,
+ providerId,
+ }
+ $http
+ .post('/user/oauth-unlink', data)
+ .catch(error => {
+ $scope.providers[providerId].ui.isProcessing = false
+ _unlinkError(providerId, error)
+ })
+ .then(response => {
+ $scope.providers[providerId].ui.isProcessing = false
+ if (response.status === 200) {
+ $scope.thirdPartyIds[providerId] = null
+ } else {
+ _unlinkError(providerId, response)
+ }
+ })
+ }
+ }
+
+ _reset()
+ }
+)
diff --git a/services/web/frontend/js/main/plans.js b/services/web/frontend/js/main/plans.js
new file mode 100644
index 0000000000..478c139f5d
--- /dev/null
+++ b/services/web/frontend/js/main/plans.js
@@ -0,0 +1,464 @@
+/* eslint-disable
+ camelcase,
+ max-len
+*/
+import App from '../base'
+import getMeta from '../utils/meta'
+App.factory('MultiCurrencyPricing', function () {
+ const currencyCode = getMeta('ol-recomendedCurrency')
+
+ return {
+ currencyCode,
+
+ plans: {
+ USD: {
+ symbol: '$',
+ student: {
+ monthly: '$8',
+ annual: '$80',
+ },
+ personal: {
+ monthly: '$10',
+ annual: '$120',
+ },
+ collaborator: {
+ monthly: '$15',
+ annual: '$180',
+ },
+ professional: {
+ monthly: '$30',
+ annual: '$360',
+ },
+ },
+
+ EUR: {
+ symbol: '€',
+ student: {
+ monthly: '€7',
+ annual: '€70',
+ },
+ personal: {
+ monthly: '€9',
+ annual: '€108',
+ },
+ collaborator: {
+ monthly: '€14',
+ annual: '€168',
+ },
+ professional: {
+ monthly: '€28',
+ annual: '€336',
+ },
+ },
+
+ GBP: {
+ symbol: '£',
+ student: {
+ monthly: '£6',
+ annual: '£60',
+ },
+ personal: {
+ monthly: '£8',
+ annual: '£96',
+ },
+ collaborator: {
+ monthly: '£12',
+ annual: '£144',
+ },
+ professional: {
+ monthly: '£24',
+ annual: '£288',
+ },
+ },
+
+ SEK: {
+ symbol: 'kr',
+ student: {
+ monthly: '60 kr',
+ annual: '600 kr',
+ },
+ personal: {
+ monthly: '73 kr',
+ annual: '876 kr',
+ },
+ collaborator: {
+ monthly: '110 kr',
+ annual: '1320 kr',
+ },
+ professional: {
+ monthly: '220 kr',
+ annual: '2640 kr',
+ },
+ },
+ CAD: {
+ symbol: '$',
+ student: {
+ monthly: '$9',
+ annual: '$90',
+ },
+ personal: {
+ monthly: '$11',
+ annual: '$132',
+ },
+ collaborator: {
+ monthly: '$17',
+ annual: '$204',
+ },
+ professional: {
+ monthly: '$34',
+ annual: '$408',
+ },
+ },
+
+ NOK: {
+ symbol: 'kr',
+ student: {
+ monthly: '60 kr',
+ annual: '600 kr',
+ },
+ personal: {
+ monthly: '73 kr',
+ annual: '876 kr',
+ },
+ collaborator: {
+ monthly: '110 kr',
+ annual: '1320 kr',
+ },
+ professional: {
+ monthly: '220 kr',
+ annual: '2640 kr',
+ },
+ },
+
+ DKK: {
+ symbol: 'kr',
+ student: {
+ monthly: '50 kr',
+ annual: '500 kr',
+ },
+ personal: {
+ monthly: '60 kr',
+ annual: '720 kr',
+ },
+ collaborator: {
+ monthly: '90 kr',
+ annual: '1080 kr',
+ },
+ professional: {
+ monthly: '180 kr',
+ annual: '2160 kr',
+ },
+ },
+
+ AUD: {
+ symbol: '$',
+ student: {
+ monthly: '$10',
+ annual: '$100',
+ },
+ personal: {
+ monthly: '$12',
+ annual: '$144',
+ },
+ collaborator: {
+ monthly: '$18',
+ annual: '$216',
+ },
+ professional: {
+ monthly: '$35',
+ annual: '$420',
+ },
+ },
+
+ NZD: {
+ symbol: '$',
+ student: {
+ monthly: '$10',
+ annual: '$100',
+ },
+ personal: {
+ monthly: '$12',
+ annual: '$144',
+ },
+ collaborator: {
+ monthly: '$18',
+ annual: '$216',
+ },
+ professional: {
+ monthly: '$35',
+ annual: '$420',
+ },
+ },
+
+ CHF: {
+ symbol: 'Fr',
+ student: {
+ monthly: 'Fr 8',
+ annual: 'Fr 80',
+ },
+ personal: {
+ monthly: 'Fr 10',
+ annual: 'Fr 120',
+ },
+ collaborator: {
+ monthly: 'Fr 15',
+ annual: 'Fr 180',
+ },
+ professional: {
+ monthly: 'Fr 30',
+ annual: 'Fr 360',
+ },
+ },
+
+ SGD: {
+ symbol: '$',
+ student: {
+ monthly: '$12',
+ annual: '$120',
+ },
+ personal: {
+ monthly: '$13',
+ annual: '$156',
+ },
+ collaborator: {
+ monthly: '$20',
+ annual: '$240',
+ },
+ professional: {
+ monthly: '$40',
+ annual: '$480',
+ },
+ },
+ },
+ }
+})
+
+App.controller(
+ 'PlansController',
+ function (
+ $scope,
+ $modal,
+ eventTracking,
+ MultiCurrencyPricing,
+ $http,
+ $filter,
+ $location
+ ) {
+ $scope.plans = MultiCurrencyPricing.plans
+
+ $scope.currencyCode = MultiCurrencyPricing.currencyCode
+
+ $scope.trial_len = 7
+
+ $scope.planQueryString = '_free_trial_7_days'
+
+ $scope.ui = { view: 'monthly' }
+
+ $scope.changeCurreny = function (e, newCurrency) {
+ e.preventDefault()
+ $scope.currencyCode = newCurrency
+ }
+
+ // because ternary logic in angular bindings is hard
+ $scope.getCollaboratorPlanCode = function () {
+ const { view } = $scope.ui
+ if (view === 'annual') {
+ return 'collaborator-annual'
+ } else {
+ return `collaborator${$scope.planQueryString}`
+ }
+ }
+
+ $scope.getPersonalPlanCode = function () {
+ const { view } = $scope.ui
+ if (view === 'annual') {
+ return 'paid-personal-annual'
+ } else {
+ return `paid-personal${$scope.planQueryString}`
+ }
+ }
+
+ $scope.signUpNowClicked = function (plan, location) {
+ if ($scope.ui.view === 'annual') {
+ plan = `${plan}_annual`
+ }
+ plan = eventLabel(plan, location)
+ eventTracking.sendMB('plans-page-start-trial')
+ eventTracking.send('subscription-funnel', 'sign_up_now_button', plan)
+ }
+
+ $scope.switchToMonthly = function (e, location) {
+ const uiView = 'monthly'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
+
+ $scope.switchToStudent = function (e, location) {
+ const uiView = 'student'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
+
+ $scope.switchToAnnual = function (e, location) {
+ const uiView = 'annual'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
+
+ $scope.openGroupPlanModal = function () {
+ const path = `${window.location.pathname}${window.location.search}`
+ history.replaceState(null, document.title, path + '#groups')
+ $modal
+ .open({
+ templateUrl: 'groupPlanModalPurchaseTemplate',
+ controller: 'GroupPlansModalPurchaseController',
+ })
+ .result.finally(() =>
+ history.replaceState(null, document.title, window.location.pathname)
+ )
+ eventTracking.send(
+ 'subscription-funnel',
+ 'plans-page',
+ 'group-inquiry-potential'
+ )
+ }
+
+ if ($location.hash() === 'groups') {
+ $scope.openGroupPlanModal()
+ }
+
+ var eventLabel = (label, location) => label
+
+ function switchEvent(e, label, location) {
+ e.preventDefault()
+ const gaLabel = eventLabel(label, location)
+ eventTracking.send('subscription-funnel', 'plans-page', gaLabel)
+ }
+ }
+)
+
+App.controller(
+ 'GroupPlansModalPurchaseController',
+ function ($scope, $modal, $location, $httpParamSerializer) {
+ $scope.options = {
+ plan_codes: [
+ {
+ display: 'Collaborator',
+ code: 'collaborator',
+ },
+ {
+ display: 'Professional',
+ code: 'professional',
+ },
+ ],
+ currencies: [
+ {
+ display: 'USD ($)',
+ code: 'USD',
+ },
+ {
+ display: 'GBP (£)',
+ code: 'GBP',
+ },
+ {
+ display: 'EUR (€)',
+ code: 'EUR',
+ },
+ ],
+ currencySymbols: {
+ USD: '$',
+ EUR: '€',
+ GBP: '£',
+ },
+ sizes: [2, 3, 4, 5, 10, 20, 50],
+ usages: [
+ {
+ display: 'Enterprise',
+ code: 'enterprise',
+ },
+ {
+ display: 'Educational',
+ code: 'educational',
+ },
+ ],
+ }
+
+ $scope.prices = getMeta('ol-groupPlans')
+
+ let currency = 'USD'
+ const recomendedCurrency = getMeta('ol-recomendedCurrency')
+ if (['USD', 'GBP', 'EUR'].includes(recomendedCurrency)) {
+ currency = recomendedCurrency
+ }
+
+ // default selected
+ $scope.selected = {
+ plan_code: 'collaborator',
+ currency,
+ size: '10',
+ usage: 'enterprise',
+ }
+ // selected via query
+ if ($location.search()) {
+ // usage
+ if ($location.search().usage) {
+ $scope.options.usages.forEach(usage => {
+ if (usage.code === $location.search().usage) {
+ $scope.selected.usage = usage.code
+ }
+ })
+ }
+ // plan
+ if ($location.search().plan) {
+ $scope.options.plan_codes.forEach(plan => {
+ if (plan.code === $location.search().plan) {
+ $scope.selected.plan_code = plan.code
+ }
+ })
+ }
+ // number
+ if ($location.search().number) {
+ // $location.search().number is a string,
+ // but $scope.options.sizes are numbers
+ // and $scope.selected.size is a string
+ const groupCount = parseInt($location.search().number, 10)
+ if ($scope.options.sizes.indexOf(groupCount) !== -1) {
+ $scope.selected.size = $location.search().number
+ }
+ }
+ // currency
+ if ($location.search().currency) {
+ $scope.options.currencies.forEach(currency => {
+ if (currency.code === $location.search().currency) {
+ $scope.selected.currency = currency.code
+ }
+ })
+ }
+ }
+
+ $scope.recalculatePrice = function () {
+ const { usage, plan_code, currency, size } = $scope.selected
+ const price = $scope.prices[usage][plan_code][currency][size]
+ const currencySymbol = $scope.options.currencySymbols[currency]
+ $scope.displayPrice = `${currencySymbol}${price}`
+ }
+
+ $scope.$watch('selected', $scope.recalculatePrice, true)
+ $scope.recalculatePrice()
+
+ $scope.purchase = function () {
+ const { plan_code, size, usage, currency } = $scope.selected
+ const queryParams = {
+ planCode: `group_${plan_code}_${size}_${usage}`,
+ currency,
+ itm_campaign: 'groups',
+ }
+ if ($location.search().itm_content) {
+ queryParams.itm_content = $location.search().itm_content
+ }
+ window.location = `/user/subscription/new?${$httpParamSerializer(
+ queryParams
+ )}`
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/post-gateway.js b/services/web/frontend/js/main/post-gateway.js
new file mode 100644
index 0000000000..d029d941fe
--- /dev/null
+++ b/services/web/frontend/js/main/post-gateway.js
@@ -0,0 +1,18 @@
+import App from '../base'
+
+export default App.controller('PostGatewayController', function ($scope) {
+ $scope.handleGateway = function () {
+ const { params } = JSON.parse($('#gateway-data').text())
+ params.viaGateway = 'true'
+ Object.keys(params).forEach(param => {
+ $(' ')
+ .attr({
+ type: 'hidden',
+ name: param,
+ value: params[param],
+ })
+ .appendTo('#gateway')
+ })
+ $('#gateway').submit()
+ }
+})
diff --git a/services/web/frontend/js/main/project-list/index.js b/services/web/frontend/js/main/project-list/index.js
new file mode 100644
index 0000000000..4b55d00a9c
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/index.js
@@ -0,0 +1,8 @@
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+import './project-list'
+import './modal-controllers'
+import './tag-controllers'
+import './notifications-controller'
+import './left-hand-menu-promo-controller'
+import '../../services/queued-http'
diff --git a/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js b/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js
new file mode 100644
index 0000000000..6f0c92eab4
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js
@@ -0,0 +1,26 @@
+import App from '../../base'
+
+export default App.controller(
+ 'LeftHandMenuPromoController',
+ function ($scope, UserAffiliationsDataService, eventTracking) {
+ $scope.hasProjects = window.data.projects.length > 0
+ $scope.userHasNoSubscription = window.userHasNoSubscription
+
+ $scope.upgradeSubscription = function () {
+ eventTracking.send('subscription-funnel', 'project-page', 'upgrade')
+ }
+
+ $scope.share = function () {
+ eventTracking.send('subscription-funnel', 'project-page', 'sharing')
+ }
+
+ const _userHasNoAffiliation = function () {
+ $scope.withAffiliations = window.data.userAffiliations.length > 0
+ $scope.userOnPayingUniversity = window.data.userAffiliations.some(
+ affiliation => affiliation.licence && affiliation.licence !== 'free'
+ )
+ }
+
+ _userHasNoAffiliation()
+ }
+)
diff --git a/services/web/frontend/js/main/project-list/modal-controllers.js b/services/web/frontend/js/main/project-list/modal-controllers.js
new file mode 100644
index 0000000000..232a85aca8
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/modal-controllers.js
@@ -0,0 +1,171 @@
+/* eslint-disable
+ node/handle-callback-err,
+ max-len,
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../../base'
+App.controller(
+ 'RenameProjectModalController',
+ function ($scope, $modalInstance, $timeout, project, queuedHttp) {
+ $scope.inputs = { projectName: project.name }
+
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.rename = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $scope
+ .renameProject(project, $scope.inputs.projectName)
+ .then(function () {
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'CloneProjectModalController',
+ function ($scope, $modalInstance, $timeout, project) {
+ $scope.inputs = { projectName: project.name + ' (Copy)' }
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.clone = function () {
+ $scope.state.inflight = true
+ return $scope
+ .cloneProject(project, $scope.inputs.projectName)
+ .then(function () {
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'NewProjectModalController',
+ function ($scope, $modalInstance, $timeout, template) {
+ $scope.inputs = { projectName: '' }
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.create = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $scope
+ .createProject($scope.inputs.projectName, template)
+ .then(function (response) {
+ const { data } = response
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close(data.project_id)
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'ArchiveTrashLeaveOrDeleteProjectsModalController',
+ function ($scope, $modalInstance, $timeout, projects, action) {
+ $scope.projects = projects
+
+ $scope.action = action
+
+ $scope.confirm = () => $modalInstance.close({ projects, action })
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
+
+App.controller(
+ 'UploadProjectModalController',
+ function ($scope, $modalInstance, $timeout) {
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+
+ return ($scope.onComplete = function (error, name, response) {
+ if (response.project_id != null) {
+ return (window.location = `/project/${response.project_id}`)
+ }
+ })
+ }
+)
+
+App.controller(
+ 'V1ImportModalController',
+ function ($scope, $modalInstance, project) {
+ $scope.project = project
+
+ return ($scope.dismiss = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+export default App.controller(
+ 'ShowErrorModalController',
+ function ($scope, $modalInstance, error) {
+ $scope.error = error
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
diff --git a/services/web/frontend/js/main/project-list/notifications-controller.js b/services/web/frontend/js/main/project-list/notifications-controller.js
new file mode 100644
index 0000000000..500b712994
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/notifications-controller.js
@@ -0,0 +1,125 @@
+import App from '../../base'
+
+const ExposedSettings = window.ExposedSettings
+App.controller('NotificationsController', function ($scope, $http) {
+ for (const notification of $scope.notifications || []) {
+ notification.hide = false
+ }
+
+ $scope.samlInitPath = ExposedSettings.samlInitPath
+
+ $scope.dismiss = notification => {
+ if (!notification._id) {
+ notification.hide = true
+ return
+ }
+ $http({
+ url: `/notifications/${notification._id}`,
+ method: 'DELETE',
+ headers: {
+ 'X-Csrf-Token': window.csrfToken,
+ },
+ }).then(() => (notification.hide = true))
+ }
+})
+
+App.controller(
+ 'DismissableNotificationsController',
+ function ($scope, localStorage) {
+ $scope.shouldShowNotification =
+ localStorage('dismissed-covid-19-notification-extended') !== true
+
+ $scope.dismiss = () => {
+ localStorage('dismissed-covid-19-notification-extended', true)
+ $scope.shouldShowNotification = false
+ }
+ }
+)
+
+App.controller('ProjectInviteNotificationController', function ($scope, $http) {
+ // Shortcuts for translation keys
+ $scope.projectName = $scope.notification.messageOpts.projectName
+ $scope.userName = $scope.notification.messageOpts.userName
+
+ $scope.accept = function () {
+ $scope.notification.inflight = true
+ return $http({
+ url: `/project/${$scope.notification.messageOpts.projectId}/invite/token/${$scope.notification.messageOpts.token}/accept`,
+ method: 'POST',
+ headers: {
+ 'X-Csrf-Token': window.csrfToken,
+ 'X-Requested-With': 'XMLHttpRequest',
+ },
+ })
+ .then(() => {
+ $scope.notification.accepted = true
+ })
+ .catch(({ status }) => {
+ if (status === 404) {
+ // 404 probably means the invite has already been accepted and
+ // deleted. Treat as success
+ $scope.notification.accepted = true
+ } else {
+ $scope.notification.error = true
+ }
+ })
+ .finally(() => {
+ $scope.notification.inflight = false
+ })
+ }
+})
+
+App.controller(
+ 'EmailNotificationController',
+ function ($scope, $http, UserAffiliationsDataService) {
+ $scope.userEmails = window.data.userEmails
+ const _ssoAvailable = email => {
+ if (!ExposedSettings.hasSamlFeature) return false
+ if (email.samlProviderId) return true
+ if (!email.affiliation || !email.affiliation.institution) return false
+ if (email.affiliation.institution.ssoEnabled) return true
+ if (
+ ExposedSettings.hasSamlBeta &&
+ email.affiliation.institution.ssoBeta
+ ) {
+ return true
+ }
+ return false
+ }
+ $scope.showConfirmEmail = email => {
+ if (ExposedSettings.emailConfirmationDisabled) {
+ return false
+ }
+ if (!email.confirmedAt && !email.hide) {
+ if (_ssoAvailable(email)) {
+ return false
+ }
+ return true
+ }
+ return false
+ }
+ for (const userEmail of $scope.userEmails) {
+ userEmail.hide = false
+ }
+
+ $scope.resendConfirmationEmail = function (userEmail) {
+ userEmail.confirmationInflight = true
+ userEmail.error = false
+ userEmail.errorMessage = null
+ UserAffiliationsDataService.resendConfirmationEmail(userEmail.email)
+ .then(() => {
+ userEmail.hide = true
+ $scope.$emit('project-list:notifications-received')
+ })
+ .catch(error => {
+ userEmail.error = true
+ userEmail.errorMessage = error.data.message
+ console.error(error)
+ $scope.$emit('project-list:notifications-received')
+ })
+ .finally(() => {
+ userEmail.confirmationInflight = false
+ })
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/project-list/project-list.js b/services/web/frontend/js/main/project-list/project-list.js
new file mode 100644
index 0000000000..83a23c07e2
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/project-list.js
@@ -0,0 +1,922 @@
+import _ from 'lodash'
+import App from '../../base'
+import './services/project-list'
+App.controller('ProjectPageController', function (
+ $scope,
+ $modal,
+ $window,
+ queuedHttp,
+ eventTracking, // eslint-disable-line camelcase
+ $timeout,
+ localStorage,
+ ProjectListService
+) {
+ $scope.projects = window.data.projects
+ $scope.tags = window.data.tags
+ $scope.notifications = window.data.notifications
+ $scope.notificationsInstitution = window.data.notificationsInstitution
+ $scope.allSelected = false
+ $scope.selectedProjects = []
+ $scope.filter = 'all'
+ $scope.predicate = 'lastUpdated'
+ $scope.nUntagged = 0
+ $scope.reverse = true
+ $scope.searchText = { value: '' }
+ $scope.$watch('predicate', function (newValue) {
+ $scope.comparator =
+ newValue === 'ownerName' ? ownerNameComparator : defaultComparator
+ })
+
+ $timeout(() => recalculateProjectListHeight(), 10)
+
+ $scope.$watch(
+ () =>
+ $scope.projects.filter(
+ project =>
+ (project.tags == null || project.tags.length === 0) &&
+ !project.archived &&
+ !project.trashed
+ ).length,
+ newVal => ($scope.nUntagged = newVal)
+ )
+
+ var recalculateProjectListHeight = function () {
+ const $projListCard = $('.project-list-card')
+ if (!$projListCard || !$projListCard.offset()) return
+
+ const topOffset = $projListCard.offset().top
+ const cardPadding = $projListCard.outerHeight() - $projListCard.height()
+ const bottomOffset = $('footer').outerHeight()
+ const height = $window.innerHeight - topOffset - bottomOffset - cardPadding
+ $scope.projectListHeight = height
+ }
+
+ function defaultComparator(v1, v2) {
+ var result = 0
+ var type1 = v1.type
+ var type2 = v2.type
+
+ if ($scope.predicate === 'ownerName') {
+ return
+ }
+
+ if (type1 === type2) {
+ var value1 = v1.value
+ var value2 = v2.value
+
+ if (type1 === 'string') {
+ // Compare strings case-insensitively
+ value1 = value1.toLowerCase()
+ value2 = value2.toLowerCase()
+ } else if (type1 === 'object') {
+ // For basic objects, use the position of the object
+ // in the collection instead of the value
+ if (angular.isObject(value1)) value1 = v1.index
+ if (angular.isObject(value2)) value2 = v2.index
+ }
+
+ if (value1 !== value2) {
+ result = value1 < value2 ? -1 : 1
+ }
+ } else {
+ result = type1 < type2 ? -1 : 1
+ }
+
+ return result
+ }
+
+ function ownerNameComparator(v1, v2) {
+ if ($scope.predicate !== 'ownerName') {
+ return
+ }
+ if (v1.value === 'You') {
+ if (v2.value === 'You') {
+ return v1.index < v2.index ? -1 : 1
+ } else {
+ return 1
+ }
+ } else if (v1.value === 'An Overleaf v1 User' || v1.value === 'None') {
+ if (v2.value === 'An Overleaf v1 User' || v2.value === 'None') {
+ return v1.index < v2.index ? -1 : 1
+ } else {
+ return -1
+ }
+ } else {
+ if (v2.value === 'You') {
+ return -1
+ } else if (v2.value === 'An Overleaf v1 User' || v2.value === 'None') {
+ return 1
+ } else {
+ return v1.value > v2.value ? -1 : 1
+ }
+ }
+ }
+
+ angular.element($window).bind('resize', function () {
+ recalculateProjectListHeight()
+ $scope.$apply()
+ })
+
+ $scope.$on('project-list:notifications-received', () =>
+ $scope.$applyAsync(() => recalculateProjectListHeight())
+ )
+
+ // Allow tags to be accessed on projects as well
+ const projectsById = {}
+ for (const project of $scope.projects) {
+ projectsById[project.id] = project
+ }
+
+ $scope.getProjectById = id => projectsById[id]
+
+ for (const tag of $scope.tags) {
+ for (const projectId of tag.project_ids || []) {
+ const project = projectsById[projectId]
+ if (project) {
+ if (!project.tags) {
+ project.tags = []
+ }
+ project.tags.push(tag)
+ }
+ }
+ }
+
+ $scope.changePredicate = function (newPredicate) {
+ if ($scope.predicate === newPredicate) {
+ $scope.reverse = !$scope.reverse
+ }
+ $scope.predicate = newPredicate
+ }
+
+ $scope.getSortIconClass = function (column) {
+ if (column === $scope.predicate && $scope.reverse) {
+ return 'fa-caret-down'
+ } else if (column === $scope.predicate && !$scope.reverse) {
+ return 'fa-caret-up'
+ } else {
+ return ''
+ }
+ }
+
+ $scope.searchProjects = function () {
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project-search',
+ 'keydown'
+ )
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.clearSearchText = function () {
+ $scope.searchText.value = ''
+ $scope.filter = 'all'
+ $scope.$emit('search:clear')
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.setFilter = function (filter) {
+ $scope.filter = filter
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.updateSelectedProjects = function () {
+ $scope.selectedProjects = $scope.projects.filter(
+ project => project.selected
+ )
+ }
+
+ $scope.getSelectedProjects = () => $scope.selectedProjects
+
+ $scope.getSelectedProjectIds = () =>
+ $scope.selectedProjects.map(project => project.id)
+
+ $scope.getFirstSelectedProject = () => $scope.selectedProjects[0]
+
+ $scope.hasLeavableProjectsSelected = () =>
+ _.some(
+ $scope.getSelectedProjects(),
+ project => project.accessLevel !== 'owner' && project.trashed
+ )
+
+ $scope.hasDeletableProjectsSelected = () =>
+ _.some(
+ $scope.getSelectedProjects(),
+ project => project.accessLevel === 'owner' && project.trashed
+ )
+
+ $scope.updateVisibleProjects = function () {
+ $scope.visibleProjects = []
+ const selectedTag = $scope.getSelectedTag()
+ for (const project of $scope.projects) {
+ let visible = true
+ // Only show if it matches any search text
+ if ($scope.searchText.value !== '') {
+ if (
+ project.name
+ .toLowerCase()
+ .indexOf($scope.searchText.value.toLowerCase()) === -1
+ ) {
+ visible = false
+ }
+ }
+ // Only show if it matches the selected tag
+ if (
+ $scope.filter === 'tag' &&
+ selectedTag != null &&
+ !selectedTag.project_ids.includes(project.id)
+ ) {
+ visible = false
+ }
+
+ // Hide tagged projects if we only want to see the uncategorized ones
+ if (
+ $scope.filter === 'untagged' &&
+ (project.tags != null ? project.tags.length : undefined) > 0
+ ) {
+ visible = false
+ }
+
+ // Hide projects we own if we only want to see shared projects
+ if ($scope.filter === 'shared' && project.accessLevel === 'owner') {
+ visible = false
+ }
+
+ // Hide projects we don't own if we only want to see owned projects
+ if ($scope.filter === 'owned' && project.accessLevel !== 'owner') {
+ visible = false
+ }
+
+ if ($scope.filter === 'archived') {
+ // Only show archived projects
+ if (!project.archived) {
+ visible = false
+ }
+ } else {
+ // Only show non-archived projects
+ if (project.archived) {
+ visible = false
+ }
+ }
+
+ if ($scope.filter === 'trashed') {
+ // Only show trashed projects
+ if (!project.trashed) {
+ visible = false
+ }
+ } else {
+ // Only show non-trashed projects
+ if (project.trashed) {
+ visible = false
+ }
+ }
+
+ if (visible) {
+ $scope.visibleProjects.push(project)
+ } else {
+ // We don't want hidden selections
+ project.selected = false
+ }
+ }
+
+ localStorage(
+ 'project_list',
+ JSON.stringify({
+ filter: $scope.filter,
+ selectedTagId: selectedTag != null ? selectedTag._id : undefined,
+ })
+ )
+ $scope.updateSelectedProjects()
+ }
+
+ $scope.getSelectedTag = function () {
+ for (const tag of $scope.tags) {
+ if (tag.selected) {
+ return tag
+ }
+ }
+ return null
+ }
+
+ $scope._removeProjectIdsFromTagArray = function (tag, removeProjectIds) {
+ // Remove project_id from tag.project_ids
+ const remainingProjectIds = []
+ const removedProjectIds = []
+ for (const projectId of tag.project_ids) {
+ if (!removeProjectIds.includes(projectId)) {
+ remainingProjectIds.push(projectId)
+ } else {
+ removedProjectIds.push(projectId)
+ }
+ }
+ tag.project_ids = remainingProjectIds
+ return removedProjectIds
+ }
+
+ $scope._removeProjectFromList = function (project) {
+ const index = $scope.projects.indexOf(project)
+ if (index > -1) {
+ $scope.projects.splice(index, 1)
+ }
+ }
+
+ $scope.removeSelectedProjectsFromTag = function (tag) {
+ tag.showWhenEmpty = true
+
+ const selectedProjectIds = $scope.getSelectedProjectIds()
+ const selectedProjects = $scope.getSelectedProjects()
+
+ const removedProjectIds = $scope._removeProjectIdsFromTagArray(
+ tag,
+ selectedProjectIds
+ )
+
+ // Remove tag from project.tags
+ for (const project of selectedProjects) {
+ if (!project.tags) {
+ project.tags = []
+ }
+ const index = project.tags.indexOf(tag)
+ if (index > -1) {
+ project.tags.splice(index, 1)
+ }
+ }
+
+ for (const projectId of removedProjectIds) {
+ queuedHttp({
+ method: 'DELETE',
+ url: `/tag/${tag._id}/project/${projectId}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ // If we're filtering by this tag then we need to remove
+ // the projects from view
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.removeProjectFromTag = function (project, tag) {
+ tag.showWhenEmpty = true
+
+ if (!project.tags) {
+ project.tags = []
+ }
+ const index = project.tags.indexOf(tag)
+
+ if (index > -1) {
+ $scope._removeProjectIdsFromTagArray(tag, [project.id])
+ project.tags.splice(index, 1)
+ queuedHttp({
+ method: 'DELETE',
+ url: `/tag/${tag._id}/project/${project.id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ $scope.updateVisibleProjects()
+ }
+ }
+
+ $scope.addSelectedProjectsToTag = function (tag) {
+ const selectedProjects = $scope.getSelectedProjects()
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project action',
+ 'addSelectedProjectsToTag'
+ )
+
+ // Add project_ids into tag.project_ids
+ const addedProjectIds = []
+ for (const projectId of $scope.getSelectedProjectIds()) {
+ if (!tag.project_ids.includes(projectId)) {
+ tag.project_ids.push(projectId)
+ addedProjectIds.push(projectId)
+ }
+ }
+
+ // Add tag into each project.tags
+ for (const project of selectedProjects) {
+ if (!project.tags) {
+ project.tags = []
+ }
+ if (!project.tags.includes(tag)) {
+ project.tags.push(tag)
+ }
+ }
+
+ for (const projectId of addedProjectIds) {
+ queuedHttp.post(`/tag/${tag._id}/project/${projectId}`, {
+ _csrf: window.csrfToken,
+ })
+ }
+ }
+
+ $scope.openNewTagModal = function (e) {
+ const modalInstance = $modal.open({
+ templateUrl: 'newTagModalTemplate',
+ controller: 'NewTagModalController',
+ })
+
+ modalInstance.result.then(function (tag) {
+ const tagIsDuplicate = $scope.tags.find(function (existingTag) {
+ return tag.name === existingTag.name
+ })
+
+ if (!tagIsDuplicate) {
+ $scope.tags.push(tag)
+ $scope.addSelectedProjectsToTag(tag)
+ }
+ })
+ }
+
+ $scope.createProject = function (name, template) {
+ if (template == null) {
+ template = 'none'
+ }
+ return queuedHttp
+ .post('/project/new', {
+ _csrf: window.csrfToken,
+ projectName: name,
+ template,
+ })
+ .then(function (response) {
+ const { data } = response
+ $scope.projects.push({
+ name,
+ id: data.project_id,
+ accessLevel: 'owner',
+ owner: data.owner,
+ // TODO: Check access level if correct after adding it in
+ // to the rest of the app
+ })
+ $scope.updateVisibleProjects()
+ })
+ }
+
+ $scope.openCreateProjectModal = function (template) {
+ if (template == null) {
+ template = 'none'
+ }
+ eventTracking.send('project-list-page-interaction', 'new-project', template)
+ const modalInstance = $modal.open({
+ templateUrl: 'newProjectModalTemplate',
+ controller: 'NewProjectModalController',
+ resolve: {
+ template() {
+ return template
+ },
+ },
+ scope: $scope,
+ })
+
+ modalInstance.result.then(
+ projectId => (window.location = `/project/${projectId}`)
+ )
+ }
+
+ $scope.renameProject = (project, newName) =>
+ queuedHttp
+ .post(`/project/${project.id}/rename`, {
+ newProjectName: newName,
+ _csrf: window.csrfToken,
+ })
+ .then(() => (project.name = newName))
+
+ $scope.openRenameProjectModal = function () {
+ const project = $scope.getFirstSelectedProject()
+ if (!project || project.accessLevel !== 'owner') {
+ return
+ }
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project action',
+ 'Rename'
+ )
+ $modal.open({
+ templateUrl: 'renameProjectModalTemplate',
+ controller: 'RenameProjectModalController',
+ resolve: {
+ project() {
+ return project
+ },
+ },
+ scope: $scope,
+ })
+ }
+
+ $scope.cloneProject = function (project, cloneName) {
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project action',
+ 'Clone'
+ )
+ return queuedHttp
+ .post(`/project/${project.id}/clone`, {
+ _csrf: window.csrfToken,
+ projectName: cloneName,
+ })
+ .then(function (response) {
+ const { data } = response
+ $scope.projects.push({
+ name: data.name,
+ id: data.project_id,
+ accessLevel: 'owner',
+ owner: data.owner,
+ // TODO: Check access level if correct after adding it in
+ // to the rest of the app
+ })
+ $scope.updateVisibleProjects()
+ })
+ }
+
+ $scope.openCloneProjectModal = function (project) {
+ if (!project) {
+ return
+ }
+
+ $modal.open({
+ templateUrl: 'cloneProjectModalTemplate',
+ controller: 'CloneProjectModalController',
+ resolve: {
+ project() {
+ return project
+ },
+ },
+ scope: $scope,
+ })
+ }
+
+ // Methods to create modals for archiving, trashing, leaving and deleting projects
+ const _createArchiveTrashLeaveOrDeleteProjectsModal = function (
+ action,
+ projects
+ ) {
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project action',
+ action
+ )
+ return $modal.open({
+ templateUrl: 'archiveTrashLeaveOrDeleteProjectsModalTemplate',
+ controller: 'ArchiveTrashLeaveOrDeleteProjectsModalController',
+ resolve: {
+ projects() {
+ return projects
+ },
+ action() {
+ return action
+ },
+ },
+ })
+ }
+
+ $scope.createArchiveProjectsModal = function (projects) {
+ return _createArchiveTrashLeaveOrDeleteProjectsModal('archive', projects)
+ }
+
+ $scope.createTrashProjectsModal = function (projects) {
+ return _createArchiveTrashLeaveOrDeleteProjectsModal('trash', projects)
+ }
+
+ $scope.createLeaveProjectsModal = function (projects) {
+ return _createArchiveTrashLeaveOrDeleteProjectsModal('leave', projects)
+ }
+
+ $scope.createDeleteProjectsModal = function (projects) {
+ return _createArchiveTrashLeaveOrDeleteProjectsModal('delete', projects)
+ }
+
+ $scope.createLeaveOrDeleteProjectsModal = function (projects) {
+ return _createArchiveTrashLeaveOrDeleteProjectsModal(
+ 'leaveOrDelete',
+ projects
+ )
+ }
+
+ //
+ $scope.openArchiveProjectsModal = function () {
+ const modalInstance = $scope.createArchiveProjectsModal(
+ $scope.getSelectedProjects()
+ )
+ modalInstance.result.then(() => $scope.archiveSelectedProjects())
+ }
+
+ $scope.openTrashProjectsModal = function () {
+ const modalInstance = $scope.createTrashProjectsModal(
+ $scope.getSelectedProjects()
+ )
+
+ modalInstance.result.then(() => $scope.trashSelectedProjects())
+ }
+
+ $scope.openLeaveProjectsModal = function () {
+ const modalInstance = $scope.createLeaveProjectsModal(
+ $scope.getSelectedProjects()
+ )
+ modalInstance.result.then(() => $scope.leaveSelectedProjects())
+ }
+
+ $scope.openDeleteProjectsModal = function () {
+ const modalInstance = $scope.createDeleteProjectsModal(
+ $scope.getSelectedProjects()
+ )
+ modalInstance.result.then(() => $scope.deleteSelectedProjects())
+ }
+
+ $scope.openLeaveOrDeleteProjectsModal = function () {
+ const modalInstance = $scope.createLeaveOrDeleteProjectsModal(
+ $scope.getSelectedProjects()
+ )
+ modalInstance.result.then(() => $scope.leaveOrDeleteSelectedProjects())
+ }
+
+ //
+ $scope.archiveSelectedProjects = () =>
+ $scope.archiveProjects($scope.getSelectedProjects())
+
+ $scope.unarchiveSelectedProjects = () =>
+ $scope.unarchiveProjects($scope.getSelectedProjects())
+
+ $scope.trashSelectedProjects = () =>
+ $scope.trashProjects($scope.getSelectedProjects())
+
+ $scope.untrashSelectedProjects = () =>
+ $scope.untrashProjects($scope.getSelectedProjects())
+
+ $scope.leaveSelectedProjects = () =>
+ $scope.leaveProjects($scope.getSelectedProjects())
+
+ $scope.deleteSelectedProjects = () =>
+ $scope.deleteProjects($scope.getSelectedProjects())
+
+ $scope.leaveOrDeleteSelectedProjects = () =>
+ $scope.leaveOrDeleteProjects($scope.getSelectedProjects())
+
+ //
+ $scope.archiveProjects = function (projects) {
+ for (const project of projects) {
+ project.archived = true
+ project.trashed = false
+ _archiveProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.unarchiveProjects = function (projects) {
+ for (const project of projects) {
+ project.archived = false
+ _unarchiveProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.trashProjects = function (projects) {
+ for (const project of projects) {
+ project.trashed = true
+ project.archived = false
+ _trashProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.untrashProjects = function (projects) {
+ for (const project of projects) {
+ project.trashed = false
+ _untrashProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.leaveProjects = function (projects) {
+ _deleteOrLeaveProjectsLocally(projects)
+ for (const project of projects) {
+ _leaveProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.deleteProjects = function (projects) {
+ _deleteOrLeaveProjectsLocally(projects)
+ for (const project of projects) {
+ _deleteProject(project)
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ $scope.leaveOrDeleteProjects = function (projects) {
+ _deleteOrLeaveProjectsLocally(projects)
+ for (const project of projects) {
+ if (project.accessLevel === 'owner') {
+ _deleteProject(project)
+ } else {
+ _leaveProject(project)
+ }
+ }
+ $scope.updateVisibleProjects()
+ }
+
+ // Actual interaction with the backend---we could move this into a service
+ const _archiveProject = function (project) {
+ return queuedHttp({
+ method: 'POST',
+ url: `/project/${project.id}/archive`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _unarchiveProject = function (project) {
+ return queuedHttp({
+ method: 'DELETE',
+ url: `/project/${project.id}/archive`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _trashProject = function (project) {
+ return queuedHttp({
+ method: 'POST',
+ url: `/project/${project.id}/trash`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _untrashProject = function (project) {
+ return queuedHttp({
+ method: 'DELETE',
+ url: `/project/${project.id}/trash`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _leaveProject = function (project) {
+ return queuedHttp({
+ method: 'POST',
+ url: `/project/${project.id}/leave`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _deleteProject = function (project) {
+ return queuedHttp({
+ method: 'DELETE',
+ url: `/project/${project.id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ }
+
+ const _deleteOrLeaveProjectsLocally = function (projects) {
+ const projectIds = projects.map(p => p.id)
+ for (const tag of $scope.tags || []) {
+ $scope._removeProjectIdsFromTagArray(tag, projectIds)
+ }
+ for (const project of projects || []) {
+ $scope._removeProjectFromList(project)
+ }
+ }
+
+ $scope.getValueForCurrentPredicate = function (project) {
+ if ($scope.predicate === 'ownerName') {
+ return ProjectListService.getOwnerName(project)
+ } else {
+ return project[$scope.predicate]
+ }
+ }
+
+ $scope.openUploadProjectModal = function () {
+ $modal.open({
+ templateUrl: 'uploadProjectModalTemplate',
+ controller: 'UploadProjectModalController',
+ })
+ }
+
+ $scope.downloadSelectedProjects = () =>
+ $scope.downloadProjectsById($scope.getSelectedProjectIds())
+
+ $scope.downloadProjectsById = function (projectIds) {
+ let path
+ eventTracking.send(
+ 'project-list-page-interaction',
+ 'project action',
+ 'Download Zip'
+ )
+ if (projectIds.length > 1) {
+ path = `/project/download/zip?project_ids=${projectIds.join(',')}`
+ } else {
+ path = `/project/${projectIds[0]}/download/zip`
+ }
+ return (window.location = path)
+ }
+
+ const markTagAsSelected = id => {
+ for (const tag of $scope.tags) {
+ if (tag._id === id) {
+ tag.selected = true
+ } else {
+ tag.selected = false
+ }
+ }
+ }
+
+ const storedUIOpts = JSON.parse(localStorage('project_list'))
+
+ if (storedUIOpts && storedUIOpts.filter) {
+ if (storedUIOpts.filter === 'tag' && storedUIOpts.selectedTagId) {
+ markTagAsSelected(storedUIOpts.selectedTagId)
+ }
+ $scope.setFilter(storedUIOpts.filter)
+ } else {
+ $scope.updateVisibleProjects()
+ }
+})
+
+App.controller(
+ 'ProjectListItemController',
+ function ($scope, $modal, queuedHttp, ProjectListService) {
+ $scope.projectLink = function (project) {
+ return `/project/${project.id}`
+ }
+
+ $scope.isLinkSharingProject = project => project.source === 'token'
+
+ $scope.hasGenericOwnerName = () => {
+ /* eslint-disable camelcase */
+ const { first_name, last_name, email } = $scope.project.owner
+ return !first_name && !last_name && !email
+ /* eslint-enable camelcase */
+ }
+
+ $scope.getOwnerName = ProjectListService.getOwnerName
+
+ $scope.getUserName = ProjectListService.getUserName
+
+ $scope.isOwner = () =>
+ $scope.project.owner && window.user_id === $scope.project.owner._id
+
+ $scope.$watch('project.selected', function (value) {
+ if (value != null) {
+ $scope.updateSelectedProjects()
+ }
+ })
+
+ $scope.clone = function (e) {
+ e.stopPropagation()
+ $scope.openCloneProjectModal($scope.project)
+ }
+
+ $scope.download = function (e) {
+ e.stopPropagation()
+ $scope.downloadProjectsById([$scope.project.id])
+ }
+
+ $scope.archive = function (e) {
+ e.stopPropagation()
+ $scope.createArchiveProjectsModal([$scope.project]).result.then(() => {
+ $scope.archiveProjects([$scope.project])
+ })
+ }
+
+ $scope.unarchive = function (e) {
+ e.stopPropagation()
+ $scope.unarchiveProjects([$scope.project])
+ }
+
+ $scope.trash = function (e) {
+ e.stopPropagation()
+ $scope.createTrashProjectsModal([$scope.project]).result.then(() => {
+ $scope.trashProjects([$scope.project])
+ })
+ }
+
+ $scope.untrash = function (e) {
+ e.stopPropagation()
+ $scope.untrashProjects([$scope.project])
+ }
+
+ $scope.leave = function (e) {
+ e.stopPropagation()
+ $scope.createLeaveProjectsModal([$scope.project]).result.then(() => {
+ $scope.leaveProjects([$scope.project])
+ })
+ }
+
+ $scope.delete = function (e) {
+ e.stopPropagation()
+ $scope.createDeleteProjectsModal([$scope.project]).result.then(() => {
+ $scope.deleteProjects([$scope.project])
+ })
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/project-list/services/project-list.js b/services/web/frontend/js/main/project-list/services/project-list.js
new file mode 100644
index 0000000000..df74fede70
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/services/project-list.js
@@ -0,0 +1,35 @@
+/* eslint-disable
+ camelcase
+*/
+import App from '../../../base'
+
+export default App.service('ProjectListService', function () {
+ return {
+ getOwnerName(project) {
+ if (project.accessLevel === 'owner') {
+ return 'You'
+ } else if (project.owner != null) {
+ return this.getUserName(project.owner)
+ } else {
+ return 'None'
+ }
+ },
+
+ getUserName(user) {
+ if (user && user._id === window.user_id) {
+ return 'You'
+ } else if (user) {
+ const { first_name, last_name, email } = user
+ if (first_name || last_name) {
+ return [first_name, last_name].filter(n => n != null).join(' ')
+ } else if (email) {
+ return email
+ } else {
+ return 'An Overleaf v1 User'
+ }
+ } else {
+ return 'None'
+ }
+ },
+ }
+})
diff --git a/services/web/frontend/js/main/project-list/tag-controllers.js b/services/web/frontend/js/main/project-list/tag-controllers.js
new file mode 100644
index 0000000000..a2a825fcc1
--- /dev/null
+++ b/services/web/frontend/js/main/project-list/tag-controllers.js
@@ -0,0 +1,226 @@
+import App from '../../base'
+import ColorManager from '../../ide/colors/ColorManager'
+App.controller('TagListController', function ($scope, $modal) {
+ $scope.filterProjects = function (filter = 'all') {
+ $scope._clearTags()
+ $scope.setFilter(filter)
+ }
+
+ $scope._clearTags = () =>
+ $scope.tags.forEach(tag => {
+ tag.selected = false
+ })
+
+ $scope.selectTag = function (tag) {
+ $scope._clearTags()
+ tag.selected = true
+ $scope.setFilter('tag')
+ }
+
+ $scope.selectUntagged = function () {
+ $scope._clearTags()
+ $scope.setFilter('untagged')
+ }
+
+ $scope.countProjectsForTag = function (tag) {
+ return tag.project_ids.reduce((acc, projectId) => {
+ const project = $scope.getProjectById(projectId)
+
+ // There is a bug where the tag is not cleaned up when you leave a
+ // project, so tag.project_ids can contain a project that the user can
+ // no longer access. If the project cannot be found, ignore it
+ if (!project) return acc
+
+ // Ignore archived projects as they are not shown in the filter
+ if (!(project.archived || project.trashed)) {
+ return acc + 1
+ } else {
+ return acc
+ }
+ }, 0)
+ }
+
+ $scope.getHueForTagId = tagId => ColorManager.getHueForTagId(tagId)
+
+ $scope.deleteTag = function (tag) {
+ const modalInstance = $modal.open({
+ templateUrl: 'deleteTagModalTemplate',
+ controller: 'DeleteTagModalController',
+ resolve: {
+ tag() {
+ return tag
+ },
+ },
+ })
+ modalInstance.result.then(function () {
+ // Remove tag from projects
+ for (const project of $scope.projects) {
+ if (!project.tags) {
+ project.tags = []
+ }
+ const index = project.tags.indexOf(tag)
+ if (index > -1) {
+ project.tags.splice(index, 1)
+ }
+ }
+
+ // Remove tag in place to update the state everywhere
+ $scope.tags.splice($scope.tags.indexOf(tag), 1)
+ })
+ }
+
+ $scope.renameTag = function (tag) {
+ const modalInstance = $modal.open({
+ templateUrl: 'renameTagModalTemplate',
+ controller: 'RenameTagModalController',
+ resolve: {
+ tag() {
+ return tag
+ },
+ },
+ })
+ modalInstance.result.then(newName => (tag.name = newName))
+ }
+})
+
+App.controller('TagDropdownItemController', function ($scope) {
+ $scope.recalculateProjectsInTag = function () {
+ let partialSelection
+ $scope.areSelectedProjectsInTag = false
+ for (const projectId of $scope.getSelectedProjectIds()) {
+ if ($scope.tag.project_ids.includes(projectId)) {
+ $scope.areSelectedProjectsInTag = true
+ } else {
+ partialSelection = true
+ }
+ }
+
+ if ($scope.areSelectedProjectsInTag && partialSelection) {
+ $scope.areSelectedProjectsInTag = 'partial'
+ }
+ }
+
+ $scope.addOrRemoveProjectsFromTag = function () {
+ if ($scope.areSelectedProjectsInTag === true) {
+ $scope.removeSelectedProjectsFromTag($scope.tag)
+ $scope.areSelectedProjectsInTag = false
+ } else if (
+ $scope.areSelectedProjectsInTag === false ||
+ $scope.areSelectedProjectsInTag === 'partial'
+ ) {
+ $scope.addSelectedProjectsToTag($scope.tag)
+ $scope.areSelectedProjectsInTag = true
+ }
+ }
+
+ $scope.$watch('selectedProjects', () => $scope.recalculateProjectsInTag())
+ $scope.recalculateProjectsInTag()
+})
+
+App.controller(
+ 'NewTagModalController',
+ function ($scope, $modalInstance, $timeout, $http) {
+ $scope.inputs = { newTagName: '' }
+
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.create = function () {
+ const name = $scope.inputs.newTagName
+ $scope.state.inflight = true
+ $scope.state.error = false
+ $http
+ .post('/tag', {
+ _csrf: window.csrfToken,
+ name,
+ })
+ .then(function (response) {
+ const { data } = response
+ $scope.state.inflight = false
+ $modalInstance.close(data)
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
+
+App.controller(
+ 'RenameTagModalController',
+ function ($scope, $modalInstance, $timeout, $http, tag) {
+ $scope.inputs = { tagName: tag.name }
+
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.rename = function () {
+ const name = $scope.inputs.tagName
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $http
+ .post(`/tag/${tag._id}/rename`, {
+ _csrf: window.csrfToken,
+ name,
+ })
+ .then(function () {
+ $scope.state.inflight = false
+ $modalInstance.close(name)
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
+
+export default App.controller(
+ 'DeleteTagModalController',
+ function ($scope, $modalInstance, $http, tag) {
+ $scope.tag = tag
+ $scope.state = {
+ inflight: false,
+ error: false,
+ }
+
+ $scope.delete = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $http({
+ method: 'DELETE',
+ url: `/tag/${tag._id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ })
+ .then(function () {
+ $scope.state.inflight = false
+ $modalInstance.close()
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
diff --git a/services/web/frontend/js/main/register-users.js b/services/web/frontend/js/main/register-users.js
new file mode 100644
index 0000000000..d7e2296768
--- /dev/null
+++ b/services/web/frontend/js/main/register-users.js
@@ -0,0 +1,50 @@
+import _ from 'lodash'
+/* eslint-disable
+ max-len,
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+
+export default App.controller(
+ 'RegisterUsersController',
+ function ($scope, queuedHttp) {
+ $scope.users = []
+
+ $scope.inputs = { emails: '' }
+
+ const parseEmails = function (emailsString) {
+ const regexBySpaceOrComma = /[\s,]+/
+ let emails = emailsString.split(regexBySpaceOrComma)
+ emails = _.map(emails, email => (email = email.trim()))
+ emails = _.filter(emails, email => email.indexOf('@') !== -1)
+ return emails
+ }
+
+ return ($scope.registerUsers = function () {
+ const emails = parseEmails($scope.inputs.emails)
+ $scope.error = false
+ return Array.from(emails).map(email =>
+ queuedHttp
+ .post('/admin/register', {
+ email,
+ _csrf: window.csrfToken,
+ })
+ .then(function (response) {
+ const { data } = response
+ const user = data
+ $scope.users.push(user)
+ return ($scope.inputs.emails = '')
+ })
+ .catch(() => ($scope.error = true))
+ )
+ })
+ }
+)
diff --git a/services/web/frontend/js/main/scribtex-popup.js b/services/web/frontend/js/main/scribtex-popup.js
new file mode 100644
index 0000000000..52e4c4aa70
--- /dev/null
+++ b/services/web/frontend/js/main/scribtex-popup.js
@@ -0,0 +1,14 @@
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+
+export default App.controller('ScribtexPopupController', ($scope, $modal) =>
+ $modal.open({
+ templateUrl: 'scribtexModalTemplate',
+ })
+)
diff --git a/services/web/frontend/js/main/subscription-dashboard.js b/services/web/frontend/js/main/subscription-dashboard.js
new file mode 100644
index 0000000000..2984f060b9
--- /dev/null
+++ b/services/web/frontend/js/main/subscription-dashboard.js
@@ -0,0 +1,312 @@
+import _ from 'lodash'
+/* global recurly */
+
+/* eslint-disable
+ camelcase,
+ max-len,
+ no-return-assign,
+ no-unused-vars,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS104: Avoid inline assignments
+ * DS204: Change includes calls to have a more natural evaluation order
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+import getMeta from '../utils/meta'
+const SUBSCRIPTION_URL = '/user/subscription/update'
+
+const ensureRecurlyIsSetup = _.once(() => {
+ if (typeof recurly === 'undefined' || !recurly) {
+ return false
+ }
+ recurly.configure(getMeta('ol-recurlyApiKey'))
+ return true
+})
+
+App.controller('MetricsEmailController', function ($scope, $http) {
+ $scope.institutionEmailSubscription = function (institutionId) {
+ var inst = _.find(window.managedInstitutions, function (institution) {
+ return institution.v1Id === parseInt(institutionId)
+ })
+ if (inst.metricsEmail.optedOutUserIds.includes(window.user_id)) {
+ return 'Subscribe'
+ } else {
+ return 'Unsubscribe'
+ }
+ }
+
+ $scope.changeInstitutionalEmailSubscription = function (institutionId) {
+ $scope.subscriptionChanging = true
+ return $http({
+ method: 'POST',
+ url: `/institutions/${institutionId}/emailSubscription`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ }).then(function successCallback(response) {
+ window.managedInstitutions = _.map(
+ window.managedInstitutions,
+ function (institution) {
+ if (institution.v1Id === parseInt(institutionId)) {
+ institution.metricsEmail.optedOutUserIds = response.data
+ }
+ return institution
+ }
+ )
+ $scope.subscriptionChanging = false
+ })
+ }
+})
+
+App.factory('RecurlyPricing', function ($q, MultiCurrencyPricing) {
+ return {
+ loadDisplayPriceWithTax: function (planCode, currency, taxRate) {
+ if (!ensureRecurlyIsSetup()) return
+ const currencySymbol = MultiCurrencyPricing.plans[currency].symbol
+ const pricing = recurly.Pricing()
+ return $q(function (resolve, reject) {
+ pricing
+ .plan(planCode, { quantity: 1 })
+ .currency(currency)
+ .done(function (price) {
+ const totalPriceExTax = parseFloat(price.next.total)
+ let taxAmmount = totalPriceExTax * taxRate
+ if (isNaN(taxAmmount)) {
+ taxAmmount = 0
+ }
+ let total = totalPriceExTax + taxAmmount
+ if (total % 1 !== 0) {
+ total = total.toFixed(2)
+ }
+ resolve(`${currencySymbol}${total}`)
+ })
+ })
+ },
+ }
+})
+
+App.controller(
+ 'ChangePlanFormController',
+ function ($scope, $modal, RecurlyPricing) {
+ if (!ensureRecurlyIsSetup()) return
+
+ $scope.changePlan = () =>
+ $modal.open({
+ templateUrl: 'confirmChangePlanModalTemplate',
+ controller: 'ConfirmChangePlanController',
+ scope: $scope,
+ })
+
+ $scope.cancelPendingPlanChange = () =>
+ $modal.open({
+ templateUrl: 'cancelPendingPlanChangeModalTemplate',
+ controller: 'CancelPendingPlanChangeController',
+ scope: $scope,
+ })
+
+ $scope.$watch('plan', function (plan) {
+ if (!plan) return
+ const planCodesChangingAtTermEnd = getMeta(
+ 'ol-planCodesChangingAtTermEnd'
+ )
+ $scope.planChangesAtTermEnd = false
+ if (
+ planCodesChangingAtTermEnd &&
+ planCodesChangingAtTermEnd.indexOf(plan.planCode) > -1
+ ) {
+ $scope.planChangesAtTermEnd = true
+ }
+ const planCode = plan.planCode
+ const subscription = getMeta('ol-subscription')
+ const { currency, taxRate } = subscription.recurly
+ $scope.price = '...' // Placeholder while we talk to recurly
+ RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
+ price => {
+ $scope.price = price
+ }
+ )
+ })
+ }
+)
+
+App.controller(
+ 'ConfirmChangePlanController',
+ function ($scope, $modalInstance, $http) {
+ $scope.confirmChangePlan = function () {
+ const body = {
+ plan_code: $scope.plan.planCode,
+ _csrf: window.csrfToken,
+ }
+
+ $scope.genericError = false
+ $scope.inflight = true
+
+ return $http
+ .post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
+ .then(() => location.reload())
+ .catch(() => {
+ $scope.genericError = true
+ $scope.inflight = false
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'CancelPendingPlanChangeController',
+ function ($scope, $modalInstance, $http) {
+ $scope.confirmCancelPendingPlanChange = function () {
+ const body = {
+ _csrf: window.csrfToken,
+ }
+
+ $scope.genericError = false
+ $scope.inflight = true
+
+ return $http
+ .post('/user/subscription/cancel-pending', body)
+ .then(() => location.reload())
+ .catch(() => {
+ $scope.genericError = true
+ $scope.inflight = false
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'LeaveGroupModalController',
+ function ($scope, $modalInstance, $http) {
+ $scope.confirmLeaveGroup = function () {
+ $scope.inflight = true
+ return $http({
+ url: '/subscription/group/user',
+ method: 'DELETE',
+ params: {
+ subscriptionId: $scope.subscriptionId,
+ _csrf: window.csrfToken,
+ },
+ })
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller('GroupMembershipController', function ($scope, $modal) {
+ $scope.removeSelfFromGroup = function (subscriptionId) {
+ $scope.subscriptionId = subscriptionId
+ return $modal.open({
+ templateUrl: 'LeaveGroupModalTemplate',
+ controller: 'LeaveGroupModalController',
+ scope: $scope,
+ })
+ }
+})
+
+App.controller('RecurlySubscriptionController', function ($scope) {
+ const recurlyIsSetup = ensureRecurlyIsSetup()
+ const subscription = getMeta('ol-subscription')
+ $scope.showChangePlanButton = recurlyIsSetup && !subscription.groupPlan
+ if (
+ window.subscription.recurly.account.has_past_due_invoice &&
+ window.subscription.recurly.account.has_past_due_invoice._ === 'true'
+ ) {
+ $scope.showChangePlanButton = false
+ }
+ $scope.recurlyLoadError = !recurlyIsSetup
+
+ $scope.switchToDefaultView = () => {
+ $scope.showCancellation = false
+ $scope.showChangePlan = false
+ }
+ $scope.switchToDefaultView()
+
+ $scope.switchToCancellationView = () => {
+ $scope.showCancellation = true
+ $scope.showChangePlan = false
+ }
+
+ $scope.switchToChangePlanView = () => {
+ $scope.showCancellation = false
+ $scope.showChangePlan = true
+ }
+})
+
+App.controller(
+ 'RecurlyCancellationController',
+ function ($scope, RecurlyPricing, $http) {
+ if (!ensureRecurlyIsSetup()) return
+ const subscription = getMeta('ol-subscription')
+ const sevenDaysTime = new Date()
+ sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
+ const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
+ const freeTrialInFuture = freeTrialEndDate > new Date()
+ const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
+
+ const isMonthlyCollab =
+ subscription.plan.planCode.indexOf('collaborator') !== -1 &&
+ subscription.plan.planCode.indexOf('ann') === -1 &&
+ !subscription.groupPlan
+ const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
+
+ if (isMonthlyCollab && stillInFreeTrial) {
+ $scope.showExtendFreeTrial = true
+ } else if (isMonthlyCollab && !stillInFreeTrial) {
+ $scope.showDowngradeToStudent = true
+ } else {
+ $scope.showBasicCancel = true
+ }
+
+ const { currency, taxRate } = subscription.recurly
+ $scope.studentPrice = '...' // Placeholder while we talk to recurly
+ RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
+ price => {
+ $scope.studentPrice = price
+ }
+ )
+
+ $scope.downgradeToStudent = function () {
+ const body = {
+ plan_code: 'student',
+ _csrf: window.csrfToken,
+ }
+ $scope.inflight = true
+ return $http
+ .post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
+
+ $scope.cancelSubscription = function () {
+ const body = { _csrf: window.csrfToken }
+
+ $scope.inflight = true
+ return $http
+ .post('/user/subscription/cancel', body)
+ .then(() => (location.href = '/user/subscription/canceled'))
+ .catch(() => console.log('something went wrong changing plan'))
+ }
+
+ $scope.extendTrial = function () {
+ const body = { _csrf: window.csrfToken }
+ $scope.inflight = true
+ return $http
+ .put('/user/subscription/extend', body)
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/subscription/team-invite-controller.js b/services/web/frontend/js/main/subscription/team-invite-controller.js
new file mode 100644
index 0000000000..11d7ec14bb
--- /dev/null
+++ b/services/web/frontend/js/main/subscription/team-invite-controller.js
@@ -0,0 +1,62 @@
+/* eslint-disable
+ max-len,
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../../base'
+import getMeta from '../../utils/meta'
+
+export default App.controller('TeamInviteController', function ($scope, $http) {
+ $scope.inflight = false
+ const hasIndividualRecurlySubscription = getMeta(
+ 'ol-hasIndividualRecurlySubscription'
+ )
+
+ if (hasIndividualRecurlySubscription) {
+ $scope.view = 'hasIndividualRecurlySubscription'
+ } else {
+ $scope.view = 'teamInvite'
+ }
+
+ $scope.keepPersonalSubscription = () => ($scope.view = 'teamInvite')
+
+ $scope.cancelPersonalSubscription = function () {
+ $scope.inflight = true
+ const request = $http.post('/user/subscription/cancel', {
+ _csrf: window.csrfToken,
+ })
+ request.then(function () {
+ $scope.inflight = false
+ return ($scope.view = 'teamInvite')
+ })
+ return request.catch(() => {
+ $scope.inflight = false
+ $scope.cancel_error = true
+ console.log('the request failed')
+ })
+ }
+
+ return ($scope.joinTeam = function () {
+ $scope.inflight = true
+ const inviteToken = getMeta('ol-inviteToken')
+ const request = $http.put(`/subscription/invites/${inviteToken}/`, {
+ _csrf: window.csrfToken,
+ })
+ request.then(function (response) {
+ const { status } = response
+ $scope.inflight = false
+ $scope.view = 'inviteAccepted'
+ if (status !== 200) {
+ // assume request worked
+ return ($scope.requestSent = false)
+ }
+ })
+ return request.catch(() => console.log('the request failed'))
+ })
+})
diff --git a/services/web/frontend/js/main/subscription/upgrade-subscription.js b/services/web/frontend/js/main/subscription/upgrade-subscription.js
new file mode 100644
index 0000000000..40a7d76386
--- /dev/null
+++ b/services/web/frontend/js/main/subscription/upgrade-subscription.js
@@ -0,0 +1,11 @@
+import App from '../../base'
+
+export default App.controller(
+ 'UpgradeSubscriptionController',
+ function ($scope, eventTracking) {
+ $scope.upgradeSubscription = function () {
+ eventTracking.send('subscription-funnel', 'subscription-page', 'upgrade')
+ eventTracking.sendMB('subscription-page-upgrade-button-click')
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/system-messages.js b/services/web/frontend/js/main/system-messages.js
new file mode 100644
index 0000000000..1c7d9be1d7
--- /dev/null
+++ b/services/web/frontend/js/main/system-messages.js
@@ -0,0 +1,59 @@
+/* eslint-disable
+ max-len,
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+const MESSAGE_POLL_INTERVAL = 15 * 60 * 1000
+// Controller for messages (array)
+App.controller('SystemMessagesController', ($http, $scope) => {
+ $scope.messages = []
+ var pollSystemMessages = function () {
+ // Ignore polling if tab is hidden or browser is offline
+ if (document.hidden || !navigator.onLine) {
+ return
+ }
+
+ $http
+ .get('/system/messages')
+ .then(response => {
+ // Ignore if content-type is anything but JSON, prevents a bug where
+ // the user logs out in another tab, then a 302 redirect was returned,
+ // which is transparently resolved by the browser to the login (HTML)
+ // page.
+ // This then caused an Angular error where it was attempting to loop
+ // through the HTML as a string
+ if (response.headers('content-type').includes('json')) {
+ $scope.messages = response.data
+ }
+ })
+ .catch(() => {
+ // ignore errors
+ })
+ }
+ pollSystemMessages()
+ setInterval(pollSystemMessages, MESSAGE_POLL_INTERVAL)
+})
+
+export default App.controller(
+ 'SystemMessageController',
+ function ($scope, $sce) {
+ $scope.hidden = $.localStorage(`systemMessage.hide.${$scope.message._id}`)
+ $scope.protected = $scope.message._id === 'protected'
+ $scope.htmlContent = $scope.message.content
+
+ return ($scope.hide = function () {
+ if (!$scope.protected) {
+ // do not allow protected messages to be hidden
+ $scope.hidden = true
+ return $.localStorage(`systemMessage.hide.${$scope.message._id}`, true)
+ }
+ })
+ }
+)
diff --git a/services/web/frontend/js/main/token-access.js b/services/web/frontend/js/main/token-access.js
new file mode 100644
index 0000000000..0d9cd9a343
--- /dev/null
+++ b/services/web/frontend/js/main/token-access.js
@@ -0,0 +1,78 @@
+import App from '../base'
+App.controller(
+ 'TokenAccessPageController',
+ ($scope, $http, $location, localStorage) => {
+ window.S = $scope
+ $scope.mode = 'accessAttempt' // 'accessAttempt' | 'v1Import'
+
+ $scope.v1ImportData = null
+
+ $scope.accessInFlight = false
+ $scope.accessSuccess = false
+ $scope.accessError = false
+
+ $scope.currentPath = () => {
+ return $location.path()
+ }
+
+ $scope.buildZipDownloadPath = projectId => {
+ return `/overleaf/project/${projectId}/download/zip`
+ }
+
+ $scope.getProjectName = () => {
+ if (!$scope.v1ImportData || !$scope.v1ImportData.name) {
+ return 'This project'
+ } else {
+ return $scope.v1ImportData.name
+ }
+ }
+
+ $scope.post = () => {
+ $scope.mode = 'accessAttempt'
+ const textData = $('#overleaf-token-access-data').text()
+ const parsedData = JSON.parse(textData)
+ const { postUrl, csrfToken } = parsedData
+ $scope.accessInFlight = true
+
+ $http({
+ method: 'POST',
+ url: postUrl,
+ data: {
+ _csrf: csrfToken,
+ },
+ }).then(
+ function successCallback(response) {
+ $scope.accessInFlight = false
+ $scope.accessError = false
+ const { data } = response
+ if (data.redirect) {
+ const redirect = response.data.redirect
+ if (!redirect) {
+ console.warn(
+ 'no redirect supplied in success response data',
+ response
+ )
+ $scope.accessError = true
+ return
+ }
+ window.location.replace(redirect)
+ } else if (data.v1Import) {
+ $scope.mode = 'v1Import'
+ $scope.v1ImportData = data.v1Import
+ } else {
+ console.warn(
+ 'invalid data from server in success response',
+ response
+ )
+ $scope.accessError = true
+ }
+ },
+ function errorCallback(response) {
+ console.warn('error response from server', response)
+ $scope.accessInFlight = false
+ $scope.accessError = response.status === 404 ? 'not_found' : 'error'
+ }
+ )
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/translations.js b/services/web/frontend/js/main/translations.js
new file mode 100644
index 0000000000..d790f890d0
--- /dev/null
+++ b/services/web/frontend/js/main/translations.js
@@ -0,0 +1,32 @@
+import App from '../base'
+
+App.controller(
+ 'TranslationsPopupController',
+ function ($scope, ipCookie, localStorage) {
+ function getStoredDismissal() {
+ const localStore = localStorage('hide-i18n-notification')
+
+ if (localStore === null) {
+ // Not stored in localStorage, check cookie
+ const cookieStore = ipCookie('hidei18nNotification')
+
+ // If stored in cookie, set on localStorage for forwards compat
+ if (cookieStore) {
+ localStorage('hide-i18n-notification', cookieStore)
+ ipCookie.remove('hidei18nNotification')
+ }
+
+ return cookieStore
+ }
+
+ return localStore
+ }
+
+ $scope.hidei18nNotification = getStoredDismissal()
+
+ $scope.dismiss = function () {
+ localStorage('hide-i18n-notification', true)
+ $scope.hidei18nNotification = true
+ }
+ }
+)
diff --git a/services/web/frontend/js/main/user-membership.js b/services/web/frontend/js/main/user-membership.js
new file mode 100644
index 0000000000..ff521f4e13
--- /dev/null
+++ b/services/web/frontend/js/main/user-membership.js
@@ -0,0 +1,121 @@
+import _ from 'lodash'
+/* eslint-disable
+ max-len,
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+App.controller('UserMembershipController', function ($scope, queuedHttp) {
+ $scope.users = window.users
+ $scope.groupSize = window.groupSize
+ $scope.paths = window.paths
+ $scope.selectedUsers = []
+
+ $scope.inputs = {
+ addMembers: {
+ content: '',
+ error: false,
+ errorMessage: null,
+ inflightCount: 0,
+ },
+ removeMembers: {
+ error: false,
+ errorMessage: null,
+ },
+ }
+
+ const parseEmails = function (emailsString) {
+ const regexBySpaceOrComma = /[\s,]+/
+ let emails = emailsString.split(regexBySpaceOrComma)
+ emails = _.map(emails, email => (email = email.trim()))
+ emails = _.filter(emails, email => email.indexOf('@') !== -1)
+ return emails
+ }
+
+ $scope.addMembers = function () {
+ $scope.inputs.addMembers.error = false
+ $scope.inputs.addMembers.errorMessage = null
+ $scope.inputs.addMembers.inflightCount = 0
+ const emails = parseEmails($scope.inputs.addMembers.content)
+ return Array.from(emails).map(email => {
+ $scope.inputs.addMembers.inflightCount += 1
+ return queuedHttp
+ .post(window.paths.addMember, {
+ email,
+ _csrf: window.csrfToken,
+ })
+ .then(function (response) {
+ $scope.inputs.addMembers.inflightCount -= 1
+ const { data } = response
+ if (data.user != null) {
+ $scope.users.push(data.user)
+ }
+ return ($scope.inputs.addMembers.content = '')
+ })
+ .catch(function (response) {
+ $scope.inputs.addMembers.inflightCount -= 1
+ const { data } = response
+ $scope.inputs.addMembers.error = true
+ return ($scope.inputs.addMembers.errorMessage =
+ data.error != null ? data.error.message : undefined)
+ })
+ })
+ }
+
+ $scope.removeMembers = function () {
+ $scope.inputs.removeMembers.error = false
+ $scope.inputs.removeMembers.errorMessage = null
+ for (const user of Array.from($scope.selectedUsers)) {
+ ;(function (user) {
+ let url
+ if (window.paths.removeInvite && user.invite && user._id == null) {
+ url = `${window.paths.removeInvite}/${encodeURIComponent(user.email)}`
+ } else if (window.paths.removeMember && user._id != null) {
+ url = `${window.paths.removeMember}/${user._id}`
+ } else {
+ return
+ }
+ return queuedHttp({
+ method: 'DELETE',
+ url,
+ headers: {
+ 'X-Csrf-Token': window.csrfToken,
+ },
+ })
+ .then(function () {
+ const index = $scope.users.indexOf(user)
+ if (index === -1) {
+ return
+ }
+ return $scope.users.splice(index, 1)
+ })
+ .catch(function (response) {
+ const { data } = response
+ $scope.inputs.removeMembers.error = true
+ return ($scope.inputs.removeMembers.errorMessage =
+ data.error != null ? data.error.message : undefined)
+ })
+ })(user)
+ }
+ return $scope.updateSelectedUsers
+ }
+
+ return ($scope.updateSelectedUsers = () =>
+ ($scope.selectedUsers = $scope.users.filter(user => user.selected)))
+})
+
+export default App.controller('UserMembershipListItemController', $scope =>
+ $scope.$watch('user.selected', function (value) {
+ if (value != null) {
+ return $scope.updateSelectedUsers()
+ }
+ })
+)
diff --git a/services/web/frontend/js/modules/errorCatcher.js b/services/web/frontend/js/modules/errorCatcher.js
new file mode 100644
index 0000000000..2f94ecc728
--- /dev/null
+++ b/services/web/frontend/js/modules/errorCatcher.js
@@ -0,0 +1,74 @@
+/* eslint-disable
+ max-len,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import { captureException } from '../infrastructure/error-reporter'
+
+const app = angular.module('ErrorCatcher', [])
+const UNHANDLED_REJECTION_ERR_MSG = 'Possibly unhandled rejection: canceled'
+
+app.config([
+ '$provide',
+ $provide =>
+ $provide.decorator('$exceptionHandler', [
+ '$log',
+ '$delegate',
+ ($log, $delegate) =>
+ function (exception, cause) {
+ if (
+ exception === UNHANDLED_REJECTION_ERR_MSG &&
+ cause === undefined
+ ) {
+ return
+ }
+
+ captureException(exception, scope => {
+ scope.setTag('handler', 'angular-exception-handler')
+ return scope
+ })
+
+ return $delegate(exception, cause)
+ },
+ ]),
+])
+
+// Interceptor to check auth failures in all $http requests
+// http://bahmutov.calepin.co/catch-all-errors-in-angular-app.html
+
+app.factory('unAuthHttpResponseInterceptor', ($q, $location) => ({
+ responseError(response) {
+ // redirect any unauthorised or forbidden responses back to /login
+ //
+ // set disableAutoLoginRedirect:true in the http request config
+ // to disable this behaviour
+ if (
+ [401, 403].includes(response.status) &&
+ !(response.config != null
+ ? response.config.disableAutoLoginRedirect
+ : undefined)
+ ) {
+ // for /project urls set the ?redir parameter to come back here
+ // otherwise just go to the login page
+ if (window.location.pathname.match(/^\/project/)) {
+ window.location = `/login?redir=${encodeURI(window.location.pathname)}`
+ } else {
+ window.location = '/login'
+ }
+ }
+ // pass the response back to the original requester
+ return $q.reject(response)
+ },
+}))
+
+app.config([
+ '$httpProvider',
+ $httpProvider =>
+ $httpProvider.interceptors.push('unAuthHttpResponseInterceptor'),
+])
diff --git a/services/web/frontend/js/modules/localStorage.js b/services/web/frontend/js/modules/localStorage.js
new file mode 100644
index 0000000000..e155dd6c2a
--- /dev/null
+++ b/services/web/frontend/js/modules/localStorage.js
@@ -0,0 +1,17 @@
+angular.module('localStorage', []).value('localStorage', localStorage)
+
+/*
+ localStorage can throw browser exceptions, for example if it is full
+ We don't use localStorage for anything critical, on in that case just
+ fail gracefully.
+*/
+function localStorage(...args) {
+ try {
+ return $.localStorage(...args)
+ } catch (e) {
+ console.error('localStorage exception', e)
+ return null
+ }
+}
+
+export default localStorage
diff --git a/services/web/frontend/js/modules/recursionHelper.js b/services/web/frontend/js/modules/recursionHelper.js
new file mode 100644
index 0000000000..f19caefed0
--- /dev/null
+++ b/services/web/frontend/js/modules/recursionHelper.js
@@ -0,0 +1,78 @@
+/* eslint-disable
+ max-len,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+//
+// * An Angular service which helps with creating recursive directives.
+// * @author Mark Lagendijk
+// * @license MIT
+//
+// From: https://github.com/marklagendijk/angular-recursion
+/* eslint-disable
+ max-len,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+//
+// * An Angular service which helps with creating recursive directives.
+// * @author Mark Lagendijk
+// * @license MIT
+//
+// From: https://github.com/marklagendijk/angular-recursion
+angular.module('RecursionHelper', []).factory('RecursionHelper', [
+ '$compile',
+ function ($compile) {
+ /*
+ Manually compiles the element, fixing the recursion loop.
+ @param element
+ @param [link] A post-link function, or an object with function(s) registered via pre and post properties.
+ @returns An object containing the linking functions.
+ */
+ return {
+ compile(element, link) {
+ // Normalize the link parameter
+ if (angular.isFunction(link)) {
+ link = { post: link }
+ }
+
+ // Break the recursion loop by removing the contents
+ const contents = element.contents().remove()
+ let compiledContents
+ return {
+ pre: link && link.pre ? link.pre : null,
+
+ /*
+ Compiles and re-adds the contents
+ */
+ post(scope, element) {
+ // Compile the contents
+ if (!compiledContents) {
+ compiledContents = $compile(contents)
+ }
+
+ // Re-add the compiled contents to the element
+ compiledContents(scope, function (clone) {
+ element.append(clone)
+ })
+
+ // Call the post-linking function, if any
+ if (link && link.post) {
+ link.post.apply(null, arguments)
+ }
+ },
+ }
+ },
+ }
+ },
+])
diff --git a/services/web/frontend/js/modules/sessionStorage.js b/services/web/frontend/js/modules/sessionStorage.js
new file mode 100644
index 0000000000..532c3e179b
--- /dev/null
+++ b/services/web/frontend/js/modules/sessionStorage.js
@@ -0,0 +1,17 @@
+angular.module('sessionStorage', []).value('sessionStorage', sessionStorage)
+
+/*
+ sessionStorage can throw browser exceptions, for example if it is full
+ We don't use sessionStorage for anything critical, on in that case just
+ fail gracefully.
+*/
+function sessionStorage(...args) {
+ try {
+ return $.sessionStorage(...args)
+ } catch (e) {
+ console.error('sessionStorage exception', e)
+ return null
+ }
+}
+
+export default sessionStorage
diff --git a/services/web/frontend/js/serviceWorker.js b/services/web/frontend/js/serviceWorker.js
new file mode 100644
index 0000000000..3bb1afedba
--- /dev/null
+++ b/services/web/frontend/js/serviceWorker.js
@@ -0,0 +1,769 @@
+import { v4 as uuid } from 'uuid'
+const OError = require('@overleaf/o-error')
+
+// VERSION should get incremented when making changes to caching behavior or
+// adjusting metrics collection.
+// Keep in sync with PdfJsMetrics.
+const VERSION = 2
+
+const CLEAR_CACHE_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/output$/
+const COMPILE_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/compile$/
+const PDF_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/.*\/output.pdf$/
+const PDF_JS_CHUNK_SIZE = 128 * 1024
+const MAX_SUBREQUEST_COUNT = 4
+const MAX_SUBREQUEST_BYTES = 4 * PDF_JS_CHUNK_SIZE
+const INCREMENTAL_CACHE_SIZE = 1000
+
+// Each compile request defines a context (essentially the specific pdf file for
+// that compile), requests for that pdf file can use the hashes in the compile
+// response, which are stored in the context.
+
+const CLIENT_CONTEXT = new Map()
+
+/**
+ * @param {string} clientId
+ */
+function getClientContext(clientId) {
+ let clientContext = CLIENT_CONTEXT.get(clientId)
+ if (!clientContext) {
+ const cached = new Set()
+ const pdfs = new Map()
+ const metrics = {
+ version: VERSION,
+ id: uuid(),
+ epoch: Date.now(),
+ failedCount: 0,
+ tooLargeOverheadCount: 0,
+ tooManyRequestsCount: 0,
+ cachedCount: 0,
+ cachedBytes: 0,
+ fetchedCount: 0,
+ fetchedBytes: 0,
+ requestedCount: 0,
+ requestedBytes: 0,
+ compileCount: 0,
+ }
+ clientContext = { pdfs, metrics, cached }
+ CLIENT_CONTEXT.set(clientId, clientContext)
+ // clean up old client maps
+ expirePdfContexts()
+ }
+ return clientContext
+}
+
+/**
+ * @param {string} clientId
+ * @param {string} path
+ * @param {Object} pdfContext
+ */
+function registerPdfContext(clientId, path, pdfContext) {
+ const clientContext = getClientContext(clientId)
+ const { pdfs, metrics, cached, clsiServerId } = clientContext
+ pdfContext.metrics = metrics
+ pdfContext.cached = cached
+ if (pdfContext.clsiServerId !== clsiServerId) {
+ // VM changed, this invalidates all browser caches.
+ clientContext.clsiServerId = pdfContext.clsiServerId
+ cached.clear()
+ }
+ // we only need to keep the last 3 contexts
+ for (const key of pdfs.keys()) {
+ if (pdfs.size < 3) {
+ break
+ }
+ pdfs.delete(key) // the map keys are returned in insertion order, so we are deleting the oldest entry here
+ }
+ pdfs.set(path, pdfContext)
+}
+
+/**
+ * @param {string} clientId
+ * @param {string} path
+ */
+function getPdfContext(clientId, path) {
+ const { pdfs } = getClientContext(clientId)
+ return pdfs.get(path)
+}
+
+function expirePdfContexts() {
+ // discard client maps for clients that are no longer connected
+ const currentClientSet = new Set()
+ self.clients.matchAll().then(function (clientList) {
+ clientList.forEach(client => {
+ currentClientSet.add(client.id)
+ })
+ CLIENT_CONTEXT.forEach((map, clientId) => {
+ if (!currentClientSet.has(clientId)) {
+ CLIENT_CONTEXT.delete(clientId)
+ }
+ })
+ })
+}
+
+/**
+ *
+ * @param {Object} metrics
+ * @param {number} size
+ * @param {number} cachedCount
+ * @param {number} cachedBytes
+ * @param {number} fetchedCount
+ * @param {number} fetchedBytes
+ */
+function trackDownloadStats(
+ metrics,
+ { size, cachedCount, cachedBytes, fetchedCount, fetchedBytes }
+) {
+ metrics.cachedCount += cachedCount
+ metrics.cachedBytes += cachedBytes
+ metrics.fetchedCount += fetchedCount
+ metrics.fetchedBytes += fetchedBytes
+ metrics.requestedCount++
+ metrics.requestedBytes += size
+}
+
+/**
+ * @param {Object} metrics
+ * @param {boolean} sizeDiffers
+ * @param {boolean} mismatch
+ * @param {boolean} success
+ */
+function trackChunkVerify(metrics, { sizeDiffers, mismatch, success }) {
+ if (sizeDiffers) {
+ metrics.chunkVerifySizeDiffers |= 0
+ metrics.chunkVerifySizeDiffers += 1
+ }
+ if (mismatch) {
+ metrics.chunkVerifyMismatch |= 0
+ metrics.chunkVerifyMismatch += 1
+ }
+ if (success) {
+ metrics.chunkVerifySuccess |= 0
+ metrics.chunkVerifySuccess += 1
+ }
+}
+
+/**
+ * @param {Array} chunks
+ */
+function countBytes(chunks) {
+ return chunks.reduce((totalBytes, chunk) => {
+ return totalBytes + (chunk.end - chunk.start)
+ }, 0)
+}
+
+/**
+ * @param {FetchEvent} event
+ */
+function onFetch(event) {
+ const url = new URL(event.request.url)
+ const path = url.pathname
+
+ if (path.match(COMPILE_REQUEST_MATCHER)) {
+ return processCompileRequest(event)
+ }
+
+ if (path.match(PDF_REQUEST_MATCHER)) {
+ const ctx = getPdfContext(event.clientId, path)
+ if (ctx) {
+ return processPdfRequest(event, ctx)
+ }
+ }
+
+ if (
+ event.request.method === 'DELETE' &&
+ path.match(CLEAR_CACHE_REQUEST_MATCHER)
+ ) {
+ return processClearCacheRequest(event)
+ }
+
+ // other request, ignore
+}
+
+/**
+ * @param {FetchEvent} event
+ */
+function processClearCacheRequest(event) {
+ CLIENT_CONTEXT.delete(event.clientId)
+ // use default request proxy.
+}
+
+/**
+ * @param {FetchEvent} event
+ */
+function processCompileRequest(event) {
+ event.respondWith(
+ fetch(event.request).then(response => {
+ if (response.status !== 200) return response
+
+ return response.json().then(body => {
+ handleCompileResponse(event, response, body)
+
+ // Send the service workers metrics to the frontend.
+ const { metrics } = getClientContext(event.clientId)
+ metrics.compileCount++
+ body.serviceWorkerMetrics = metrics
+
+ return new Response(JSON.stringify(body), response)
+ })
+ })
+ )
+}
+
+/**
+ * @param {Request} request
+ * @param {Object} file
+ * @return {Response}
+ */
+function handleProbeRequest(request, file) {
+ // PDF.js starts the pdf download with a probe request that has no
+ // range headers on it.
+ // Upon seeing the response headers, it decides whether to upgrade the
+ // transport to chunked requests or keep reading the response body.
+ // For small PDFs (2*chunkSize = 2*128kB) it just sends one request.
+ // We will fetch all the ranges in bulk and emit them.
+ // For large PDFs it sends this probe request, aborts that request before
+ // reading any data and then sends multiple range requests.
+ // It would be wasteful to action this probe request with all the ranges
+ // that are available in the PDF and serve the full PDF content to
+ // PDF.js for the probe request.
+ // We are emitting a dummy response to the probe request instead.
+ // It triggers the chunked transfer and subsequent fewer ranges need to be
+ // requested -- only those of visible pages in the pdf viewer.
+ // https://github.com/mozilla/pdf.js/blob/6fd899dc443425747098935207096328e7b55eb2/src/display/network_utils.js#L43-L47
+ const pdfJSWillUseChunkedTransfer = file.size > 2 * PDF_JS_CHUNK_SIZE
+ const isRangeRequest = request.headers.has('Range')
+ if (!isRangeRequest && pdfJSWillUseChunkedTransfer) {
+ const headers = new Headers()
+ headers.set('Accept-Ranges', 'bytes')
+ headers.set('Content-Length', file.size)
+ headers.set('Content-Type', 'application/pdf')
+ return new Response('', {
+ headers,
+ status: 200,
+ statusText: 'OK',
+ })
+ }
+}
+
+/**
+ *
+ * @param {FetchEvent} event
+ * @param {Object} file
+ * @param {string} clsiServerId
+ * @param {string} compileGroup
+ * @param {Date} pdfCreatedAt
+ * @param {Object} metrics
+ * @param {Set} cached
+ */
+function processPdfRequest(
+ event,
+ { file, clsiServerId, compileGroup, pdfCreatedAt, metrics, cached }
+) {
+ const response = handleProbeRequest(event.request, file)
+ if (response) {
+ return event.respondWith(response)
+ }
+
+ const verifyChunks = event.request.url.includes('verify_chunks=true')
+ const rangeHeader =
+ event.request.headers.get('Range') || `bytes=0-${file.size - 1}`
+ const [start, last] = rangeHeader
+ .slice('bytes='.length)
+ .split('-')
+ .map(i => parseInt(i, 10))
+ const end = last + 1
+
+ // Check that handling the range request won't trigger excessive subrequests,
+ // (to avoid unwanted latency compared to the original request).
+ const { chunks, newChunks } = cutRequestAmplification(
+ getMatchingChunks(file.ranges, start, end),
+ cached,
+ metrics
+ )
+ const dynamicChunks = getInterleavingDynamicChunks(chunks, start, end)
+ const chunksSize = countBytes(newChunks)
+ const size = end - start
+
+ if (chunks.length === 0 && dynamicChunks.length === 1) {
+ // fall back to the original range request when no chunks are cached.
+ trackDownloadStats(metrics, {
+ size,
+ cachedCount: 0,
+ cachedBytes: 0,
+ fetchedCount: 1,
+ fetchedBytes: size,
+ })
+ return
+ }
+ if (
+ chunksSize > MAX_SUBREQUEST_BYTES &&
+ !(dynamicChunks.length === 0 && newChunks.length <= 1)
+ ) {
+ // fall back to the original range request when a very large amount of
+ // object data would be requested, unless it is the only object in the
+ // request or everything is already cached.
+ metrics.tooLargeOverheadCount++
+ trackDownloadStats(metrics, {
+ size,
+ cachedCount: 0,
+ cachedBytes: 0,
+ fetchedCount: 1,
+ fetchedBytes: size,
+ })
+ return
+ }
+
+ // URL prefix is /project/:id/user/:id/build/... or /project/:id/build/...
+ // for authenticated and unauthenticated users respectively.
+ const perUserPrefix = file.url.slice(0, file.url.indexOf('/build/'))
+ const byteRanges = dynamicChunks
+ .map(chunk => `${chunk.start}-${chunk.end - 1}`)
+ .join(',')
+ const coalescedDynamicChunks = []
+ switch (dynamicChunks.length) {
+ case 0:
+ break
+ case 1:
+ coalescedDynamicChunks.push({
+ chunk: dynamicChunks[0],
+ url: event.request.url,
+ init: { headers: { Range: `bytes=${byteRanges}` } },
+ })
+ break
+ default:
+ coalescedDynamicChunks.push({
+ chunk: dynamicChunks,
+ url: event.request.url,
+ init: { headers: { Range: `bytes=${byteRanges}` } },
+ })
+ }
+ const requests = chunks
+ .map(chunk => {
+ const path = `${perUserPrefix}/content/${file.contentId}/${chunk.hash}`
+ const url = new URL(path, event.request.url)
+ if (clsiServerId) {
+ url.searchParams.set('clsiserverid', clsiServerId)
+ }
+ if (compileGroup) {
+ url.searchParams.set('compileGroup', compileGroup)
+ }
+ return { chunk, url: url.toString() }
+ })
+ .concat(coalescedDynamicChunks)
+ let cachedCount = 0
+ let cachedBytes = 0
+ let fetchedCount = 0
+ let fetchedBytes = 0
+ const reAssembledBlob = new Uint8Array(size)
+ event.respondWith(
+ Promise.all(
+ requests.map(({ chunk, url, init }) =>
+ fetch(url, init)
+ .then(response => {
+ if (!(response.status === 206 || response.status === 200)) {
+ throw new OError(
+ 'non successful response status: ' + response.status
+ )
+ }
+ const boundary = getMultipartBoundary(response)
+ if (Array.isArray(chunk) && !boundary) {
+ throw new OError('missing boundary on multipart request', {
+ headers: Object.fromEntries(response.headers.entries()),
+ chunk,
+ })
+ }
+ const blobFetchDate = getServerTime(response)
+ const blobSize = getResponseSize(response)
+ if (blobFetchDate && blobSize) {
+ const chunkSize =
+ Math.min(end, chunk.end) - Math.max(start, chunk.start)
+ // Example: 2MB PDF, 1MB image, 128KB PDF.js chunk.
+ // | pdf.js chunk |
+ // | A BIG IMAGE BLOB |
+ // | THE FULL PDF |
+ if (blobFetchDate < pdfCreatedAt) {
+ cachedCount++
+ cachedBytes += chunkSize
+ // Roll the position of the hash in the Map.
+ cached.delete(chunk.hash)
+ cached.add(chunk.hash)
+ } else {
+ // Blobs are fetched in bulk.
+ fetchedCount++
+ fetchedBytes += blobSize
+ }
+ }
+ return response
+ .blob()
+ .then(blob => blob.arrayBuffer())
+ .then(arraybuffer => {
+ return {
+ boundary,
+ chunk,
+ data: backFillObjectContext(chunk, arraybuffer),
+ }
+ })
+ })
+ .catch(error => {
+ throw OError.tag(error, 'cannot fetch chunk', { url })
+ })
+ )
+ )
+ .then(rawResponses => {
+ const responses = []
+ for (const response of rawResponses) {
+ if (response.boundary) {
+ responses.push(
+ ...getMultiPartResponses(response, file, metrics, verifyChunks)
+ )
+ } else {
+ responses.push(response)
+ }
+ }
+ responses.forEach(({ chunk, data }) => {
+ // overlap:
+ // | REQUESTED_RANGE |
+ // | CHUNK |
+ const offsetStart = Math.max(start - chunk.start, 0)
+ // overlap:
+ // | REQUESTED_RANGE |
+ // | CHUNK |
+ const offsetEnd = Math.max(chunk.end - end, 0)
+ if (offsetStart > 0 || offsetEnd > 0) {
+ // compute index positions for slice to handle case where offsetEnd=0
+ const chunkSize = chunk.end - chunk.start
+ data = data.subarray(offsetStart, chunkSize - offsetEnd)
+ }
+ const insertPosition = Math.max(chunk.start - start, 0)
+ reAssembledBlob.set(data, insertPosition)
+ })
+
+ let verifyProcess = Promise.resolve(reAssembledBlob)
+ if (verifyChunks) {
+ verifyProcess = fetch(event.request)
+ .then(response => response.arrayBuffer())
+ .then(arrayBuffer => {
+ const fullBlob = new Uint8Array(arrayBuffer)
+ const stats = {}
+ if (reAssembledBlob.byteLength !== fullBlob.byteLength) {
+ stats.sizeDiffers = true
+ } else if (
+ !reAssembledBlob.every((v, idx) => v === fullBlob[idx])
+ ) {
+ stats.mismatch = true
+ } else {
+ stats.success = true
+ }
+ trackChunkVerify(metrics, stats)
+ if (stats.success === true) {
+ return reAssembledBlob
+ } else {
+ return fullBlob
+ }
+ })
+ }
+
+ return verifyProcess.then(blob => {
+ trackDownloadStats(metrics, {
+ size,
+ cachedCount,
+ cachedBytes,
+ fetchedCount,
+ fetchedBytes,
+ })
+ return new Response(blob, {
+ status: 206,
+ headers: {
+ 'Accept-Ranges': 'bytes',
+ 'Content-Length': size,
+ 'Content-Range': `bytes ${start}-${last}/${file.size}`,
+ 'Content-Type': 'application/pdf',
+ },
+ })
+ })
+ })
+ .catch(error => {
+ fetchedBytes += size
+ metrics.failedCount++
+ trackDownloadStats(metrics, {
+ size,
+ cachedCount: 0,
+ cachedBytes: 0,
+ fetchedCount,
+ fetchedBytes,
+ })
+ reportError(event, OError.tag(error, 'failed to compose pdf response'))
+ return fetch(event.request)
+ })
+ )
+}
+
+/**
+ *
+ * @param {Response} response
+ */
+function getServerTime(response) {
+ const raw = response.headers.get('Date')
+ if (!raw) return new Date()
+ return new Date(raw)
+}
+
+/**
+ *
+ * @param {Response} response
+ */
+function getResponseSize(response) {
+ const raw = response.headers.get('Content-Length')
+ if (!raw) return 0
+ return parseInt(raw, 10)
+}
+
+/**
+ *
+ * @param {Response} response
+ */
+function getMultipartBoundary(response) {
+ const raw = response.headers.get('Content-Type')
+ if (!raw.includes('multipart/byteranges')) return ''
+ const idx = raw.indexOf('boundary=')
+ if (idx === -1) return ''
+ return raw.slice(idx + 'boundary='.length)
+}
+
+/**
+ * @param {Object} response
+ * @param {Object} file
+ * @param {Object} metrics
+ * @param {boolean} verifyChunks
+ */
+function getMultiPartResponses(response, file, metrics, verifyChunks) {
+ const { chunk: chunks, data, boundary } = response
+ const responses = []
+ let offsetStart = 0
+ for (const chunk of chunks) {
+ const header = `\r\n--${boundary}\r\nContent-Type: application/pdf\r\nContent-Range: bytes ${
+ chunk.start
+ }-${chunk.end - 1}/${file.size}\r\n\r\n`
+ const headerSize = header.length
+
+ // Verify header content. A proxy might have tampered with it.
+ const headerRaw = ENCODER.encode(header)
+ if (
+ !data
+ .subarray(offsetStart, offsetStart + headerSize)
+ .every((v, idx) => v === headerRaw[idx])
+ ) {
+ metrics.headerVerifyFailure |= 0
+ metrics.headerVerifyFailure++
+ throw new OError('multipart response header does not match', {
+ actual: new TextDecoder().decode(
+ data.subarray(offsetStart, offsetStart + headerSize)
+ ),
+ expected: header,
+ })
+ }
+
+ offsetStart += headerSize
+ const chunkSize = chunk.end - chunk.start
+ responses.push({
+ chunk,
+ data: data.subarray(offsetStart, offsetStart + chunkSize),
+ })
+ offsetStart += chunkSize
+ }
+ return responses
+}
+
+/**
+ * @param {FetchEvent} event
+ * @param {Response} response
+ * @param {Object} body
+ */
+function handleCompileResponse(event, response, body) {
+ if (!body || body.status !== 'success') return
+
+ const pdfCreatedAt = getServerTime(response)
+
+ for (const file of body.outputFiles) {
+ if (file.path !== 'output.pdf') continue // not the pdf used for rendering
+ if (file.ranges) {
+ file.ranges.forEach(backFillEdgeBounds)
+ const { clsiServerId, compileGroup } = body
+ registerPdfContext(event.clientId, file.url, {
+ pdfCreatedAt,
+ file,
+ clsiServerId,
+ compileGroup,
+ })
+ }
+ break
+ }
+}
+
+const ENCODER = new TextEncoder()
+function backFillEdgeBounds(chunk) {
+ if (chunk.objectId) {
+ chunk.objectId = ENCODER.encode(chunk.objectId)
+ chunk.start -= chunk.objectId.byteLength
+ }
+ return chunk
+}
+
+/**
+ * @param chunk
+ * @param {ArrayBuffer} arrayBuffer
+ * @return {Uint8Array}
+ */
+function backFillObjectContext(chunk, arrayBuffer) {
+ if (!chunk.objectId) {
+ // This is a dynamic chunk
+ return new Uint8Array(arrayBuffer)
+ }
+ const { start, end, objectId } = chunk
+ const header = Uint8Array.from(objectId)
+ const fullBuffer = new Uint8Array(end - start)
+ fullBuffer.set(header, 0)
+ fullBuffer.set(new Uint8Array(arrayBuffer), objectId.length)
+ return fullBuffer
+}
+
+/**
+ * @param {Array} chunks
+ * @param {number} start
+ * @param {number} end
+ * @returns {Array}
+ */
+function getMatchingChunks(chunks, start, end) {
+ const matchingChunks = []
+ for (const chunk of chunks) {
+ if (chunk.end <= start) {
+ // no overlap:
+ // | REQUESTED_RANGE |
+ // | CHUNK |
+ continue
+ }
+ if (chunk.start >= end) {
+ // no overlap:
+ // | REQUESTED_RANGE |
+ // | CHUNK |
+ break
+ }
+ matchingChunks.push(chunk)
+ }
+ return matchingChunks
+}
+
+/**
+ * @param {Array} potentialChunks
+ * @param {Set} cached
+ * @param {Object} metrics
+ */
+function cutRequestAmplification(potentialChunks, cached, metrics) {
+ const chunks = []
+ const newChunks = []
+ let tooManyRequests = false
+ for (const chunk of potentialChunks) {
+ if (cached.has(chunk.hash)) {
+ chunks.push(chunk)
+ continue
+ }
+ if (newChunks.length < MAX_SUBREQUEST_COUNT) {
+ chunks.push(chunk)
+ newChunks.push(chunk)
+ } else {
+ tooManyRequests = true
+ }
+ }
+ if (tooManyRequests) {
+ metrics.tooManyRequestsCount++
+ }
+ if (cached.size > INCREMENTAL_CACHE_SIZE) {
+ for (const key of cached) {
+ if (cached.size < INCREMENTAL_CACHE_SIZE) {
+ break
+ }
+ // Map keys are stored in insertion order.
+ // We re-insert keys on cache hit, 'cached' is a cheap LRU.
+ cached.delete(key)
+ }
+ }
+ return { chunks, newChunks }
+}
+
+/**
+ * @param {Array} chunks
+ * @param {number} start
+ * @param {number} end
+ * @returns {Array}
+ */
+function getInterleavingDynamicChunks(chunks, start, end) {
+ const dynamicChunks = []
+ for (const chunk of chunks) {
+ if (start < chunk.start) {
+ dynamicChunks.push({ start, end: chunk.start })
+ }
+ start = chunk.end
+ }
+
+ if (start < end) {
+ dynamicChunks.push({ start, end })
+ }
+ return dynamicChunks
+}
+
+/**
+ * @param {FetchEvent} event
+ */
+function onFetchWithErrorHandling(event) {
+ try {
+ onFetch(event)
+ } catch (error) {
+ reportError(event, OError.tag(error, 'low level error in onFetch'))
+ }
+}
+// allow fetch event listener to be removed if necessary
+const controller = new AbortController()
+// listen to all network requests
+self.addEventListener('fetch', onFetchWithErrorHandling, {
+ signal: controller.signal,
+})
+
+// complete setup ASAP
+self.addEventListener('install', event => {
+ event.waitUntil(self.skipWaiting())
+})
+self.addEventListener('activate', event => {
+ event.waitUntil(self.clients.claim())
+})
+self.addEventListener('message', event => {
+ if (event.data && event.data.type === 'disable') {
+ controller.abort() // removes the fetch event listener
+ }
+})
+
+/**
+ *
+ * @param {FetchEvent} event
+ * @param {Error} error
+ */
+function reportError(event, error) {
+ self.clients
+ .get(event.clientId)
+ .then(client => {
+ if (!client) {
+ // The client disconnected.
+ return
+ }
+ client.postMessage(
+ JSON.stringify({
+ extra: { url: event.request.url, info: OError.getFullInfo(error) },
+ error: {
+ name: error.name,
+ message: error.message,
+ stack: OError.getFullStack(error),
+ },
+ })
+ )
+ })
+ .catch(() => {})
+}
diff --git a/services/web/frontend/js/services/algolia-search.js b/services/web/frontend/js/services/algolia-search.js
new file mode 100644
index 0000000000..6eb1c92ab6
--- /dev/null
+++ b/services/web/frontend/js/services/algolia-search.js
@@ -0,0 +1,20 @@
+import _ from 'lodash'
+import App from '../base'
+import AlgoliaSearch from 'algoliasearch'
+import getMeta from '../utils/meta'
+
+export default App.factory('algoliaSearch', function () {
+ let wikiIdx
+ const algoliaConfig = getMeta('ol-algolia')
+ const wikiIndex = _.get(algoliaConfig, 'indexes.wiki')
+ if (wikiIndex) {
+ const client = AlgoliaSearch(algoliaConfig.appId, algoliaConfig.apiKey)
+ wikiIdx = client.initIndex(wikiIndex)
+ }
+
+ const service = {
+ searchWiki: wikiIdx ? wikiIdx.search.bind(wikiIdx) : null,
+ }
+
+ return service
+})
diff --git a/services/web/frontend/js/services/queued-http.js b/services/web/frontend/js/services/queued-http.js
new file mode 100644
index 0000000000..b00b22744a
--- /dev/null
+++ b/services/web/frontend/js/services/queued-http.js
@@ -0,0 +1,77 @@
+/* eslint-disable
+ max-len,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+
+export default App.factory('queuedHttp', function ($http, $q) {
+ const pendingRequests = []
+ let inflight = false
+
+ var processPendingRequests = function () {
+ if (inflight) {
+ return
+ }
+ const doRequest = pendingRequests.shift()
+ if (doRequest != null) {
+ inflight = true
+ return doRequest()
+ .then(function () {
+ inflight = false
+ return processPendingRequests()
+ })
+ .catch(function () {
+ inflight = false
+ return processPendingRequests()
+ })
+ }
+ }
+
+ const queuedHttp = function (...args) {
+ // We can't use Angular's $q.defer promises, because it only passes
+ // a single argument on error, and $http passes multiple.
+ const promise = {}
+ const successCallbacks = []
+ const errorCallbacks = []
+
+ // Adhere to the $http promise conventions
+ promise.then = function (callback, errCallback) {
+ successCallbacks.push(callback)
+ if (errCallback != null) {
+ errorCallbacks.push(errCallback)
+ }
+ return promise
+ }
+
+ promise.catch = function (callback) {
+ errorCallbacks.push(callback)
+ return promise
+ }
+
+ const doRequest = () =>
+ $http(...Array.from(args || []))
+ .then((...args) =>
+ Array.from(successCallbacks).map(cb => cb(...Array.from(args || [])))
+ )
+ .catch((...args) =>
+ Array.from(errorCallbacks).map(cb => cb(...Array.from(args || [])))
+ )
+
+ pendingRequests.push(doRequest)
+ processPendingRequests()
+
+ return promise
+ }
+
+ queuedHttp.post = (url, data) => queuedHttp({ method: 'POST', url, data })
+
+ return queuedHttp
+})
diff --git a/services/web/frontend/js/services/validateCaptcha.js b/services/web/frontend/js/services/validateCaptcha.js
new file mode 100644
index 0000000000..1d8a01b084
--- /dev/null
+++ b/services/web/frontend/js/services/validateCaptcha.js
@@ -0,0 +1,46 @@
+/* global grecaptcha */
+
+/* eslint-disable
+ no-return-assign,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ */
+import App from '../base'
+
+export default App.factory('validateCaptcha', function () {
+ let _recaptchaCallbacks = []
+ const onRecaptchaSubmit = function (token) {
+ for (const cb of _recaptchaCallbacks) {
+ cb(token)
+ }
+ _recaptchaCallbacks = []
+ }
+
+ let recaptchaId = null
+ const validateCaptcha = (callback, captchaDisabled) => {
+ if (callback == null) {
+ callback = function (response) {}
+ }
+ if (
+ typeof grecaptcha === 'undefined' ||
+ grecaptcha === null ||
+ captchaDisabled
+ ) {
+ return callback()
+ }
+ const reset = () => grecaptcha.reset()
+ _recaptchaCallbacks.push(callback)
+ _recaptchaCallbacks.push(reset)
+ if (recaptchaId == null) {
+ const el = $('#recaptcha')[0]
+ recaptchaId = grecaptcha.render(el, { callback: onRecaptchaSubmit })
+ }
+ return grecaptcha.execute(recaptchaId)
+ }
+
+ return validateCaptcha
+})
diff --git a/services/web/frontend/js/services/validateCaptchaV3.js b/services/web/frontend/js/services/validateCaptchaV3.js
new file mode 100644
index 0000000000..8283f34076
--- /dev/null
+++ b/services/web/frontend/js/services/validateCaptchaV3.js
@@ -0,0 +1,19 @@
+import App from '../base'
+
+export default App.factory('validateCaptchaV3', function () {
+ const grecaptcha = window.grecaptcha
+ const ExposedSettings = window.ExposedSettings
+ return function validateCaptchaV3(actionName, callback = () => {}) {
+ if (!grecaptcha) {
+ return
+ }
+ if (!ExposedSettings || !ExposedSettings.recaptchaSiteKeyV3) {
+ return
+ }
+ grecaptcha.ready(function () {
+ grecaptcha
+ .execute(ExposedSettings.recaptchaSiteKeyV3, { action: actionName })
+ .then(callback)
+ })
+ }
+})
diff --git a/services/web/frontend/js/services/wait-for.js b/services/web/frontend/js/services/wait-for.js
new file mode 100644
index 0000000000..0b3b26d4e4
--- /dev/null
+++ b/services/web/frontend/js/services/wait-for.js
@@ -0,0 +1,42 @@
+/* eslint-disable
+ max-len,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+import App from '../base'
+
+export default App.factory('waitFor', function ($q) {
+ const waitFor = function (testFunction, timeout, pollInterval) {
+ if (pollInterval == null) {
+ pollInterval = 500
+ }
+ const iterationLimit = Math.floor(timeout / pollInterval)
+ let iterations = 0
+ return $q(function (resolve, reject) {
+ let tryIteration
+ return (tryIteration = function () {
+ if (iterations > iterationLimit) {
+ return reject(
+ new Error(
+ `waiting too long, ${JSON.stringify({ timeout, pollInterval })}`
+ )
+ )
+ }
+ iterations += 1
+ const result = testFunction()
+ if (result != null) {
+ return resolve(result)
+ } else {
+ return setTimeout(tryIteration, pollInterval)
+ }
+ })()
+ })
+ }
+ return waitFor
+})
diff --git a/services/web/frontend/js/shared/components/accessible-modal.js b/services/web/frontend/js/shared/components/accessible-modal.js
new file mode 100644
index 0000000000..f8f839b75a
--- /dev/null
+++ b/services/web/frontend/js/shared/components/accessible-modal.js
@@ -0,0 +1,36 @@
+import { useCallback } from 'react'
+import PropTypes from 'prop-types'
+import { Modal } from 'react-bootstrap'
+
+// a bootstrap Modal with its `aria-hidden` attribute removed. Visisble modals
+// should not have their `aria-hidden` attribute set but that's a bug in our
+// version of react-bootstrap.
+function AccessibleModal({ show, ...otherProps }) {
+ // use a callback ref to track the modal. This will re-run the function
+ // when the element node or any of the dependencies are updated
+ const setModalRef = useCallback(
+ element => {
+ if (!element) return
+
+ const modalNode = element._modal && element._modal.modalNode
+ if (!modalNode) return
+
+ if (show) {
+ modalNode.removeAttribute('aria-hidden')
+ } else {
+ modalNode.setAttribute('aria-hidden', 'true')
+ }
+ },
+ // `show` is necessary as a dependency, but eslint thinks it is not
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [show]
+ )
+
+ return
+}
+
+AccessibleModal.propTypes = {
+ show: PropTypes.bool,
+}
+
+export default AccessibleModal
diff --git a/services/web/frontend/js/shared/components/beta-badge.js b/services/web/frontend/js/shared/components/beta-badge.js
new file mode 100644
index 0000000000..858db3a42a
--- /dev/null
+++ b/services/web/frontend/js/shared/components/beta-badge.js
@@ -0,0 +1,30 @@
+import { OverlayTrigger, Tooltip } from 'react-bootstrap'
+import PropTypes from 'prop-types'
+
+export default function BetaBadge({ tooltip, url = '/beta/participate' }) {
+ return (
+ {tooltip.text}}
+ delayHide={100}
+ >
+
+ {tooltip.text}
+
+
+ )
+}
+
+BetaBadge.propTypes = {
+ tooltip: PropTypes.exact({
+ id: PropTypes.string.isRequired,
+ text: PropTypes.string.isRequired,
+ placement: PropTypes.string,
+ }),
+ url: PropTypes.string,
+}
diff --git a/services/web/frontend/js/shared/components/controlled-dropdown.js b/services/web/frontend/js/shared/components/controlled-dropdown.js
new file mode 100644
index 0000000000..9e577537dd
--- /dev/null
+++ b/services/web/frontend/js/shared/components/controlled-dropdown.js
@@ -0,0 +1,35 @@
+import React from 'react'
+import { Dropdown } from 'react-bootstrap'
+import PropTypes from 'prop-types'
+import useDropdown from '../hooks/use-dropdown'
+
+export default function ControlledDropdown(props) {
+ const dropdownProps = useDropdown(Boolean(props.defaultOpen))
+
+ return (
+
+ {React.Children.map(props.children, child => {
+ if (!React.isValidElement(child)) {
+ return child
+ }
+
+ // Dropdown.Menu
+ if ('open' in child.props) {
+ return React.cloneElement(child, { open: dropdownProps.open })
+ }
+
+ // Overlay
+ if ('show' in child.props) {
+ return React.cloneElement(child, { show: dropdownProps.open })
+ }
+
+ // anything else
+ return React.cloneElement(child)
+ })}
+
+ )
+}
+ControlledDropdown.propTypes = {
+ children: PropTypes.any,
+ defaultOpen: PropTypes.bool,
+}
diff --git a/services/web/frontend/js/shared/components/copy-link.js b/services/web/frontend/js/shared/components/copy-link.js
new file mode 100644
index 0000000000..80509cc38d
--- /dev/null
+++ b/services/web/frontend/js/shared/components/copy-link.js
@@ -0,0 +1,51 @@
+import { useCallback, useState } from 'react'
+import { Button, OverlayTrigger, Tooltip } from 'react-bootstrap'
+import PropTypes from 'prop-types'
+import { Trans, useTranslation } from 'react-i18next'
+import Icon from './icon'
+
+export default function CopyLink({ link, tooltipId }) {
+ const { t } = useTranslation()
+
+ const [copied, setCopied] = useState(false)
+
+ const handleClick = useCallback(() => {
+ navigator.clipboard.writeText(link).then(() => {
+ setCopied(true)
+ window.setTimeout(() => {
+ setCopied(false)
+ }, 1500)
+ })
+ }, [link])
+
+ if (!navigator.clipboard?.writeText) {
+ return null
+ }
+
+ return (
+
+ {copied ? 'Copied!' : }
+
+ }
+ >
+
+ {copied ? : }
+
+
+ )
+}
+CopyLink.propTypes = {
+ link: PropTypes.string.isRequired,
+ tooltipId: PropTypes.string.isRequired,
+}
diff --git a/services/web/frontend/js/shared/components/icon.js b/services/web/frontend/js/shared/components/icon.js
new file mode 100644
index 0000000000..55b8649487
--- /dev/null
+++ b/services/web/frontend/js/shared/components/icon.js
@@ -0,0 +1,48 @@
+import PropTypes from 'prop-types'
+import classNames from 'classnames'
+
+function Icon({
+ type,
+ spin,
+ modifier,
+ classes = {},
+ accessibilityLabel,
+ children,
+}) {
+ const iconClassName = classNames(
+ 'fa',
+ `fa-${type}`,
+ {
+ 'fa-spin': spin,
+ [`fa-${modifier}`]: modifier,
+ },
+ classes.icon
+ )
+
+ return (
+ <>
+
+ {children}
+
+ {accessibilityLabel ? (
+ {accessibilityLabel}
+ ) : null}
+ >
+ )
+}
+
+Icon.propTypes = {
+ type: PropTypes.string.isRequired,
+ spin: PropTypes.bool,
+ modifier: PropTypes.string,
+ classes: PropTypes.exact({
+ icon: PropTypes.string,
+ }),
+ accessibilityLabel: PropTypes.string,
+ children: PropTypes.oneOfType([
+ PropTypes.arrayOf(PropTypes.node),
+ PropTypes.node,
+ ]),
+}
+
+export default Icon
diff --git a/services/web/frontend/js/shared/components/pagination.js b/services/web/frontend/js/shared/components/pagination.js
new file mode 100644
index 0000000000..b23cceb1e4
--- /dev/null
+++ b/services/web/frontend/js/shared/components/pagination.js
@@ -0,0 +1,170 @@
+import { useMemo } from 'react'
+import PropTypes from 'prop-types'
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+
+function Pagination({ currentPage, totalPages, handlePageClick }) {
+ const { t } = useTranslation()
+
+ const maxOtherPageButtons = useMemo(() => {
+ let maxOtherPageButtons = 4 // does not include current page, prev/next buttons
+ if (totalPages < maxOtherPageButtons + 1) {
+ maxOtherPageButtons = totalPages - 1
+ }
+ return maxOtherPageButtons
+ }, [totalPages])
+
+ const pageButtons = useMemo(() => {
+ const result = []
+ let nextPage = currentPage + 1
+ let prevPage = currentPage - 1
+
+ function calcPages() {
+ if (nextPage && nextPage <= totalPages) {
+ result.push(nextPage)
+ nextPage++
+ } else {
+ nextPage = undefined
+ }
+
+ if (prevPage && prevPage > 0) {
+ result.push(prevPage)
+ prevPage--
+ } else {
+ prevPage = undefined
+ }
+ }
+
+ while (result.length < maxOtherPageButtons) {
+ calcPages()
+ }
+
+ result.push(currentPage) // wait until prev/next calculated to add current
+ result.sort((a, b) => a - b) // sort numerically
+
+ return result
+ }, [currentPage, totalPages, maxOtherPageButtons])
+
+ const morePrevPages = useMemo(() => {
+ return pageButtons[0] !== 1 && currentPage - maxOtherPageButtons / 2 > 1
+ }, [pageButtons, currentPage, maxOtherPageButtons])
+
+ const moreNextPages = useMemo(() => {
+ return pageButtons[pageButtons.length - 1] < totalPages
+ }, [pageButtons, totalPages])
+
+ return (
+
+
+ {currentPage > 1 && (
+
+ handlePageClick(event, currentPage - 1)}
+ aria-label={t('go_prev_page')}
+ >
+ «
+
+
+ )}
+
+ {morePrevPages && (
+
+ …
+
+ )}
+
+ {pageButtons.map(page => (
+
+ ))}
+
+ {moreNextPages && (
+
+ …
+
+ )}
+
+ {currentPage < totalPages && (
+
+ handlePageClick(event, currentPage + 1)}
+ aria-label={t('go_next_page')}
+ >
+ »
+
+
+ )}
+
+
+ )
+}
+
+function PaginationItem({ page, currentPage, handlePageClick }) {
+ const { t } = useTranslation()
+ const itemClassName = classNames({ active: currentPage === page })
+ const ariaCurrent = currentPage === page
+ const ariaLabel =
+ currentPage === page ? t('page_current', { page }) : t('go_page', { page })
+ return (
+
+ handlePageClick(event, page)}
+ aria-label={ariaLabel}
+ >
+ {page}
+
+
+ )
+}
+
+function isPositiveNumber(value) {
+ return typeof value === 'number' && value > 0
+}
+
+function isCurrentPageWithinTotalPages(currentPage, totalPages) {
+ return currentPage <= totalPages
+}
+
+Pagination.propTypes = {
+ currentPage: function (props, propName, componentName) {
+ if (
+ !isPositiveNumber(props[propName]) ||
+ !isCurrentPageWithinTotalPages(props.currentPage, props.totalPages)
+ ) {
+ return new Error(
+ 'Invalid prop `' +
+ propName +
+ '` supplied to' +
+ ' `' +
+ componentName +
+ '`. Validation failed.'
+ )
+ }
+ },
+ totalPages: function (props, propName, componentName) {
+ if (!isPositiveNumber(props[propName])) {
+ return new Error(
+ 'Invalid prop `' +
+ propName +
+ '` supplied to' +
+ ' `' +
+ componentName +
+ '`. Validation failed.'
+ )
+ }
+ },
+ handlePageClick: PropTypes.func.isRequired,
+}
+
+PaginationItem.propTypes = {
+ currentPage: PropTypes.number.isRequired,
+ page: PropTypes.number.isRequired,
+ handlePageClick: PropTypes.func.isRequired,
+}
+
+export default Pagination
diff --git a/services/web/frontend/js/shared/components/processing.js b/services/web/frontend/js/shared/components/processing.js
new file mode 100644
index 0000000000..6d1e021336
--- /dev/null
+++ b/services/web/frontend/js/shared/components/processing.js
@@ -0,0 +1,22 @@
+import PropTypes from 'prop-types'
+import { useTranslation } from 'react-i18next'
+import Icon from './icon'
+
+function Processing({ isProcessing }) {
+ const { t } = useTranslation()
+ if (isProcessing) {
+ return (
+
+ {t('processing')}…
+
+ )
+ } else {
+ return <>>
+ }
+}
+
+Processing.propTypes = {
+ isProcessing: PropTypes.bool.isRequired,
+}
+
+export default Processing
diff --git a/services/web/frontend/js/shared/components/start-free-trial-button.js b/services/web/frontend/js/shared/components/start-free-trial-button.js
new file mode 100644
index 0000000000..82dd579d46
--- /dev/null
+++ b/services/web/frontend/js/shared/components/start-free-trial-button.js
@@ -0,0 +1,60 @@
+import { useCallback, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from 'react-bootstrap'
+import PropTypes from 'prop-types'
+import * as eventTracking from '../../infrastructure/event-tracking'
+
+export default function StartFreeTrialButton({
+ buttonStyle = 'info',
+ children,
+ classes = {},
+ setStartedFreeTrial,
+ source,
+}) {
+ const { t } = useTranslation()
+
+ useEffect(() => {
+ eventTracking.sendMB(`${source}-paywall-prompt`)
+ }, [source])
+
+ const handleClick = useCallback(
+ event => {
+ event.preventDefault()
+
+ eventTracking.send('subscription-funnel', 'upgraded-free-trial', source)
+ eventTracking.sendMB(`${source}-paywall-click`)
+
+ if (setStartedFreeTrial) {
+ setStartedFreeTrial(true)
+ }
+
+ const params = new URLSearchParams({
+ planCode: 'collaborator_free_trial_7_days',
+ ssp: 'true',
+ itm_campaign: source,
+ })
+
+ window.open(`/user/subscription/new?${params}`)
+ },
+ [setStartedFreeTrial, source]
+ )
+
+ return (
+
+ {children || t('start_free_trial')}
+
+ )
+}
+StartFreeTrialButton.propTypes = {
+ buttonStyle: PropTypes.string,
+ children: PropTypes.any,
+ classes: PropTypes.shape({
+ button: PropTypes.string.isRequired,
+ }),
+ setStartedFreeTrial: PropTypes.func,
+ source: PropTypes.string.isRequired,
+}
diff --git a/services/web/frontend/js/shared/components/tooltip-button.js b/services/web/frontend/js/shared/components/tooltip-button.js
new file mode 100644
index 0000000000..1689cf4699
--- /dev/null
+++ b/services/web/frontend/js/shared/components/tooltip-button.js
@@ -0,0 +1,24 @@
+import PropTypes from 'prop-types'
+import { Button, Tooltip, OverlayTrigger } from 'react-bootstrap'
+
+function TooltipButton({ id, description, onClick, children }) {
+ const tooltip = {description}
+
+ return (
+
+ {children}
+
+ )
+}
+
+TooltipButton.propTypes = {
+ id: PropTypes.string.isRequired,
+ description: PropTypes.string.isRequired,
+ onClick: PropTypes.func,
+ children: PropTypes.oneOfType([
+ PropTypes.arrayOf(PropTypes.node),
+ PropTypes.node,
+ ]),
+}
+
+export default TooltipButton
diff --git a/services/web/frontend/js/shared/context/compile-context.js b/services/web/frontend/js/shared/context/compile-context.js
new file mode 100644
index 0000000000..5f2d8b3d00
--- /dev/null
+++ b/services/web/frontend/js/shared/context/compile-context.js
@@ -0,0 +1,42 @@
+import { createContext, useContext } from 'react'
+import PropTypes from 'prop-types'
+import useScopeValue from './util/scope-value-hook'
+
+export const CompileContext = createContext()
+
+CompileContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ pdfUrl: PropTypes.string,
+ pdfDownloadUrl: PropTypes.string,
+ logEntries: PropTypes.object,
+ uncompiled: PropTypes.bool,
+ }),
+}
+
+export function CompileProvider({ children }) {
+ const [pdfUrl] = useScopeValue('pdf.url')
+ const [pdfDownloadUrl] = useScopeValue('pdf.downloadUrl')
+ const [logEntries] = useScopeValue('pdf.logEntries')
+ const [uncompiled] = useScopeValue('pdf.uncompiled')
+
+ const value = {
+ pdfUrl,
+ pdfDownloadUrl,
+ logEntries,
+ uncompiled,
+ }
+
+ return (
+ {children}
+ )
+}
+
+CompileProvider.propTypes = {
+ children: PropTypes.any,
+}
+
+export function useCompileContext(propTypes) {
+ const data = useContext(CompileContext)
+ PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
+ return data
+}
diff --git a/services/web/frontend/js/shared/context/controllers/root-context-controller.js b/services/web/frontend/js/shared/context/controllers/root-context-controller.js
new file mode 100644
index 0000000000..4e393b53a3
--- /dev/null
+++ b/services/web/frontend/js/shared/context/controllers/root-context-controller.js
@@ -0,0 +1,8 @@
+import App from '../../../base'
+import { react2angular } from 'react2angular'
+import { rootContext } from '../root-context'
+
+App.component(
+ 'sharedContextReact',
+ react2angular(rootContext.component, [], ['ide', 'settings'])
+)
diff --git a/services/web/frontend/js/shared/context/editor-context.js b/services/web/frontend/js/shared/context/editor-context.js
new file mode 100644
index 0000000000..04627c3753
--- /dev/null
+++ b/services/web/frontend/js/shared/context/editor-context.js
@@ -0,0 +1,158 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+} from 'react'
+import PropTypes from 'prop-types'
+import useScopeValue from './util/scope-value-hook'
+import useBrowserWindow from '../hooks/use-browser-window'
+import { useIdeContext } from './ide-context'
+import { useProjectContext } from './project-context'
+
+export const EditorContext = createContext()
+
+EditorContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ cobranding: PropTypes.shape({
+ logoImgUrl: PropTypes.string.isRequired,
+ brandVariationName: PropTypes.string.isRequired,
+ brandVariationId: PropTypes.number.isRequired,
+ brandId: PropTypes.number.isRequired,
+ brandVariationHomeUrl: PropTypes.string.isRequired,
+ publishGuideHtml: PropTypes.string,
+ partner: PropTypes.string,
+ brandedMenu: PropTypes.bool,
+ submitBtnHtml: PropTypes.string,
+ }),
+ hasPremiumCompile: PropTypes.bool,
+ loading: PropTypes.bool,
+ renameProject: PropTypes.func.isRequired,
+ isProjectOwner: PropTypes.bool,
+ isRestrictedTokenMember: PropTypes.bool,
+ rootFolder: PropTypes.shape({
+ children: PropTypes.arrayOf(PropTypes.shape({ type: PropTypes.string })),
+ }),
+ permissionsLevel: PropTypes.oneOf(['readOnly', 'readAndWrite', 'owner']),
+ }),
+}
+
+export function EditorProvider({ children, settings }) {
+ const ide = useIdeContext()
+
+ const { owner, features } = useProjectContext({
+ owner: PropTypes.shape({
+ _id: PropTypes.string.isRequired,
+ }),
+ features: PropTypes.shape({
+ compileGroup: PropTypes.string,
+ }),
+ })
+
+ const cobranding = useMemo(() => {
+ if (window.brandVariation) {
+ return {
+ logoImgUrl: window.brandVariation.logo_url,
+ brandVariationName: window.brandVariation.name,
+ brandVariationId: window.brandVariation.id,
+ brandId: window.brandVariation.brand_id,
+ brandVariationHomeUrl: window.brandVariation.home_url,
+ publishGuideHtml: window.brandVariation.publish_guide_html,
+ partner: window.brandVariation.partner,
+ brandedMenu: window.brandVariation.branded_menu,
+ submitBtnHtml: window.brandVariation.submit_button_html,
+ }
+ } else {
+ return undefined
+ }
+ }, [])
+
+ const [loading] = useScopeValue('state.loading')
+ const [projectName, setProjectName] = useScopeValue('project.name')
+ const [rootFolder] = useScopeValue('rootFolder')
+ const [permissionsLevel] = useScopeValue('permissionsLevel')
+
+ useEffect(() => {
+ if (ide?.socket) {
+ ide.socket.on('projectNameUpdated', setProjectName)
+ return () =>
+ ide.socket.removeListener('projectNameUpdated', setProjectName)
+ }
+ }, [ide?.socket, setProjectName])
+
+ const renameProject = useCallback(
+ newName => {
+ setProjectName(oldName => {
+ if (oldName !== newName) {
+ settings.saveProjectSettings({ name: newName }).catch(response => {
+ setProjectName(oldName)
+ const { data, status } = response
+ if (status === 400) {
+ return ide.showGenericMessageModal('Error renaming project', data)
+ } else {
+ return ide.showGenericMessageModal(
+ 'Error renaming project',
+ 'Please try again in a moment'
+ )
+ }
+ })
+ }
+ return newName
+ })
+ },
+ [settings, ide, setProjectName]
+ )
+
+ const { setTitle } = useBrowserWindow()
+ useEffect(() => {
+ setTitle(
+ `${projectName ? projectName + ' - ' : ''}Online LaTeX Editor ${
+ window.ExposedSettings.appName
+ }`
+ )
+ }, [projectName, setTitle])
+
+ const value = useMemo(
+ () => ({
+ cobranding,
+ hasPremiumCompile: features?.compileGroup === 'priority',
+ loading,
+ renameProject,
+ permissionsLevel,
+ isProjectOwner: owner?._id === window.user.id,
+ isRestrictedTokenMember: window.isRestrictedTokenMember,
+ rootFolder,
+ }),
+ [
+ cobranding,
+ features?.compileGroup,
+ loading,
+ renameProject,
+ permissionsLevel,
+ owner?._id,
+ rootFolder,
+ ]
+ )
+
+ return (
+ {children}
+ )
+}
+
+EditorProvider.propTypes = {
+ children: PropTypes.any,
+ settings: PropTypes.any.isRequired,
+}
+
+export function useEditorContext(propTypes) {
+ const context = useContext(EditorContext)
+
+ if (!context) {
+ throw new Error('useEditorContext is only available inside EditorProvider')
+ }
+
+ PropTypes.checkPropTypes(propTypes, context, 'data', 'EditorContext.Provider')
+
+ return context
+}
diff --git a/services/web/frontend/js/shared/context/ide-context.js b/services/web/frontend/js/shared/context/ide-context.js
new file mode 100644
index 0000000000..52546da157
--- /dev/null
+++ b/services/web/frontend/js/shared/context/ide-context.js
@@ -0,0 +1,30 @@
+import { createContext, useContext } from 'react'
+import PropTypes from 'prop-types'
+
+const IdeContext = createContext()
+
+IdeContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ $scope: PropTypes.object.isRequired,
+ }),
+}
+
+export function useIdeContext() {
+ const context = useContext(IdeContext)
+
+ if (!context) {
+ throw new Error('useIdeContext is only available inside IdeProvider')
+ }
+
+ return context
+}
+
+export function IdeProvider({ ide, children }) {
+ return {children}
+}
+IdeProvider.propTypes = {
+ children: PropTypes.any.isRequired,
+ ide: PropTypes.shape({
+ $scope: PropTypes.object.isRequired,
+ }).isRequired,
+}
diff --git a/services/web/frontend/js/shared/context/layout-context.js b/services/web/frontend/js/shared/context/layout-context.js
new file mode 100644
index 0000000000..c066f76089
--- /dev/null
+++ b/services/web/frontend/js/shared/context/layout-context.js
@@ -0,0 +1,86 @@
+import { createContext, useContext, useCallback, useMemo } from 'react'
+import PropTypes from 'prop-types'
+import useScopeValue from './util/scope-value-hook'
+import { useIdeContext } from './ide-context'
+
+export const LayoutContext = createContext()
+
+LayoutContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ view: PropTypes.string,
+ setView: PropTypes.func.isRequired,
+ chatIsOpen: PropTypes.bool,
+ setChatIsOpen: PropTypes.func.isRequired,
+ reviewPanelOpen: PropTypes.bool,
+ setReviewPanelOpen: PropTypes.func.isRequired,
+ leftMenuShown: PropTypes.bool,
+ setLeftMenuShown: PropTypes.func.isRequired,
+ pdfLayout: PropTypes.oneOf(['sideBySide', 'flat', 'split']).isRequired,
+ }).isRequired,
+}
+
+export function LayoutProvider({ children }) {
+ const { $scope } = useIdeContext()
+
+ const [view, _setView] = useScopeValue('ui.view')
+
+ const setView = useCallback(
+ value => {
+ _setView(oldValue => {
+ // ensure that the "history:toggle" event is broadcast when switching in or out of history view
+ if (value === 'history' || oldValue === 'history') {
+ $scope.toggleHistory()
+ }
+
+ return value
+ })
+ },
+ [$scope, _setView]
+ )
+
+ const [chatIsOpen, setChatIsOpen] = useScopeValue('ui.chatOpen')
+ const [reviewPanelOpen, setReviewPanelOpen] = useScopeValue(
+ 'ui.reviewPanelOpen'
+ )
+ const [leftMenuShown, setLeftMenuShown] = useScopeValue('ui.leftMenuShown')
+ const [pdfLayout] = useScopeValue('ui.pdfLayout', $scope)
+
+ const value = useMemo(
+ () => ({
+ view,
+ setView,
+ chatIsOpen,
+ setChatIsOpen,
+ reviewPanelOpen,
+ setReviewPanelOpen,
+ leftMenuShown,
+ setLeftMenuShown,
+ pdfLayout,
+ }),
+ [
+ chatIsOpen,
+ leftMenuShown,
+ pdfLayout,
+ reviewPanelOpen,
+ setChatIsOpen,
+ setLeftMenuShown,
+ setReviewPanelOpen,
+ setView,
+ view,
+ ]
+ )
+
+ return (
+ {children}
+ )
+}
+
+LayoutProvider.propTypes = {
+ children: PropTypes.any,
+}
+
+export function useLayoutContext(propTypes) {
+ const data = useContext(LayoutContext)
+ PropTypes.checkPropTypes(propTypes, data, 'data', 'LayoutContext.Provider')
+ return data
+}
diff --git a/services/web/frontend/js/shared/context/project-context.js b/services/web/frontend/js/shared/context/project-context.js
new file mode 100644
index 0000000000..aea17b34a3
--- /dev/null
+++ b/services/web/frontend/js/shared/context/project-context.js
@@ -0,0 +1,72 @@
+import { createContext, useContext } from 'react'
+import PropTypes from 'prop-types'
+import useScopeValue from './util/scope-value-hook'
+
+const ProjectContext = createContext()
+
+ProjectContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ _id: PropTypes.string.isRequired,
+ name: PropTypes.string.isRequired,
+ rootDoc_id: PropTypes.string,
+ members: PropTypes.arrayOf(
+ PropTypes.shape({
+ _id: PropTypes.string.isRequired,
+ })
+ ),
+ invites: PropTypes.arrayOf(
+ PropTypes.shape({
+ _id: PropTypes.string.isRequired,
+ })
+ ),
+ features: PropTypes.shape({
+ collaborators: PropTypes.number,
+ compileGroup: PropTypes.oneOf(['alpha', 'standard', 'priority'])
+ .isRequired,
+ }),
+ publicAccesLevel: PropTypes.string,
+ tokens: PropTypes.shape({
+ readOnly: PropTypes.string,
+ readAndWrite: PropTypes.string,
+ }),
+ owner: PropTypes.shape({
+ _id: PropTypes.string.isRequired,
+ email: PropTypes.string.isRequired,
+ }),
+ }),
+}
+
+export function useProjectContext(propTypes) {
+ const context = useContext(ProjectContext)
+
+ if (!context) {
+ throw new Error(
+ 'useProjectContext is only available inside ProjectProvider'
+ )
+ }
+
+ PropTypes.checkPropTypes(
+ propTypes,
+ context,
+ 'data',
+ 'ProjectContext.Provider'
+ )
+
+ return context
+}
+
+export function ProjectProvider({ children }) {
+ const [project] = useScopeValue('project', true)
+
+ // when the provider is created the project is still not added to the Angular scope.
+ // Name is also populated to prevent errors in existing React components
+ const value = project || { _id: window.project_id, name: '' }
+
+ return (
+ {children}
+ )
+}
+
+ProjectProvider.propTypes = {
+ children: PropTypes.any,
+}
diff --git a/services/web/frontend/js/shared/context/root-context.js b/services/web/frontend/js/shared/context/root-context.js
new file mode 100644
index 0000000000..d62ebd182c
--- /dev/null
+++ b/services/web/frontend/js/shared/context/root-context.js
@@ -0,0 +1,36 @@
+import PropTypes from 'prop-types'
+import createSharedContext from 'react2angular-shared-context'
+
+import { UserProvider } from './user-context'
+import { IdeProvider } from './ide-context'
+import { EditorProvider } from './editor-context'
+import { CompileProvider } from './compile-context'
+import { LayoutProvider } from './layout-context'
+import { ChatProvider } from '../../features/chat/context/chat-context'
+import { ProjectProvider } from './project-context'
+
+export function ContextRoot({ children, ide, settings }) {
+ return (
+
+
+
+
+
+
+ {children}
+
+
+
+
+
+
+ )
+}
+
+ContextRoot.propTypes = {
+ children: PropTypes.any,
+ ide: PropTypes.any.isRequired,
+ settings: PropTypes.any.isRequired,
+}
+
+export const rootContext = createSharedContext(ContextRoot)
diff --git a/services/web/frontend/js/shared/context/user-context.js b/services/web/frontend/js/shared/context/user-context.js
new file mode 100644
index 0000000000..a122078216
--- /dev/null
+++ b/services/web/frontend/js/shared/context/user-context.js
@@ -0,0 +1,32 @@
+import { createContext, useContext } from 'react'
+import PropTypes from 'prop-types'
+import useScopeValue from './util/scope-value-hook'
+
+export const UserContext = createContext()
+
+UserContext.Provider.propTypes = {
+ value: PropTypes.shape({
+ user: PropTypes.shape({
+ id: PropTypes.string,
+ allowedFreeTrial: PropTypes.boolean,
+ first_name: PropTypes.string,
+ last_name: PropTypes.string,
+ }),
+ }),
+}
+
+export function UserProvider({ children }) {
+ const [user] = useScopeValue('user', true)
+
+ return {children}
+}
+
+UserProvider.propTypes = {
+ children: PropTypes.any,
+}
+
+export function useUserContext(propTypes) {
+ const data = useContext(UserContext)
+ PropTypes.checkPropTypes(propTypes, data, 'data', 'UserContext.Provider')
+ return data
+}
diff --git a/services/web/frontend/js/shared/context/util/scope-value-hook.js b/services/web/frontend/js/shared/context/util/scope-value-hook.js
new file mode 100644
index 0000000000..3418b4bfc7
--- /dev/null
+++ b/services/web/frontend/js/shared/context/util/scope-value-hook.js
@@ -0,0 +1,44 @@
+import { useCallback, useEffect, useState } from 'react'
+import PropTypes from 'prop-types'
+import _ from 'lodash'
+import { useIdeContext } from '../ide-context'
+
+/**
+ * Binds a property in an Angular scope making it accessible in a React
+ * component. The interface is compatible with React.useState(), including
+ * the option of passing a function to the setter.
+ *
+ * @param {string} path - dot '.' path of a property in the Angular scope.
+ * @param {boolean} deep
+ * @returns {[any, function]} - Binded value and setter function tuple.
+ */
+export default function useScopeValue(path, deep = false) {
+ const { $scope } = useIdeContext({
+ $scope: PropTypes.object.isRequired,
+ })
+
+ const [value, setValue] = useState(() => _.get($scope, path))
+
+ useEffect(() => {
+ return $scope.$watch(
+ path,
+ newValue => {
+ setValue(deep ? _.cloneDeep(newValue) : newValue)
+ },
+ deep
+ )
+ }, [path, $scope, deep])
+
+ const scopeSetter = useCallback(
+ newValue => {
+ setValue(val => {
+ const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
+ $scope.$applyAsync(() => _.set($scope, path, actualNewValue))
+ return actualNewValue
+ })
+ },
+ [path, $scope]
+ )
+
+ return [value, scopeSetter]
+}
diff --git a/services/web/frontend/js/shared/hooks/use-abort-controller.js b/services/web/frontend/js/shared/hooks/use-abort-controller.js
new file mode 100644
index 0000000000..c6ad09e1b7
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-abort-controller.js
@@ -0,0 +1,14 @@
+import 'abort-controller/polyfill'
+import { useEffect, useState } from 'react'
+
+export default function useAbortController() {
+ const [controller] = useState(() => new AbortController())
+
+ useEffect(() => {
+ return () => {
+ controller.abort()
+ }
+ }, [controller])
+
+ return controller
+}
diff --git a/services/web/frontend/js/shared/hooks/use-browser-window.js b/services/web/frontend/js/shared/hooks/use-browser-window.js
new file mode 100644
index 0000000000..fa1c032ad9
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-browser-window.js
@@ -0,0 +1,68 @@
+import { useEffect, useState } from 'react'
+
+let titleIsFlashing = false
+let originalTitle
+let flashIntervalHandle
+
+function flashTitle(message) {
+ if (document.hasFocus() || titleIsFlashing) {
+ return
+ }
+
+ function swapTitle() {
+ if (window.document.title === originalTitle) {
+ window.document.title = message
+ } else {
+ window.document.title = originalTitle
+ }
+ }
+
+ originalTitle = window.document.title
+ window.document.title = message
+ titleIsFlashing = true
+ flashIntervalHandle = setInterval(swapTitle, 800)
+}
+
+function stopFlashingTitle() {
+ if (!titleIsFlashing) {
+ return
+ }
+
+ clearInterval(flashIntervalHandle)
+ window.document.title = originalTitle
+ originalTitle = undefined
+ titleIsFlashing = false
+}
+
+function setTitle(title) {
+ if (titleIsFlashing) {
+ originalTitle = title
+ } else {
+ window.document.title = title
+ }
+}
+
+function useBrowserWindow() {
+ const [hasFocus, setHasFocus] = useState(document.hasFocus())
+
+ useEffect(() => {
+ function handleFocusEvent() {
+ setHasFocus(true)
+ }
+
+ function handleBlurEvent() {
+ setHasFocus(false)
+ }
+
+ window.addEventListener('focus', handleFocusEvent)
+ window.addEventListener('blur', handleBlurEvent)
+ return () => {
+ window.removeEventListener('focus', handleFocusEvent)
+ window.removeEventListener('blur', handleBlurEvent)
+ }
+ }, [])
+
+ return { hasFocus, flashTitle, stopFlashingTitle, setTitle }
+}
+
+export default useBrowserWindow
diff --git a/services/web/frontend/js/shared/hooks/use-debounce.js b/services/web/frontend/js/shared/hooks/use-debounce.js
new file mode 100644
index 0000000000..497117cdfa
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-debounce.js
@@ -0,0 +1,17 @@
+import { useEffect, useState } from 'react'
+
+export default function useDebounce(value, delay = 0) {
+ const [debouncedValue, setDebouncedValue] = useState(value)
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => {
+ setDebouncedValue(value)
+ }, delay)
+
+ return () => {
+ window.clearTimeout(timer)
+ }
+ }, [value, delay])
+
+ return debouncedValue
+}
diff --git a/services/web/frontend/js/shared/hooks/use-dropdown.js b/services/web/frontend/js/shared/hooks/use-dropdown.js
new file mode 100644
index 0000000000..b58013e2b4
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-dropdown.js
@@ -0,0 +1,54 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { findDOMNode } from 'react-dom'
+
+export default function useDropdown(defaultOpen = false) {
+ const [open, setOpen] = useState(defaultOpen)
+
+ // store the dropdown node for use in the "click outside" event listener
+ const ref = useRef(null)
+
+ // react-bootstrap v0.x passes `component` instead of `node` to the ref callback
+ const handleRef = useCallback(
+ component => {
+ if (component) {
+ // eslint-disable-next-line react/no-find-dom-node
+ ref.current = findDOMNode(component)
+ }
+ },
+ [ref]
+ )
+
+ // prevent a click on the dropdown toggle propagating to the original handler
+ const handleClick = useCallback(event => {
+ event.stopPropagation()
+ }, [])
+
+ // handle dropdown toggle
+ const handleToggle = useCallback(value => {
+ setOpen(value)
+ }, [])
+
+ // close the dropdown on click outside the dropdown
+ const handleDocumentClick = useCallback(
+ event => {
+ if (ref.current && !ref.current.contains(event.target)) {
+ setOpen(false)
+ }
+ },
+ [ref]
+ )
+
+ // add/remove listener for click anywhere in document
+ useEffect(() => {
+ if (open) {
+ document.addEventListener('mousedown', handleDocumentClick)
+ }
+
+ return () => {
+ document.removeEventListener('mousedown', handleDocumentClick)
+ }
+ }, [open, handleDocumentClick])
+
+ // return props for the Dropdown component
+ return { ref: handleRef, onClick: handleClick, onToggle: handleToggle, open }
+}
diff --git a/services/web/frontend/js/shared/hooks/use-expand-collapse.js b/services/web/frontend/js/shared/hooks/use-expand-collapse.js
new file mode 100644
index 0000000000..2fa4aa6fbe
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-expand-collapse.js
@@ -0,0 +1,64 @@
+import { useRef, useState, useLayoutEffect } from 'react'
+import classNames from 'classnames'
+
+function useExpandCollapse({
+ initiallyExpanded = false,
+ collapsedSize = '0',
+ dimension = 'height',
+ classes = {},
+} = {}) {
+ const ref = useRef()
+ const [isExpanded, setIsExpanded] = useState(initiallyExpanded)
+ const [sizing, setSizing] = useState({
+ size: null,
+ needsExpandCollapse: null,
+ })
+
+ useLayoutEffect(() => {
+ const expandCollapseEl = ref.current
+ if (expandCollapseEl) {
+ const expandedSize =
+ dimension === 'height'
+ ? expandCollapseEl.scrollHeight
+ : expandCollapseEl.scrollWidth
+
+ const needsExpandCollapse = expandedSize > collapsedSize
+
+ if (isExpanded) {
+ setSizing({ size: expandedSize, needsExpandCollapse })
+ } else {
+ setSizing({
+ size: needsExpandCollapse ? collapsedSize : expandedSize,
+ needsExpandCollapse,
+ })
+ }
+ }
+ }, [isExpanded, collapsedSize, dimension])
+
+ const expandableClasses = classNames(
+ 'expand-collapse-container',
+ classes.container,
+ !isExpanded ? classes.containerCollapsed : null
+ )
+
+ function handleToggle() {
+ setIsExpanded(!isExpanded)
+ }
+
+ return {
+ isExpanded,
+ needsExpandCollapse: sizing.needsExpandCollapse,
+ expandableProps: {
+ ref,
+ style: {
+ [dimension === 'height' ? 'height' : 'width']: `${sizing.size}px`,
+ },
+ className: expandableClasses,
+ },
+ toggleProps: {
+ onClick: handleToggle,
+ },
+ }
+}
+
+export default useExpandCollapse
diff --git a/services/web/frontend/js/shared/hooks/use-is-mounted.js b/services/web/frontend/js/shared/hooks/use-is-mounted.js
new file mode 100644
index 0000000000..3fe667c3db
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-is-mounted.js
@@ -0,0 +1,13 @@
+import { useEffect, useRef } from 'react'
+
+export default function useIsMounted() {
+ const isMounted = useRef(true)
+
+ useEffect(() => {
+ return () => {
+ isMounted.current = false
+ }
+ }, [isMounted])
+
+ return isMounted
+}
diff --git a/services/web/frontend/js/shared/hooks/use-persisted-state.js b/services/web/frontend/js/shared/hooks/use-persisted-state.js
new file mode 100644
index 0000000000..3cc8f95e29
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-persisted-state.js
@@ -0,0 +1,25 @@
+import { useState, useCallback } from 'react'
+import localStorage from '../../infrastructure/local-storage'
+
+function usePersistedState(key, defaultValue) {
+ const [value, setValue] = useState(() => {
+ const keyExists = localStorage.getItem(key) != null
+ return keyExists ? localStorage.getItem(key) : defaultValue
+ })
+
+ const updateFunction = useCallback(
+ newValue => {
+ if (newValue === defaultValue) {
+ localStorage.removeItem(key)
+ } else {
+ localStorage.setItem(key, newValue)
+ }
+ setValue(newValue)
+ },
+ [key, defaultValue]
+ )
+
+ return [value, updateFunction]
+}
+
+export default usePersistedState
diff --git a/services/web/frontend/js/shared/hooks/use-ref-with-auto-focus.js b/services/web/frontend/js/shared/hooks/use-ref-with-auto-focus.js
new file mode 100644
index 0000000000..c537b78be5
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-ref-with-auto-focus.js
@@ -0,0 +1,17 @@
+import { useRef, useEffect } from 'react'
+
+export function useRefWithAutoFocus() {
+ const autoFocusedRef = useRef()
+
+ useEffect(() => {
+ if (autoFocusedRef.current) {
+ window.requestAnimationFrame(() => {
+ if (autoFocusedRef.current) {
+ autoFocusedRef.current.focus()
+ }
+ })
+ }
+ }, [autoFocusedRef])
+
+ return { autoFocusedRef }
+}
diff --git a/services/web/frontend/js/shared/hooks/use-resize-observer.js b/services/web/frontend/js/shared/hooks/use-resize-observer.js
new file mode 100644
index 0000000000..637e21b9b1
--- /dev/null
+++ b/services/web/frontend/js/shared/hooks/use-resize-observer.js
@@ -0,0 +1,36 @@
+import { useLayoutEffect, useRef, useCallback } from 'react'
+
+function useResizeObserver(observedElement, observedData, callback) {
+ const resizeObserver = useRef()
+
+ const observe = useCallback(() => {
+ resizeObserver.current = new ResizeObserver(function (elementsObserved) {
+ callback(elementsObserved[0])
+ })
+ }, [callback])
+
+ function unobserve(observedCurrent) {
+ resizeObserver.current.unobserve(observedCurrent)
+ }
+
+ useLayoutEffect(() => {
+ if ('ResizeObserver' in window) {
+ const observedCurrent = observedElement && observedElement.current
+ if (observedCurrent) {
+ observe(observedElement.current)
+ }
+
+ if (resizeObserver.current && observedCurrent) {
+ resizeObserver.current.observe(observedCurrent)
+ }
+
+ return () => {
+ if (observedCurrent) {
+ unobserve(observedCurrent)
+ }
+ }
+ }
+ }, [observedElement, observedData, observe])
+}
+
+export default useResizeObserver
diff --git a/services/web/frontend/js/shared/utils/colors.js b/services/web/frontend/js/shared/utils/colors.js
new file mode 100644
index 0000000000..4a3434597c
--- /dev/null
+++ b/services/web/frontend/js/shared/utils/colors.js
@@ -0,0 +1,38 @@
+import md5 from 'crypto-js/md5'
+
+const ANONYMOUS_HUE = 100
+const OWN_HUE = 200 // We will always appear as this color to ourselves
+const OWN_HUE_BLOCKED_SIZE = 20 // no other user should have a HUE in this range
+const TOTAL_HUES = 360 // actually 361, but 360 for legacy reasons
+
+export function getHueForUserId(userId, currentUserId) {
+ if (userId == null || userId === 'anonymous-user') {
+ return ANONYMOUS_HUE
+ }
+
+ if (currentUserId === userId) {
+ return OWN_HUE
+ }
+
+ let hue = getHueForId(userId)
+
+ // if `hue` is within `OWN_HUE_BLOCKED_SIZE` degrees of the personal hue
+ // (`OWN_HUE`), shift `hue` to the end of available hues by adding
+ if (
+ hue > OWN_HUE - OWN_HUE_BLOCKED_SIZE &&
+ hue < OWN_HUE + OWN_HUE_BLOCKED_SIZE
+ ) {
+ hue = hue - OWN_HUE // `hue` now at 0 +/- `OWN_HUE_BLOCKED_SIZE`
+ hue = hue + TOTAL_HUES - OWN_HUE_BLOCKED_SIZE
+ }
+
+ return hue
+}
+
+function getHueForId(id) {
+ const hash = md5(id)
+ const hue =
+ parseInt(hash.toString().slice(0, 8), 16) %
+ (TOTAL_HUES - OWN_HUE_BLOCKED_SIZE * 2)
+ return hue
+}
diff --git a/services/web/frontend/js/utils/EventEmitter.js b/services/web/frontend/js/utils/EventEmitter.js
new file mode 100644
index 0000000000..f2ddd5d81e
--- /dev/null
+++ b/services/web/frontend/js/utils/EventEmitter.js
@@ -0,0 +1,79 @@
+/* eslint-disable
+ camelcase,
+ max-len,
+ no-return-assign,
+ no-unused-vars,
+*/
+// TODO: This file was created by bulk-decaffeinate.
+// Fix any style issues and re-enable lint.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
+ */
+// Simple event emitter implementation, but has a slightly unusual API for
+// removing specific listeners. If a specific listener needs to be removed
+// (instead of all listeners), then it needs to use a "namespace":
+// Create a listener on the foo event with bar namespace: .on 'foo.bar'
+// Trigger all events for the foo event (including namespaces): .trigger 'foo'
+// Remove all listeners for the foo event (including namespaces): .off 'foo'
+// Remove a listener for the foo event with the bar namespace: .off 'foo.bar'
+let EventEmitter
+
+export default EventEmitter = class EventEmitter {
+ on(event, callback) {
+ let namespace
+ if (!this.events) {
+ this.events = {}
+ }
+ ;[event, namespace] = Array.from(event.split('.'))
+ if (!this.events[event]) {
+ this.events[event] = []
+ }
+ return this.events[event].push({
+ callback,
+ namespace,
+ })
+ }
+
+ off(event) {
+ if (!this.events) {
+ this.events = {}
+ }
+ if (event != null) {
+ let namespace
+ ;[event, namespace] = Array.from(event.split('.'))
+ if (namespace == null) {
+ // Clear all listeners for event
+ return delete this.events[event]
+ } else {
+ // Clear only namespaced listeners
+ const remaining_events = []
+ for (const callback of Array.from(this.events[event] || [])) {
+ if (callback.namespace !== namespace) {
+ remaining_events.push(callback)
+ }
+ }
+ return (this.events[event] = remaining_events)
+ }
+ } else {
+ // Remove all listeners
+ return (this.events = {})
+ }
+ }
+
+ trigger(event, ...args) {
+ if (!this.events) {
+ this.events = {}
+ }
+ return Array.from(this.events[event] || []).map(callback =>
+ callback.callback(...Array.from(args || []))
+ )
+ }
+
+ emit(...args) {
+ return this.trigger(...Array.from(args || []))
+ }
+}
diff --git a/services/web/frontend/js/utils/meta.js b/services/web/frontend/js/utils/meta.js
new file mode 100644
index 0000000000..bf707b6af7
--- /dev/null
+++ b/services/web/frontend/js/utils/meta.js
@@ -0,0 +1,48 @@
+import _ from 'lodash'
+
+// cache for parsed values
+const cache = new Map()
+
+export default function getMeta(name, fallback) {
+ if (cache.has(name)) return cache.get(name)
+ const element = document.head.querySelector(`meta[name="${name}"]`)
+ if (!element) {
+ return fallback
+ }
+ const plainTextValue = element.content
+ let value
+ switch (element.dataset.type) {
+ case 'boolean':
+ // in pug: content=false -> no content field
+ // in pug: content=true -> empty content field
+ value = element.hasAttribute('content')
+ break
+ case 'json':
+ if (!plainTextValue) {
+ // JSON.parse('') throws
+ value = undefined
+ } else {
+ value = JSON.parse(plainTextValue)
+ }
+ break
+ default:
+ value = plainTextValue
+ }
+ cache.set(name, value)
+ return value
+}
+
+function convertMetaToWindowAttributes() {
+ window.data = window.data || {}
+ Array.from(document.querySelectorAll('meta[name^="ol-"]'))
+ .map(element => element.name)
+ // process short labels before long ones:
+ // e.g. assign 'sharelatex' before 'sharelatex.templates'
+ .sort()
+ .forEach(nameWithNamespace => {
+ const label = nameWithNamespace.slice('ol-'.length)
+ _.set(window, label, getMeta(nameWithNamespace))
+ _.set(window.data, label, getMeta(nameWithNamespace))
+ })
+}
+convertMetaToWindowAttributes()
diff --git a/services/web/frontend/js/utils/webpack-public-path.js b/services/web/frontend/js/utils/webpack-public-path.js
new file mode 100644
index 0000000000..674abbf59a
--- /dev/null
+++ b/services/web/frontend/js/utils/webpack-public-path.js
@@ -0,0 +1,5 @@
+import getMeta from './meta'
+
+// Configure dynamically loaded assets (via webpack) to be downloaded from CDN
+// See: https://webpack.js.org/guides/public-path/#on-the-fly
+__webpack_public_path__ = getMeta('ol-baseAssetPath')
diff --git a/services/web/frontend/js/vendor/libs/angular-autocomplete/ac_template.html b/services/web/frontend/js/vendor/libs/angular-autocomplete/ac_template.html
new file mode 100755
index 0000000000..8058d84589
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/angular-autocomplete/ac_template.html
@@ -0,0 +1,18 @@
+
diff --git a/services/web/frontend/js/vendor/libs/angular-autocomplete/angular-autocomplete.js b/services/web/frontend/js/vendor/libs/angular-autocomplete/angular-autocomplete.js
new file mode 100644
index 0000000000..895d51f420
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/angular-autocomplete/angular-autocomplete.js
@@ -0,0 +1,258 @@
+/* --- Made by justgoscha and licensed under MIT license --- */
+
+var app = angular.module('autocomplete', []);
+
+app.directive('autocomplete', function() {
+ var index = -1;
+
+ return {
+ restrict: 'E',
+ scope: {
+ searchParam: '=ngModel',
+ suggestions: '=data',
+ onType: '=onType',
+ onSelect: '=onSelect'
+ },
+ controller: ['$scope', function($scope){
+ // the index of the suggestions that's currently selected
+ $scope.selectedIndex = -1;
+
+ // set new index
+ $scope.setIndex = function(i){
+ $scope.selectedIndex = parseInt(i);
+ };
+
+ this.setIndex = function(i){
+ $scope.setIndex(i);
+ $scope.$apply();
+ };
+
+ $scope.getIndex = function(i){
+ return $scope.selectedIndex;
+ };
+
+ // watches if the parameter filter should be changed
+ var watching = true;
+
+ // autocompleting drop down on/off
+ $scope.completing = false;
+
+ // starts autocompleting on typing in something
+ $scope.$watch('searchParam', function(newValue, oldValue){
+ if (oldValue === newValue) {
+ return;
+ }
+
+ if(watching && $scope.searchParam) {
+ $scope.completing = true;
+ $scope.searchFilter = $scope.searchParam;
+ $scope.selectedIndex = -1;
+ }
+
+ // function thats passed to on-type attribute gets executed
+ if($scope.onType)
+ $scope.onType($scope.searchParam);
+ });
+
+ // for hovering over suggestions
+ this.preSelect = function(suggestion){
+
+ watching = false;
+
+ // this line determines if it is shown
+ // in the input field before it's selected:
+ //$scope.searchParam = suggestion;
+
+ $scope.$apply();
+ watching = true;
+
+ };
+
+ $scope.preSelect = this.preSelect;
+
+ this.preSelectOff = function(){
+ watching = true;
+ };
+
+ $scope.preSelectOff = this.preSelectOff;
+
+ // selecting a suggestion with RIGHT ARROW or ENTER
+ $scope.select = function(suggestion){
+ if(suggestion){
+ $scope.searchParam = suggestion;
+ $scope.searchFilter = suggestion;
+ if($scope.onSelect)
+ $scope.onSelect(suggestion);
+ }
+ watching = false;
+ $scope.completing = false;
+ setTimeout(function(){watching = true;},1000);
+ $scope.setIndex(-1);
+ };
+
+
+ }],
+ link: function(scope, element, attrs){
+
+ var attr = '';
+
+ // Default atts
+ scope.attrs = {
+ "placeholder": "start typing...",
+ "class": "",
+ "id": "",
+ "inputclass": "",
+ "inputid": ""
+ };
+
+ for (var a in attrs) {
+ attr = a.replace('attr', '').toLowerCase();
+ // add attribute overriding defaults
+ // and preventing duplication
+ if (a.indexOf('attr') === 0) {
+ scope.attrs[attr] = attrs[a];
+ }
+ }
+
+ if (attrs.clickActivation) {
+ element[0].onclick = function(e){
+ if(!scope.searchParam){
+ scope.completing = true;
+ scope.$apply();
+ }
+ };
+ }
+
+ var key = {left: 37, up: 38, right: 39, down: 40 , enter: 13, esc: 27};
+
+ document.addEventListener("keydown", function(e){
+ var keycode = e.keyCode || e.which;
+
+ switch (keycode){
+ case key.esc:
+ // disable suggestions on escape
+ scope.select();
+ scope.setIndex(-1);
+ scope.$apply();
+ e.preventDefault();
+ }
+ }, true);
+
+ document.addEventListener("blur", function(e){
+ // disable suggestions on blur
+ // we do a timeout to prevent hiding it before a click event is registered
+ setTimeout(function() {
+ scope.select();
+ scope.setIndex(-1);
+ scope.$apply();
+ }, 200);
+ }, true);
+
+ element[0].addEventListener("keydown",function (e){
+ var keycode = e.keyCode || e.which;
+
+ var l = angular.element(this).find('li').length;
+
+ // implementation of the up and down movement in the list of suggestions
+ switch (keycode){
+ case key.up:
+
+ index = scope.getIndex()-1;
+ if(index<-1){
+ index = l-1;
+ } else if (index >= l ){
+ index = -1;
+ scope.setIndex(index);
+ scope.preSelectOff();
+ break;
+ }
+ scope.setIndex(index);
+
+ if(index!==-1)
+ scope.preSelect(angular.element(angular.element(this).find('li')[index]).text());
+
+ scope.$apply();
+
+ break;
+ case key.down:
+ index = scope.getIndex()+1;
+ if(index<-1){
+ index = l-1;
+ } else if (index >= l ){
+ index = -1;
+ scope.setIndex(index);
+ scope.preSelectOff();
+ scope.$apply();
+ break;
+ }
+ scope.setIndex(index);
+
+ if(index!==-1)
+ scope.preSelect(angular.element(angular.element(this).find('li')[index]).text());
+
+ break;
+ case key.left:
+ break;
+ case key.right:
+ case key.enter:
+
+ index = scope.getIndex();
+ // scope.preSelectOff();
+ if(index !== -1)
+ scope.select(angular.element(angular.element(this).find('li')[index]).text());
+ scope.setIndex(-1);
+ scope.$apply();
+
+ break;
+ case key.esc:
+ // disable suggestions on escape
+ scope.select();
+ scope.setIndex(-1);
+ scope.$apply();
+ e.preventDefault();
+ break;
+ default:
+ return;
+ }
+
+ if(scope.getIndex()!==-1 || keycode == key.enter)
+ e.preventDefault();
+ });
+ },
+ templateUrl: 'js/libs/angular-autocomplete/ac_template.html'
+ };
+});
+
+app.filter('highlight', ['$sce', function ($sce) {
+ return function (input, searchParam) {
+ if (typeof input === 'function') return '';
+ if (searchParam) {
+ var words = '(' +
+ searchParam.split(/\ /).join(' |') + '|' +
+ searchParam.split(/\ /).join('|') +
+ ')',
+ exp = new RegExp(words, 'gi');
+ if (words.length) {
+ input = input.replace(exp, "$1 ");
+ }
+ }
+ return $sce.trustAsHtml(input);
+ };
+}]);
+
+app.directive('suggestion', function(){
+ return {
+ restrict: 'A',
+ require: '^autocomplete', // ^look for controller on parents element
+ link: function(scope, element, attrs, autoCtrl){
+ element.bind('mouseenter', function() {
+ autoCtrl.preSelect(attrs.val);
+ autoCtrl.setIndex(attrs.index);
+ });
+
+ element.bind('mouseleave', function() {
+ autoCtrl.preSelectOff();
+ });
+ }
+ };
+});
diff --git a/services/web/frontend/js/vendor/libs/angular-cookie.js b/services/web/frontend/js/vendor/libs/angular-cookie.js
new file mode 100644
index 0000000000..d0ffd46e0f
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/angular-cookie.js
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2013 Ivan Pusic
+ * Contributors:
+ * Matjaz Lipus
+ */
+ //https://github.com/ivpusic/angular-cookie/blob/master/angular-cookie.js
+angular.module('ivpusic.cookie', ['ipCookie']);
+angular.module('ipCookie', ['ng']).
+factory('ipCookie', ['$document',
+ function ($document) {
+ 'use strict';
+
+ return (function () {
+ function cookieFun(key, value, options) {
+
+ var cookies,
+ list,
+ i,
+ cookie,
+ pos,
+ name,
+ hasCookies,
+ all,
+ expiresFor;
+
+ options = options || {};
+
+ if (value !== undefined) {
+ // we are setting value
+ value = typeof value === 'object' ? JSON.stringify(value) : String(value);
+
+ if (typeof options.expires === 'number') {
+ expiresFor = options.expires;
+ options.expires = new Date();
+ // Trying to delete a cookie; set a date far in the past
+ if (expiresFor === -1) {
+ options.expires = new Date('Thu, 01 Jan 1970 00:00:00 GMT');
+ // A new
+ } else if (options.expirationUnit !== undefined) {
+ if (options.expirationUnit === 'hours') {
+ options.expires.setHours(options.expires.getHours() + expiresFor);
+ } else if (options.expirationUnit === 'minutes') {
+ options.expires.setMinutes(options.expires.getMinutes() + expiresFor);
+ } else if (options.expirationUnit === 'seconds') {
+ options.expires.setSeconds(options.expires.getSeconds() + expiresFor);
+ } else {
+ options.expires.setDate(options.expires.getDate() + expiresFor);
+ }
+ } else {
+ options.expires.setDate(options.expires.getDate() + expiresFor);
+ }
+ }
+ return ($document[0].cookie = [
+ encodeURIComponent(key),
+ '=',
+ encodeURIComponent(value),
+ options.expires ? '; expires=' + options.expires.toUTCString() : '',
+ options.path ? '; path=' + options.path : '',
+ options.domain ? '; domain=' + options.domain : '',
+ options.secure ? '; secure' : ''
+ ].join(''));
+ }
+
+ list = [];
+ all = $document[0].cookie;
+ if (all) {
+ list = all.split('; ');
+ }
+
+ cookies = {};
+ hasCookies = false;
+
+ for (i = 0; i < list.length; ++i) {
+ if (list[i]) {
+ cookie = list[i];
+ pos = cookie.indexOf('=');
+ name = cookie.substring(0, pos);
+ value = decodeURIComponent(cookie.substring(pos + 1));
+
+ if (key === undefined || key === name) {
+ try {
+ cookies[name] = JSON.parse(value);
+ } catch (e) {
+ cookies[name] = value;
+ }
+ if (key === name) {
+ return cookies[name];
+ }
+ hasCookies = true;
+ }
+ }
+ }
+ if (hasCookies && key === undefined) {
+ return cookies;
+ }
+ }
+ cookieFun.remove = function (key, options) {
+ var hasCookie = cookieFun(key) !== undefined;
+
+ if (hasCookie) {
+ if (!options) {
+ options = {};
+ }
+ options.expires = -1;
+ cookieFun(key, '', options);
+ }
+ return hasCookie;
+ };
+ return cookieFun;
+ }());
+ }
+]);
\ No newline at end of file
diff --git a/services/web/frontend/js/vendor/libs/bib-log-parser.js b/services/web/frontend/js/vendor/libs/bib-log-parser.js
new file mode 100644
index 0000000000..d0ae35b9d5
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/bib-log-parser.js
@@ -0,0 +1,219 @@
+// Generated by CoffeeScript 1.10.0
+define(function() {
+ var BAD_CROSS_REFERENCE_REGEX, BibLogParser, LINE_SPLITTER_REGEX, MESSAGE_LEVELS, MULTILINE_COMMAND_ERROR_REGEX, MULTILINE_ERROR_REGEX, MULTILINE_WARNING_REGEX, SINGLELINE_WARNING_REGEX, consume, errorParsers, warningParsers;
+ LINE_SPLITTER_REGEX = /^\[(\d+)].*>\s(INFO|WARN|ERROR)\s-\s(.*)$/;
+ MESSAGE_LEVELS = {
+ "INFO": "info",
+ "WARN": "warning",
+ "ERROR": "error"
+ };
+ BibLogParser = function(text, options) {
+ if (typeof text !== 'string') {
+ throw new Error("BibLogParser Error: text parameter must be a string");
+ }
+ this.text = text.replace(/(\r\n)|\r/g, '\n');
+ this.options = options || {};
+ this.lines = text.split('\n');
+ };
+ consume = function(logText, regex, process) {
+ var iterationCount, match, newEntry, re, result, text;
+ text = logText;
+ result = [];
+ re = regex;
+ iterationCount = 0;
+ while (match = re.exec(text)) {
+ iterationCount += 1;
+ newEntry = process(match);
+
+ // Too many log entries can cause browser crashes
+ // Construct a too many files error from the last match
+ var maxErrors = 100;
+ if (iterationCount >= maxErrors) {
+ var level = newEntry.level + "s";
+ newEntry.message = [
+ "Over",
+ maxErrors,
+ level,
+ "returned. Download raw logs to see full list"
+ ].join(" ");
+ newEntry.line = undefined;
+ result.unshift(newEntry);
+ return [result, ""];
+ }
+
+ result.push(newEntry);
+ text = (match.input.slice(0, match.index)) + (match.input.slice(match.index + match[0].length + 1, match.input.length));
+ }
+ return [result, text];
+ };
+ MULTILINE_WARNING_REGEX = /^Warning--(.+)\n--line (\d+) of file (.+)$/m;
+ SINGLELINE_WARNING_REGEX = /^Warning--(.+)$/m;
+ MULTILINE_ERROR_REGEX = /^(.*)---line (\d+) of file (.*)\n([^]+?)\nI'm skipping whatever remains of this entry$/m;
+ BAD_CROSS_REFERENCE_REGEX = /^(A bad cross reference---entry ".+?"\nrefers to entry.+?, which doesn't exist)$/m;
+ MULTILINE_COMMAND_ERROR_REGEX = /^(.*)\n?---line (\d+) of file (.*)\n([^]+?)\nI'm skipping whatever remains of this command$/m;
+ // Errors hit in BST file have a slightly different format
+ BST_ERROR_REGEX = /^(.*?)\nwhile executing---line (\d+) of file (.*)/m;
+ warningParsers = [
+ [
+ MULTILINE_WARNING_REGEX, function(match) {
+ var fileName, fullMatch, lineNumber, message;
+ fullMatch = match[0], message = match[1], lineNumber = match[2], fileName = match[3];
+ return {
+ file: fileName,
+ level: "warning",
+ message: message,
+ line: lineNumber,
+ raw: fullMatch
+ };
+ }
+ ], [
+ SINGLELINE_WARNING_REGEX, function(match) {
+ var fullMatch, message;
+ fullMatch = match[0], message = match[1];
+ return {
+ file: '',
+ level: "warning",
+ message: message,
+ line: '',
+ raw: fullMatch
+ };
+ }
+ ]
+ ];
+ errorParsers = [
+ [
+ MULTILINE_ERROR_REGEX, function(match) {
+ var fileName, firstMessage, fullMatch, lineNumber, secondMessage;
+ fullMatch = match[0], firstMessage = match[1], lineNumber = match[2], fileName = match[3], secondMessage = match[4];
+ return {
+ file: fileName,
+ level: "error",
+ message: firstMessage + '\n' + secondMessage,
+ line: lineNumber,
+ raw: fullMatch
+ };
+ }
+ ], [
+ BAD_CROSS_REFERENCE_REGEX, function(match) {
+ var fullMatch, message;
+ fullMatch = match[0], message = match[1];
+ return {
+ file: '',
+ level: "error",
+ message: message,
+ line: '',
+ raw: fullMatch
+ };
+ }
+ ], [
+ MULTILINE_COMMAND_ERROR_REGEX, function(match) {
+ var fileName, firstMessage, fullMatch, lineNumber, secondMessage;
+ fullMatch = match[0], firstMessage = match[1], lineNumber = match[2], fileName = match[3], secondMessage = match[4];
+ return {
+ file: fileName,
+ level: "error",
+ message: firstMessage + '\n' + secondMessage,
+ line: lineNumber,
+ raw: fullMatch
+ };
+ }
+ ],[
+ BST_ERROR_REGEX, function(match) {
+ var fileName, firstMessage, fullMatch, lineNumber, secondMessage;
+ fullMatch = match[0], firstMessage = match[1], lineNumber = match[2], fileName = match[3];
+ return {
+ file: fileName,
+ level: "error",
+ message: firstMessage,
+ line: lineNumber,
+ raw: fullMatch
+ };
+ }
+ ]
+ ];
+
+ (function() {
+ this.parseBibtex = function() {
+ var allErrors, allWarnings, ref, ref1, remainingText, result;
+ result = {
+ all: [],
+ errors: [],
+ warnings: [],
+ files: [],
+ typesetting: []
+ };
+ ref = warningParsers.reduce(function(accumulator, parser) {
+ var _remainingText, currentWarnings, process, ref, regex, text, warnings;
+ currentWarnings = accumulator[0], text = accumulator[1];
+ regex = parser[0], process = parser[1];
+ ref = consume(text, regex, process), warnings = ref[0], _remainingText = ref[1];
+ return [currentWarnings.concat(warnings), _remainingText];
+ }, [[], this.text]), allWarnings = ref[0], remainingText = ref[1];
+ ref1 = errorParsers.reduce(function(accumulator, parser) {
+ var _remainingText, currentErrors, errors, process, ref1, regex, text;
+ currentErrors = accumulator[0], text = accumulator[1];
+ regex = parser[0], process = parser[1];
+ ref1 = consume(text, regex, process), errors = ref1[0], _remainingText = ref1[1];
+ return [currentErrors.concat(errors), _remainingText];
+ }, [[], remainingText]), allErrors = ref1[0], remainingText = ref1[1];
+ result.warnings = allWarnings;
+ result.errors = allErrors;
+ result.all = allWarnings.concat(allErrors);
+ return result;
+ };
+ this.parseBiber = function() {
+ var result;
+ result = {
+ all: [],
+ errors: [],
+ warnings: [],
+ files: [],
+ typesetting: []
+ };
+ this.lines.forEach(function(line) {
+ var _, fileName, fullLine, lineMatch, lineNumber, match, message, messageType, newEntry, realMessage;
+ match = line.match(LINE_SPLITTER_REGEX);
+ if (match) {
+ fullLine = match[0], lineNumber = match[1], messageType = match[2], message = match[3];
+ newEntry = {
+ file: '',
+ level: MESSAGE_LEVELS[messageType] || "INFO",
+ message: message,
+ line: '',
+ raw: fullLine
+ };
+ lineMatch = newEntry.message.match(/^BibTeX subsystem: \/.+\/(\w+\.\w+)_.+, line (\d+), (.+)$/);
+ if (lineMatch && lineMatch.length === 4) {
+ _ = lineMatch[0], fileName = lineMatch[1], lineNumber = lineMatch[2], realMessage = lineMatch[3];
+ newEntry.file = fileName;
+ newEntry.line = lineNumber;
+ newEntry.message = realMessage;
+ }
+ result.all.push(newEntry);
+ switch (newEntry.level) {
+ case 'error':
+ return result.errors.push(newEntry);
+ case 'warning':
+ return result.warnings.push(newEntry);
+ }
+ }
+ });
+ return result;
+ };
+ return this.parse = function() {
+ var firstLine;
+ firstLine = this.lines[0];
+ if (firstLine.match(/^.*INFO - This is Biber.*$/)) {
+ return this.parseBiber();
+ } else if (firstLine.match(/^This is BibTeX, Version.+$/)) {
+ return this.parseBibtex();
+ } else {
+ throw new Error("BibLogParser Error: cannot determine whether text is biber or bibtex output");
+ }
+ };
+ }).call(BibLogParser.prototype);
+ BibLogParser.parse = function(text, options) {
+ return new BibLogParser(text, options).parse();
+ };
+ return BibLogParser;
+});
diff --git a/services/web/frontend/js/vendor/libs/fineuploader-5.15.4.js b/services/web/frontend/js/vendor/libs/fineuploader-5.15.4.js
new file mode 100644
index 0000000000..606a2fb70a
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/fineuploader-5.15.4.js
@@ -0,0 +1,7455 @@
+// Fine Uploader 5.15.4 - MIT licensed. http://fineuploader.com
+(function(global) {
+ var qq = function(element) {
+ "use strict";
+ return {
+ hide: function() {
+ element.style.display = "none";
+ return this;
+ },
+ attach: function(type, fn) {
+ if (element.addEventListener) {
+ element.addEventListener(type, fn, false);
+ } else if (element.attachEvent) {
+ element.attachEvent("on" + type, fn);
+ }
+ return function() {
+ qq(element).detach(type, fn);
+ };
+ },
+ detach: function(type, fn) {
+ if (element.removeEventListener) {
+ element.removeEventListener(type, fn, false);
+ } else if (element.attachEvent) {
+ element.detachEvent("on" + type, fn);
+ }
+ return this;
+ },
+ contains: function(descendant) {
+ if (!descendant) {
+ return false;
+ }
+ if (element === descendant) {
+ return true;
+ }
+ if (element.contains) {
+ return element.contains(descendant);
+ } else {
+ return !!(descendant.compareDocumentPosition(element) & 8);
+ }
+ },
+ insertBefore: function(elementB) {
+ elementB.parentNode.insertBefore(element, elementB);
+ return this;
+ },
+ remove: function() {
+ element.parentNode.removeChild(element);
+ return this;
+ },
+ css: function(styles) {
+ if (element.style == null) {
+ throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
+ }
+ if (styles.opacity != null) {
+ if (typeof element.style.opacity !== "string" && typeof element.filters !== "undefined") {
+ styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
+ }
+ }
+ qq.extend(element.style, styles);
+ return this;
+ },
+ hasClass: function(name, considerParent) {
+ var re = new RegExp("(^| )" + name + "( |$)");
+ return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));
+ },
+ addClass: function(name) {
+ if (!qq(element).hasClass(name)) {
+ element.className += " " + name;
+ }
+ return this;
+ },
+ removeClass: function(name) {
+ var re = new RegExp("(^| )" + name + "( |$)");
+ element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
+ return this;
+ },
+ getByClass: function(className, first) {
+ var candidates, result = [];
+ if (first && element.querySelector) {
+ return element.querySelector("." + className);
+ } else if (element.querySelectorAll) {
+ return element.querySelectorAll("." + className);
+ }
+ candidates = element.getElementsByTagName("*");
+ qq.each(candidates, function(idx, val) {
+ if (qq(val).hasClass(className)) {
+ result.push(val);
+ }
+ });
+ return first ? result[0] : result;
+ },
+ getFirstByClass: function(className) {
+ return qq(element).getByClass(className, true);
+ },
+ children: function() {
+ var children = [], child = element.firstChild;
+ while (child) {
+ if (child.nodeType === 1) {
+ children.push(child);
+ }
+ child = child.nextSibling;
+ }
+ return children;
+ },
+ setText: function(text) {
+ element.innerText = text;
+ element.textContent = text;
+ return this;
+ },
+ clearText: function() {
+ return qq(element).setText("");
+ },
+ hasAttribute: function(attrName) {
+ var attrVal;
+ if (element.hasAttribute) {
+ if (!element.hasAttribute(attrName)) {
+ return false;
+ }
+ return /^false$/i.exec(element.getAttribute(attrName)) == null;
+ } else {
+ attrVal = element[attrName];
+ if (attrVal === undefined) {
+ return false;
+ }
+ return /^false$/i.exec(attrVal) == null;
+ }
+ }
+ };
+ };
+ (function() {
+ "use strict";
+ qq.canvasToBlob = function(canvas, mime, quality) {
+ return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
+ };
+ qq.dataUriToBlob = function(dataUri) {
+ var arrayBuffer, byteString, createBlob = function(data, mime) {
+ var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
+ if (blobBuilder) {
+ blobBuilder.append(data);
+ return blobBuilder.getBlob(mime);
+ } else {
+ return new Blob([ data ], {
+ type: mime
+ });
+ }
+ }, intArray, mimeString;
+ if (dataUri.split(",")[0].indexOf("base64") >= 0) {
+ byteString = atob(dataUri.split(",")[1]);
+ } else {
+ byteString = decodeURI(dataUri.split(",")[1]);
+ }
+ mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
+ arrayBuffer = new ArrayBuffer(byteString.length);
+ intArray = new Uint8Array(arrayBuffer);
+ qq.each(byteString, function(idx, character) {
+ intArray[idx] = character.charCodeAt(0);
+ });
+ return createBlob(arrayBuffer, mimeString);
+ };
+ qq.log = function(message, level) {
+ if (window.console) {
+ if (!level || level === "info") {
+ window.console.log(message);
+ } else {
+ if (window.console[level]) {
+ window.console[level](message);
+ } else {
+ window.console.log("<" + level + "> " + message);
+ }
+ }
+ }
+ };
+ qq.isObject = function(variable) {
+ return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
+ };
+ qq.isFunction = function(variable) {
+ return typeof variable === "function";
+ };
+ qq.isArray = function(value) {
+ return Object.prototype.toString.call(value) === "[object Array]" || value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer;
+ };
+ qq.isItemList = function(maybeItemList) {
+ return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
+ };
+ qq.isNodeList = function(maybeNodeList) {
+ return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || maybeNodeList.item && maybeNodeList.namedItem;
+ };
+ qq.isString = function(maybeString) {
+ return Object.prototype.toString.call(maybeString) === "[object String]";
+ };
+ qq.trimStr = function(string) {
+ if (String.prototype.trim) {
+ return string.trim();
+ }
+ return string.replace(/^\s+|\s+$/g, "");
+ };
+ qq.format = function(str) {
+ var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}");
+ qq.each(args, function(idx, val) {
+ var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2);
+ newStr = strBefore + val + strAfter;
+ nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
+ if (nextIdxToReplace < 0) {
+ return false;
+ }
+ });
+ return newStr;
+ };
+ qq.isFile = function(maybeFile) {
+ return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
+ };
+ qq.isFileList = function(maybeFileList) {
+ return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
+ };
+ qq.isFileOrInput = function(maybeFileOrInput) {
+ return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
+ };
+ qq.isInput = function(maybeInput, notFile) {
+ var evaluateType = function(type) {
+ var normalizedType = type.toLowerCase();
+ if (notFile) {
+ return normalizedType !== "file";
+ }
+ return normalizedType === "file";
+ };
+ if (window.HTMLInputElement) {
+ if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
+ if (maybeInput.type && evaluateType(maybeInput.type)) {
+ return true;
+ }
+ }
+ }
+ if (maybeInput.tagName) {
+ if (maybeInput.tagName.toLowerCase() === "input") {
+ if (maybeInput.type && evaluateType(maybeInput.type)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+ qq.isBlob = function(maybeBlob) {
+ if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
+ return true;
+ }
+ };
+ qq.isXhrUploadSupported = function() {
+ var input = document.createElement("input");
+ input.type = "file";
+ return input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof qq.createXhrInstance().upload !== "undefined";
+ };
+ qq.createXhrInstance = function() {
+ if (window.XMLHttpRequest) {
+ return new XMLHttpRequest();
+ }
+ try {
+ return new ActiveXObject("MSXML2.XMLHTTP.3.0");
+ } catch (error) {
+ qq.log("Neither XHR or ActiveX are supported!", "error");
+ return null;
+ }
+ };
+ qq.isFolderDropSupported = function(dataTransfer) {
+ return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry;
+ };
+ qq.isFileChunkingSupported = function() {
+ return !qq.androidStock() && qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
+ };
+ qq.sliceBlob = function(fileOrBlob, start, end) {
+ var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
+ return slicer.call(fileOrBlob, start, end);
+ };
+ qq.arrayBufferToHex = function(buffer) {
+ var bytesAsHex = "", bytes = new Uint8Array(buffer);
+ qq.each(bytes, function(idx, byt) {
+ var byteAsHexStr = byt.toString(16);
+ if (byteAsHexStr.length < 2) {
+ byteAsHexStr = "0" + byteAsHexStr;
+ }
+ bytesAsHex += byteAsHexStr;
+ });
+ return bytesAsHex;
+ };
+ qq.readBlobToHex = function(blob, startOffset, length) {
+ var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise();
+ fileReader.onload = function() {
+ promise.success(qq.arrayBufferToHex(fileReader.result));
+ };
+ fileReader.onerror = promise.failure;
+ fileReader.readAsArrayBuffer(initialBlob);
+ return promise;
+ };
+ qq.extend = function(first, second, extendNested) {
+ qq.each(second, function(prop, val) {
+ if (extendNested && qq.isObject(val)) {
+ if (first[prop] === undefined) {
+ first[prop] = {};
+ }
+ qq.extend(first[prop], val, true);
+ } else {
+ first[prop] = val;
+ }
+ });
+ return first;
+ };
+ qq.override = function(target, sourceFn) {
+ var super_ = {}, source = sourceFn(super_);
+ qq.each(source, function(srcPropName, srcPropVal) {
+ if (target[srcPropName] !== undefined) {
+ super_[srcPropName] = target[srcPropName];
+ }
+ target[srcPropName] = srcPropVal;
+ });
+ return target;
+ };
+ qq.indexOf = function(arr, elt, from) {
+ if (arr.indexOf) {
+ return arr.indexOf(elt, from);
+ }
+ from = from || 0;
+ var len = arr.length;
+ if (from < 0) {
+ from += len;
+ }
+ for (;from < len; from += 1) {
+ if (arr.hasOwnProperty(from) && arr[from] === elt) {
+ return from;
+ }
+ }
+ return -1;
+ };
+ qq.getUniqueId = function() {
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
+ var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
+ return v.toString(16);
+ });
+ };
+ qq.ie = function() {
+ return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1;
+ };
+ qq.ie7 = function() {
+ return navigator.userAgent.indexOf("MSIE 7") !== -1;
+ };
+ qq.ie8 = function() {
+ return navigator.userAgent.indexOf("MSIE 8") !== -1;
+ };
+ qq.ie10 = function() {
+ return navigator.userAgent.indexOf("MSIE 10") !== -1;
+ };
+ qq.ie11 = function() {
+ return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
+ };
+ qq.edge = function() {
+ return navigator.userAgent.indexOf("Edge") >= 0;
+ };
+ qq.safari = function() {
+ return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
+ };
+ qq.chrome = function() {
+ return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
+ };
+ qq.opera = function() {
+ return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
+ };
+ qq.firefox = function() {
+ return !qq.edge() && !qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "";
+ };
+ qq.windows = function() {
+ return navigator.platform === "Win32";
+ };
+ qq.android = function() {
+ return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
+ };
+ qq.androidStock = function() {
+ return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
+ };
+ qq.ios6 = function() {
+ return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
+ };
+ qq.ios7 = function() {
+ return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
+ };
+ qq.ios8 = function() {
+ return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
+ };
+ qq.ios800 = function() {
+ return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
+ };
+ qq.ios = function() {
+ return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1;
+ };
+ qq.iosChrome = function() {
+ return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
+ };
+ qq.iosSafari = function() {
+ return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
+ };
+ qq.iosSafariWebView = function() {
+ return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
+ };
+ qq.preventDefault = function(e) {
+ if (e.preventDefault) {
+ e.preventDefault();
+ } else {
+ e.returnValue = false;
+ }
+ };
+ qq.toElement = function() {
+ var div = document.createElement("div");
+ return function(html) {
+ div.innerHTML = html;
+ var element = div.firstChild;
+ div.removeChild(element);
+ return element;
+ };
+ }();
+ qq.each = function(iterableItem, callback) {
+ var keyOrIndex, retVal;
+ if (iterableItem) {
+ if (window.Storage && iterableItem.constructor === window.Storage) {
+ for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
+ retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
+ if (retVal === false) {
+ break;
+ }
+ }
+ } else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
+ for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
+ retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
+ if (retVal === false) {
+ break;
+ }
+ }
+ } else if (qq.isString(iterableItem)) {
+ for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
+ retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
+ if (retVal === false) {
+ break;
+ }
+ }
+ } else {
+ for (keyOrIndex in iterableItem) {
+ if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
+ retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
+ if (retVal === false) {
+ break;
+ }
+ }
+ }
+ }
+ }
+ };
+ qq.bind = function(oldFunc, context) {
+ if (qq.isFunction(oldFunc)) {
+ var args = Array.prototype.slice.call(arguments, 2);
+ return function() {
+ var newArgs = qq.extend([], args);
+ if (arguments.length) {
+ newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
+ }
+ return oldFunc.apply(context, newArgs);
+ };
+ }
+ throw new Error("first parameter must be a function!");
+ };
+ qq.obj2url = function(obj, temp, prefixDone) {
+ var uristrings = [], prefix = "&", add = function(nextObj, i) {
+ var nextTemp = temp ? /\[\]$/.test(temp) ? temp : temp + "[" + i + "]" : i;
+ if (nextTemp !== "undefined" && i !== "undefined") {
+ uristrings.push(typeof nextObj === "object" ? qq.obj2url(nextObj, nextTemp, true) : Object.prototype.toString.call(nextObj) === "[object Function]" ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj));
+ }
+ };
+ if (!prefixDone && temp) {
+ prefix = /\?/.test(temp) ? /\?$/.test(temp) ? "" : "&" : "?";
+ uristrings.push(temp);
+ uristrings.push(qq.obj2url(obj));
+ } else if (Object.prototype.toString.call(obj) === "[object Array]" && typeof obj !== "undefined") {
+ qq.each(obj, function(idx, val) {
+ add(val, idx);
+ });
+ } else if (typeof obj !== "undefined" && obj !== null && typeof obj === "object") {
+ qq.each(obj, function(prop, val) {
+ add(val, prop);
+ });
+ } else {
+ uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
+ }
+ if (temp) {
+ return uristrings.join(prefix);
+ } else {
+ return uristrings.join(prefix).replace(/^&/, "").replace(/%20/g, "+");
+ }
+ };
+ qq.obj2FormData = function(obj, formData, arrayKeyName) {
+ if (!formData) {
+ formData = new FormData();
+ }
+ qq.each(obj, function(key, val) {
+ key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
+ if (qq.isObject(val)) {
+ qq.obj2FormData(val, formData, key);
+ } else if (qq.isFunction(val)) {
+ formData.append(key, val());
+ } else {
+ formData.append(key, val);
+ }
+ });
+ return formData;
+ };
+ qq.obj2Inputs = function(obj, form) {
+ var input;
+ if (!form) {
+ form = document.createElement("form");
+ }
+ qq.obj2FormData(obj, {
+ append: function(key, val) {
+ input = document.createElement("input");
+ input.setAttribute("name", key);
+ input.setAttribute("value", val);
+ form.appendChild(input);
+ }
+ });
+ return form;
+ };
+ qq.parseJson = function(json) {
+ if (window.JSON && qq.isFunction(JSON.parse)) {
+ return JSON.parse(json);
+ } else {
+ return eval("(" + json + ")");
+ }
+ };
+ qq.getExtension = function(filename) {
+ var extIdx = filename.lastIndexOf(".") + 1;
+ if (extIdx > 0) {
+ return filename.substr(extIdx, filename.length - extIdx);
+ }
+ };
+ qq.getFilename = function(blobOrFileInput) {
+ if (qq.isInput(blobOrFileInput)) {
+ return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
+ } else if (qq.isFile(blobOrFileInput)) {
+ if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
+ return blobOrFileInput.fileName;
+ }
+ }
+ return blobOrFileInput.name;
+ };
+ qq.DisposeSupport = function() {
+ var disposers = [];
+ return {
+ dispose: function() {
+ var disposer;
+ do {
+ disposer = disposers.shift();
+ if (disposer) {
+ disposer();
+ }
+ } while (disposer);
+ },
+ attach: function() {
+ var args = arguments;
+ this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
+ },
+ addDisposer: function(disposeFunction) {
+ disposers.push(disposeFunction);
+ }
+ };
+ };
+ })();
+ (function() {
+ "use strict";
+ if (typeof define === "function" && define.amd) {
+ define(function() {
+ return qq;
+ });
+ } else if (typeof module !== "undefined" && module.exports) {
+ module.exports = qq;
+ } else {
+ global.qq = qq;
+ }
+ })();
+ (function() {
+ "use strict";
+ qq.Error = function(message) {
+ this.message = "[Fine Uploader " + qq.version + "] " + message;
+ };
+ qq.Error.prototype = new Error();
+ })();
+ qq.version = "5.15.4";
+ qq.supportedFeatures = function() {
+ "use strict";
+ var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress;
+ function testSupportsFileInputElement() {
+ var supported = true, tempInput;
+ try {
+ tempInput = document.createElement("input");
+ tempInput.type = "file";
+ qq(tempInput).hide();
+ if (tempInput.disabled) {
+ supported = false;
+ }
+ } catch (ex) {
+ supported = false;
+ }
+ return supported;
+ }
+ function isChrome21OrHigher() {
+ return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
+ }
+ function isChrome14OrHigher() {
+ return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
+ }
+ function isCrossOriginXhrSupported() {
+ if (window.XMLHttpRequest) {
+ var xhr = qq.createXhrInstance();
+ return xhr.withCredentials !== undefined;
+ }
+ return false;
+ }
+ function isXdrSupported() {
+ return window.XDomainRequest !== undefined;
+ }
+ function isCrossOriginAjaxSupported() {
+ if (isCrossOriginXhrSupported()) {
+ return true;
+ }
+ return isXdrSupported();
+ }
+ function isFolderSelectionSupported() {
+ return document.createElement("input").webkitdirectory !== undefined;
+ }
+ function isLocalStorageSupported() {
+ try {
+ return !!window.localStorage && qq.isFunction(window.localStorage.setItem);
+ } catch (error) {
+ return false;
+ }
+ }
+ function isDragAndDropSupported() {
+ var span = document.createElement("span");
+ return ("draggable" in span || "ondragstart" in span && "ondrop" in span) && !qq.android() && !qq.ios();
+ }
+ supportsUploading = testSupportsFileInputElement();
+ supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
+ supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
+ supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();
+ supportsFolderDrop = supportsFileDrop && isChrome21OrHigher();
+ supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
+ supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
+ supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
+ supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
+ supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
+ supportsDeleteFileXdr = isXdrSupported();
+ supportsDeleteFileCors = isCrossOriginAjaxSupported();
+ supportsFolderSelection = isFolderSelectionSupported();
+ supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
+ supportsUploadProgress = function() {
+ if (supportsAjaxFileUploading) {
+ return !qq.androidStock() && !qq.iosChrome();
+ }
+ return false;
+ }();
+ return {
+ ajaxUploading: supportsAjaxFileUploading,
+ blobUploading: supportsUploadingBlobs,
+ canDetermineSize: supportsAjaxFileUploading,
+ chunking: supportsChunking,
+ deleteFileCors: supportsDeleteFileCors,
+ deleteFileCorsXdr: supportsDeleteFileXdr,
+ deleteFileCorsXhr: supportsDeleteFileCorsXhr,
+ dialogElement: !!window.HTMLDialogElement,
+ fileDrop: supportsFileDrop,
+ folderDrop: supportsFolderDrop,
+ folderSelection: supportsFolderSelection,
+ imagePreviews: supportsImagePreviews,
+ imageValidation: supportsImagePreviews,
+ itemSizeValidation: supportsAjaxFileUploading,
+ pause: supportsChunking,
+ progressBar: supportsUploadProgress,
+ resume: supportsResume,
+ scaling: supportsImagePreviews && supportsUploadingBlobs,
+ tiffPreviews: qq.safari(),
+ unlimitedScaledImageSize: !qq.ios(),
+ uploading: supportsUploading,
+ uploadCors: supportsUploadCors,
+ uploadCustomHeaders: supportsAjaxFileUploading,
+ uploadNonMultipart: supportsAjaxFileUploading,
+ uploadViaPaste: supportsUploadViaPaste
+ };
+ }();
+ qq.isGenericPromise = function(maybePromise) {
+ "use strict";
+ return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
+ };
+ qq.Promise = function() {
+ "use strict";
+ var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0;
+ qq.extend(this, {
+ then: function(onSuccess, onFailure) {
+ if (state === 0) {
+ if (onSuccess) {
+ successCallbacks.push(onSuccess);
+ }
+ if (onFailure) {
+ failureCallbacks.push(onFailure);
+ }
+ } else if (state === -1) {
+ onFailure && onFailure.apply(null, failureArgs);
+ } else if (onSuccess) {
+ onSuccess.apply(null, successArgs);
+ }
+ return this;
+ },
+ done: function(callback) {
+ if (state === 0) {
+ doneCallbacks.push(callback);
+ } else {
+ callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
+ }
+ return this;
+ },
+ success: function() {
+ state = 1;
+ successArgs = arguments;
+ if (successCallbacks.length) {
+ qq.each(successCallbacks, function(idx, callback) {
+ callback.apply(null, successArgs);
+ });
+ }
+ if (doneCallbacks.length) {
+ qq.each(doneCallbacks, function(idx, callback) {
+ callback.apply(null, successArgs);
+ });
+ }
+ return this;
+ },
+ failure: function() {
+ state = -1;
+ failureArgs = arguments;
+ if (failureCallbacks.length) {
+ qq.each(failureCallbacks, function(idx, callback) {
+ callback.apply(null, failureArgs);
+ });
+ }
+ if (doneCallbacks.length) {
+ qq.each(doneCallbacks, function(idx, callback) {
+ callback.apply(null, failureArgs);
+ });
+ }
+ return this;
+ }
+ });
+ };
+ qq.BlobProxy = function(referenceBlob, onCreate) {
+ "use strict";
+ qq.extend(this, {
+ referenceBlob: referenceBlob,
+ create: function() {
+ return onCreate(referenceBlob);
+ }
+ });
+ };
+ qq.UploadButton = function(o) {
+ "use strict";
+ var self = this, disposeSupport = new qq.DisposeSupport(), options = {
+ acceptFiles: null,
+ element: null,
+ focusClass: "qq-upload-button-focus",
+ folders: false,
+ hoverClass: "qq-upload-button-hover",
+ ios8BrowserCrashWorkaround: false,
+ multiple: false,
+ name: "qqfile",
+ onChange: function(input) {},
+ title: null
+ }, input, buttonId;
+ qq.extend(options, o);
+ buttonId = qq.getUniqueId();
+ function createInput() {
+ var input = document.createElement("input");
+ input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
+ input.setAttribute("title", options.title);
+ self.setMultiple(options.multiple, input);
+ if (options.folders && qq.supportedFeatures.folderSelection) {
+ input.setAttribute("webkitdirectory", "");
+ }
+ if (options.acceptFiles) {
+ input.setAttribute("accept", options.acceptFiles);
+ }
+ input.setAttribute("type", "file");
+ input.setAttribute("name", options.name);
+ qq(input).css({
+ position: "absolute",
+ right: 0,
+ top: 0,
+ fontFamily: "Arial",
+ fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
+ margin: 0,
+ padding: 0,
+ cursor: "pointer",
+ opacity: 0
+ });
+ !qq.ie7() && qq(input).css({
+ height: "100%"
+ });
+ options.element.appendChild(input);
+ disposeSupport.attach(input, "change", function() {
+ options.onChange(input);
+ });
+ disposeSupport.attach(input, "mouseover", function() {
+ qq(options.element).addClass(options.hoverClass);
+ });
+ disposeSupport.attach(input, "mouseout", function() {
+ qq(options.element).removeClass(options.hoverClass);
+ });
+ disposeSupport.attach(input, "focus", function() {
+ qq(options.element).addClass(options.focusClass);
+ });
+ disposeSupport.attach(input, "blur", function() {
+ qq(options.element).removeClass(options.focusClass);
+ });
+ return input;
+ }
+ qq(options.element).css({
+ position: "relative",
+ overflow: "hidden",
+ direction: "ltr"
+ });
+ qq.extend(this, {
+ getInput: function() {
+ return input;
+ },
+ getButtonId: function() {
+ return buttonId;
+ },
+ setMultiple: function(isMultiple, optInput) {
+ var input = optInput || this.getInput();
+ if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
+ input.setAttribute("multiple", "");
+ } else {
+ if (isMultiple) {
+ input.setAttribute("multiple", "");
+ } else {
+ input.removeAttribute("multiple");
+ }
+ }
+ },
+ setAcceptFiles: function(acceptFiles) {
+ if (acceptFiles !== options.acceptFiles) {
+ input.setAttribute("accept", acceptFiles);
+ }
+ },
+ reset: function() {
+ if (input.parentNode) {
+ qq(input).remove();
+ }
+ qq(options.element).removeClass(options.focusClass);
+ input = null;
+ input = createInput();
+ }
+ });
+ input = createInput();
+ };
+ qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
+ qq.UploadData = function(uploaderProxy) {
+ "use strict";
+ var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {};
+ function getDataByIds(idOrIds) {
+ if (qq.isArray(idOrIds)) {
+ var entries = [];
+ qq.each(idOrIds, function(idx, id) {
+ entries.push(data[id]);
+ });
+ return entries;
+ }
+ return data[idOrIds];
+ }
+ function getDataByUuids(uuids) {
+ if (qq.isArray(uuids)) {
+ var entries = [];
+ qq.each(uuids, function(idx, uuid) {
+ entries.push(data[byUuid[uuid]]);
+ });
+ return entries;
+ }
+ return data[byUuid[uuids]];
+ }
+ function getDataByStatus(status) {
+ var statusResults = [], statuses = [].concat(status);
+ qq.each(statuses, function(index, statusEnum) {
+ var statusResultIndexes = byStatus[statusEnum];
+ if (statusResultIndexes !== undefined) {
+ qq.each(statusResultIndexes, function(i, dataIndex) {
+ statusResults.push(data[dataIndex]);
+ });
+ }
+ });
+ return statusResults;
+ }
+ qq.extend(this, {
+ addFile: function(spec) {
+ var status = spec.status || qq.status.SUBMITTING, id = data.push({
+ name: spec.name,
+ originalName: spec.name,
+ uuid: spec.uuid,
+ size: spec.size == null ? -1 : spec.size,
+ status: status
+ }) - 1;
+ if (spec.batchId) {
+ data[id].batchId = spec.batchId;
+ if (byBatchId[spec.batchId] === undefined) {
+ byBatchId[spec.batchId] = [];
+ }
+ byBatchId[spec.batchId].push(id);
+ }
+ if (spec.proxyGroupId) {
+ data[id].proxyGroupId = spec.proxyGroupId;
+ if (byProxyGroupId[spec.proxyGroupId] === undefined) {
+ byProxyGroupId[spec.proxyGroupId] = [];
+ }
+ byProxyGroupId[spec.proxyGroupId].push(id);
+ }
+ data[id].id = id;
+ byUuid[spec.uuid] = id;
+ if (byStatus[status] === undefined) {
+ byStatus[status] = [];
+ }
+ byStatus[status].push(id);
+ spec.onBeforeStatusChange && spec.onBeforeStatusChange(id);
+ uploaderProxy.onStatusChange(id, null, status);
+ return id;
+ },
+ retrieve: function(optionalFilter) {
+ if (qq.isObject(optionalFilter) && data.length) {
+ if (optionalFilter.id !== undefined) {
+ return getDataByIds(optionalFilter.id);
+ } else if (optionalFilter.uuid !== undefined) {
+ return getDataByUuids(optionalFilter.uuid);
+ } else if (optionalFilter.status) {
+ return getDataByStatus(optionalFilter.status);
+ }
+ } else {
+ return qq.extend([], data, true);
+ }
+ },
+ reset: function() {
+ data = [];
+ byUuid = {};
+ byStatus = {};
+ byBatchId = {};
+ },
+ setStatus: function(id, newStatus) {
+ var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
+ byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
+ data[id].status = newStatus;
+ if (byStatus[newStatus] === undefined) {
+ byStatus[newStatus] = [];
+ }
+ byStatus[newStatus].push(id);
+ uploaderProxy.onStatusChange(id, oldStatus, newStatus);
+ },
+ uuidChanged: function(id, newUuid) {
+ var oldUuid = data[id].uuid;
+ data[id].uuid = newUuid;
+ byUuid[newUuid] = id;
+ delete byUuid[oldUuid];
+ },
+ updateName: function(id, newName) {
+ data[id].name = newName;
+ },
+ updateSize: function(id, newSize) {
+ data[id].size = newSize;
+ },
+ setParentId: function(targetId, parentId) {
+ data[targetId].parentId = parentId;
+ },
+ getIdsInProxyGroup: function(id) {
+ var proxyGroupId = data[id].proxyGroupId;
+ if (proxyGroupId) {
+ return byProxyGroupId[proxyGroupId];
+ }
+ return [];
+ },
+ getIdsInBatch: function(id) {
+ var batchId = data[id].batchId;
+ return byBatchId[batchId];
+ }
+ });
+ };
+ qq.status = {
+ SUBMITTING: "submitting",
+ SUBMITTED: "submitted",
+ REJECTED: "rejected",
+ QUEUED: "queued",
+ CANCELED: "canceled",
+ PAUSED: "paused",
+ UPLOADING: "uploading",
+ UPLOAD_RETRYING: "retrying upload",
+ UPLOAD_SUCCESSFUL: "upload successful",
+ UPLOAD_FAILED: "upload failed",
+ DELETE_FAILED: "delete failed",
+ DELETING: "deleting",
+ DELETED: "deleted"
+ };
+ (function() {
+ "use strict";
+ qq.basePublicApi = {
+ addBlobs: function(blobDataOrArray, params, endpoint) {
+ this.addFiles(blobDataOrArray, params, endpoint);
+ },
+ addInitialFiles: function(cannedFileList) {
+ var self = this;
+ qq.each(cannedFileList, function(index, cannedFile) {
+ self._addCannedFile(cannedFile);
+ });
+ },
+ addFiles: function(data, params, endpoint) {
+ this._maybeHandleIos8SafariWorkaround();
+ var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) {
+ this._handleNewFile({
+ blob: blob,
+ name: this._options.blobs.defaultName
+ }, batchId, verifiedFiles);
+ }, this), processBlobData = qq.bind(function(blobData) {
+ this._handleNewFile(blobData, batchId, verifiedFiles);
+ }, this), processCanvas = qq.bind(function(canvas) {
+ var blob = qq.canvasToBlob(canvas);
+ this._handleNewFile({
+ blob: blob,
+ name: this._options.blobs.defaultName + ".png"
+ }, batchId, verifiedFiles);
+ }, this), processCanvasData = qq.bind(function(canvasData) {
+ var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
+ this._handleNewFile({
+ blob: blob,
+ name: canvasData.name
+ }, batchId, verifiedFiles);
+ }, this), processFileOrInput = qq.bind(function(fileOrInput) {
+ if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
+ var files = Array.prototype.slice.call(fileOrInput.files), self = this;
+ qq.each(files, function(idx, file) {
+ self._handleNewFile(file, batchId, verifiedFiles);
+ });
+ } else {
+ this._handleNewFile(fileOrInput, batchId, verifiedFiles);
+ }
+ }, this), normalizeData = function() {
+ if (qq.isFileList(data)) {
+ data = Array.prototype.slice.call(data);
+ }
+ data = [].concat(data);
+ }, self = this, verifiedFiles = [];
+ this._currentBatchId = batchId;
+ if (data) {
+ normalizeData();
+ qq.each(data, function(idx, fileContainer) {
+ if (qq.isFileOrInput(fileContainer)) {
+ processFileOrInput(fileContainer);
+ } else if (qq.isBlob(fileContainer)) {
+ processBlob(fileContainer);
+ } else if (qq.isObject(fileContainer)) {
+ if (fileContainer.blob && fileContainer.name) {
+ processBlobData(fileContainer);
+ } else if (fileContainer.canvas && fileContainer.name) {
+ processCanvasData(fileContainer);
+ }
+ } else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
+ processCanvas(fileContainer);
+ } else {
+ self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
+ }
+ });
+ this.log("Received " + verifiedFiles.length + " files.");
+ this._prepareItemsForUpload(verifiedFiles, params, endpoint);
+ }
+ },
+ cancel: function(id) {
+ this._handler.cancel(id);
+ },
+ cancelAll: function() {
+ var storedIdsCopy = [], self = this;
+ qq.extend(storedIdsCopy, this._storedIds);
+ qq.each(storedIdsCopy, function(idx, storedFileId) {
+ self.cancel(storedFileId);
+ });
+ this._handler.cancelAll();
+ },
+ clearStoredFiles: function() {
+ this._storedIds = [];
+ },
+ continueUpload: function(id) {
+ var uploadData = this._uploadData.retrieve({
+ id: id
+ });
+ if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
+ return false;
+ }
+ if (uploadData.status === qq.status.PAUSED) {
+ this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
+ this._uploadFile(id);
+ return true;
+ } else {
+ this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
+ }
+ return false;
+ },
+ deleteFile: function(id) {
+ return this._onSubmitDelete(id);
+ },
+ doesExist: function(fileOrBlobId) {
+ return this._handler.isValid(fileOrBlobId);
+ },
+ drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
+ var promiseToReturn = new qq.Promise(), fileOrUrl, options;
+ if (this._imageGenerator) {
+ fileOrUrl = this._thumbnailUrls[fileId];
+ options = {
+ customResizeFunction: customResizeFunction,
+ maxSize: maxSize > 0 ? maxSize : null,
+ scale: maxSize > 0
+ };
+ if (!fromServer && qq.supportedFeatures.imagePreviews) {
+ fileOrUrl = this.getFile(fileId);
+ }
+ if (fileOrUrl == null) {
+ promiseToReturn.failure({
+ container: imgOrCanvas,
+ error: "File or URL not found."
+ });
+ } else {
+ this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(function success(modifiedContainer) {
+ promiseToReturn.success(modifiedContainer);
+ }, function failure(container, reason) {
+ promiseToReturn.failure({
+ container: container,
+ error: reason || "Problem generating thumbnail"
+ });
+ });
+ }
+ } else {
+ promiseToReturn.failure({
+ container: imgOrCanvas,
+ error: "Missing image generator module"
+ });
+ }
+ return promiseToReturn;
+ },
+ getButton: function(fileId) {
+ return this._getButton(this._buttonIdsForFileIds[fileId]);
+ },
+ getEndpoint: function(fileId) {
+ return this._endpointStore.get(fileId);
+ },
+ getFile: function(fileOrBlobId) {
+ return this._handler.getFile(fileOrBlobId) || null;
+ },
+ getInProgress: function() {
+ return this._uploadData.retrieve({
+ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ]
+ }).length;
+ },
+ getName: function(id) {
+ return this._uploadData.retrieve({
+ id: id
+ }).name;
+ },
+ getParentId: function(id) {
+ var uploadDataEntry = this.getUploads({
+ id: id
+ }), parentId = null;
+ if (uploadDataEntry) {
+ if (uploadDataEntry.parentId !== undefined) {
+ parentId = uploadDataEntry.parentId;
+ }
+ }
+ return parentId;
+ },
+ getResumableFilesData: function() {
+ return this._handler.getResumableFilesData();
+ },
+ getSize: function(id) {
+ return this._uploadData.retrieve({
+ id: id
+ }).size;
+ },
+ getNetUploads: function() {
+ return this._netUploaded;
+ },
+ getRemainingAllowedItems: function() {
+ var allowedItems = this._currentItemLimit;
+ if (allowedItems > 0) {
+ return allowedItems - this._netUploadedOrQueued;
+ }
+ return null;
+ },
+ getUploads: function(optionalFilter) {
+ return this._uploadData.retrieve(optionalFilter);
+ },
+ getUuid: function(id) {
+ return this._uploadData.retrieve({
+ id: id
+ }).uuid;
+ },
+ log: function(str, level) {
+ if (this._options.debug && (!level || level === "info")) {
+ qq.log("[Fine Uploader " + qq.version + "] " + str);
+ } else if (level && level !== "info") {
+ qq.log("[Fine Uploader " + qq.version + "] " + str, level);
+ }
+ },
+ pauseUpload: function(id) {
+ var uploadData = this._uploadData.retrieve({
+ id: id
+ });
+ if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
+ return false;
+ }
+ if (qq.indexOf([ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING ], uploadData.status) >= 0) {
+ if (this._handler.pause(id)) {
+ this._uploadData.setStatus(id, qq.status.PAUSED);
+ return true;
+ } else {
+ this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
+ }
+ } else {
+ this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
+ }
+ return false;
+ },
+ removeFileRef: function(id) {
+ this._handler.expunge(id);
+ },
+ reset: function() {
+ this.log("Resetting uploader...");
+ this._handler.reset();
+ this._storedIds = [];
+ this._autoRetries = [];
+ this._retryTimeouts = [];
+ this._preventRetries = [];
+ this._thumbnailUrls = [];
+ qq.each(this._buttons, function(idx, button) {
+ button.reset();
+ });
+ this._paramsStore.reset();
+ this._endpointStore.reset();
+ this._netUploadedOrQueued = 0;
+ this._netUploaded = 0;
+ this._uploadData.reset();
+ this._buttonIdsForFileIds = [];
+ this._pasteHandler && this._pasteHandler.reset();
+ this._options.session.refreshOnReset && this._refreshSessionData();
+ this._succeededSinceLastAllComplete = [];
+ this._failedSinceLastAllComplete = [];
+ this._totalProgress && this._totalProgress.reset();
+ },
+ retry: function(id) {
+ return this._manualRetry(id);
+ },
+ scaleImage: function(id, specs) {
+ var self = this;
+ return qq.Scaler.prototype.scaleImage(id, specs, {
+ log: qq.bind(self.log, self),
+ getFile: qq.bind(self.getFile, self),
+ uploadData: self._uploadData
+ });
+ },
+ setCustomHeaders: function(headers, id) {
+ this._customHeadersStore.set(headers, id);
+ },
+ setDeleteFileCustomHeaders: function(headers, id) {
+ this._deleteFileCustomHeadersStore.set(headers, id);
+ },
+ setDeleteFileEndpoint: function(endpoint, id) {
+ this._deleteFileEndpointStore.set(endpoint, id);
+ },
+ setDeleteFileParams: function(params, id) {
+ this._deleteFileParamsStore.set(params, id);
+ },
+ setEndpoint: function(endpoint, id) {
+ this._endpointStore.set(endpoint, id);
+ },
+ setForm: function(elementOrId) {
+ this._updateFormSupportAndParams(elementOrId);
+ },
+ setItemLimit: function(newItemLimit) {
+ this._currentItemLimit = newItemLimit;
+ },
+ setName: function(id, newName) {
+ this._uploadData.updateName(id, newName);
+ },
+ setParams: function(params, id) {
+ this._paramsStore.set(params, id);
+ },
+ setUuid: function(id, newUuid) {
+ return this._uploadData.uuidChanged(id, newUuid);
+ },
+ setStatus: function(id, newStatus) {
+ var fileRecord = this.getUploads({
+ id: id
+ });
+ if (!fileRecord) {
+ throw new qq.Error(id + " is not a valid file ID.");
+ }
+ switch (newStatus) {
+ case qq.status.DELETED:
+ this._onDeleteComplete(id, null, false);
+ break;
+
+ case qq.status.DELETE_FAILED:
+ this._onDeleteComplete(id, null, true);
+ break;
+
+ default:
+ var errorMessage = "Method setStatus called on '" + name + "' not implemented yet for " + newStatus;
+ this.log(errorMessage);
+ throw new qq.Error(errorMessage);
+ }
+ },
+ uploadStoredFiles: function() {
+ if (this._storedIds.length === 0) {
+ this._itemError("noFilesError");
+ } else {
+ this._uploadStoredFiles();
+ }
+ }
+ };
+ qq.basePrivateApi = {
+ _addCannedFile: function(sessionData) {
+ var self = this;
+ return this._uploadData.addFile({
+ uuid: sessionData.uuid,
+ name: sessionData.name,
+ size: sessionData.size,
+ status: qq.status.UPLOAD_SUCCESSFUL,
+ onBeforeStatusChange: function(id) {
+ sessionData.deleteFileEndpoint && self.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
+ sessionData.deleteFileParams && self.setDeleteFileParams(sessionData.deleteFileParams, id);
+ if (sessionData.thumbnailUrl) {
+ self._thumbnailUrls[id] = sessionData.thumbnailUrl;
+ }
+ self._netUploaded++;
+ self._netUploadedOrQueued++;
+ }
+ });
+ },
+ _annotateWithButtonId: function(file, associatedInput) {
+ if (qq.isFile(file)) {
+ file.qqButtonId = this._getButtonId(associatedInput);
+ }
+ },
+ _batchError: function(message) {
+ this._options.callbacks.onError(null, null, message, undefined);
+ },
+ _createDeleteHandler: function() {
+ var self = this;
+ return new qq.DeleteFileAjaxRequester({
+ method: this._options.deleteFile.method.toUpperCase(),
+ maxConnections: this._options.maxConnections,
+ uuidParamName: this._options.request.uuidName,
+ customHeaders: this._deleteFileCustomHeadersStore,
+ paramsStore: this._deleteFileParamsStore,
+ endpointStore: this._deleteFileEndpointStore,
+ cors: this._options.cors,
+ log: qq.bind(self.log, self),
+ onDelete: function(id) {
+ self._onDelete(id);
+ self._options.callbacks.onDelete(id);
+ },
+ onDeleteComplete: function(id, xhrOrXdr, isError) {
+ self._onDeleteComplete(id, xhrOrXdr, isError);
+ self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
+ }
+ });
+ },
+ _createPasteHandler: function() {
+ var self = this;
+ return new qq.PasteSupport({
+ targetElement: this._options.paste.targetElement,
+ callbacks: {
+ log: qq.bind(self.log, self),
+ pasteReceived: function(blob) {
+ self._handleCheckedCallback({
+ name: "onPasteReceived",
+ callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
+ onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
+ identifier: "pasted image"
+ });
+ }
+ }
+ });
+ },
+ _createStore: function(initialValue, _readOnlyValues_) {
+ var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) {
+ if (qq.isObject(orig)) {
+ return qq.extend({}, orig);
+ }
+ return orig;
+ }, getReadOnlyValues = function() {
+ if (qq.isFunction(readOnlyValues)) {
+ return readOnlyValues();
+ }
+ return readOnlyValues;
+ }, includeReadOnlyValues = function(id, existing) {
+ if (readOnlyValues && qq.isObject(existing)) {
+ qq.extend(existing, getReadOnlyValues());
+ }
+ if (perIdReadOnlyValues[id]) {
+ qq.extend(existing, perIdReadOnlyValues[id]);
+ }
+ };
+ return {
+ set: function(val, id) {
+ if (id == null) {
+ store = {};
+ catchall = copy(val);
+ } else {
+ store[id] = copy(val);
+ }
+ },
+ get: function(id) {
+ var values;
+ if (id != null && store[id]) {
+ values = store[id];
+ } else {
+ values = copy(catchall);
+ }
+ includeReadOnlyValues(id, values);
+ return copy(values);
+ },
+ addReadOnly: function(id, values) {
+ if (qq.isObject(store)) {
+ if (id === null) {
+ if (qq.isFunction(values)) {
+ readOnlyValues = values;
+ } else {
+ readOnlyValues = readOnlyValues || {};
+ qq.extend(readOnlyValues, values);
+ }
+ } else {
+ perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
+ qq.extend(perIdReadOnlyValues[id], values);
+ }
+ }
+ },
+ remove: function(fileId) {
+ return delete store[fileId];
+ },
+ reset: function() {
+ store = {};
+ perIdReadOnlyValues = {};
+ catchall = initialValue;
+ }
+ };
+ },
+ _createUploadDataTracker: function() {
+ var self = this;
+ return new qq.UploadData({
+ getName: function(id) {
+ return self.getName(id);
+ },
+ getUuid: function(id) {
+ return self.getUuid(id);
+ },
+ getSize: function(id) {
+ return self.getSize(id);
+ },
+ onStatusChange: function(id, oldStatus, newStatus) {
+ self._onUploadStatusChange(id, oldStatus, newStatus);
+ self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
+ self._maybeAllComplete(id, newStatus);
+ if (self._totalProgress) {
+ setTimeout(function() {
+ self._totalProgress.onStatusChange(id, oldStatus, newStatus);
+ }, 0);
+ }
+ }
+ });
+ },
+ _createUploadButton: function(spec) {
+ var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button;
+ function allowMultiple() {
+ if (qq.supportedFeatures.ajaxUploading) {
+ if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) {
+ return false;
+ }
+ if (spec.multiple === undefined) {
+ return self._options.multiple;
+ }
+ return spec.multiple;
+ }
+ return false;
+ }
+ button = new qq.UploadButton({
+ acceptFiles: acceptFiles,
+ element: spec.element,
+ focusClass: this._options.classes.buttonFocus,
+ folders: spec.folders,
+ hoverClass: this._options.classes.buttonHover,
+ ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,
+ multiple: allowMultiple(),
+ name: this._options.request.inputName,
+ onChange: function(input) {
+ self._onInputChange(input);
+ },
+ title: spec.title == null ? this._options.text.fileInputTitle : spec.title
+ });
+ this._disposeSupport.addDisposer(function() {
+ button.dispose();
+ });
+ self._buttons.push(button);
+ return button;
+ },
+ _createUploadHandler: function(additionalOptions, namespace) {
+ var self = this, lastOnProgress = {}, options = {
+ debug: this._options.debug,
+ maxConnections: this._options.maxConnections,
+ cors: this._options.cors,
+ paramsStore: this._paramsStore,
+ endpointStore: this._endpointStore,
+ chunking: this._options.chunking,
+ resume: this._options.resume,
+ blobs: this._options.blobs,
+ log: qq.bind(self.log, self),
+ preventRetryParam: this._options.retry.preventRetryResponseProperty,
+ onProgress: function(id, name, loaded, total) {
+ if (loaded < 0 || total < 0) {
+ return;
+ }
+ if (lastOnProgress[id]) {
+ if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
+ self._onProgress(id, name, loaded, total);
+ self._options.callbacks.onProgress(id, name, loaded, total);
+ }
+ } else {
+ self._onProgress(id, name, loaded, total);
+ self._options.callbacks.onProgress(id, name, loaded, total);
+ }
+ lastOnProgress[id] = {
+ loaded: loaded,
+ total: total
+ };
+ },
+ onComplete: function(id, name, result, xhr) {
+ delete lastOnProgress[id];
+ var status = self.getUploads({
+ id: id
+ }).status, retVal;
+ if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
+ return;
+ }
+ retVal = self._onComplete(id, name, result, xhr);
+ if (retVal instanceof qq.Promise) {
+ retVal.done(function() {
+ self._options.callbacks.onComplete(id, name, result, xhr);
+ });
+ } else {
+ self._options.callbacks.onComplete(id, name, result, xhr);
+ }
+ },
+ onCancel: function(id, name, cancelFinalizationEffort) {
+ var promise = new qq.Promise();
+ self._handleCheckedCallback({
+ name: "onCancel",
+ callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
+ onFailure: promise.failure,
+ onSuccess: function() {
+ cancelFinalizationEffort.then(function() {
+ self._onCancel(id, name);
+ });
+ promise.success();
+ },
+ identifier: id
+ });
+ return promise;
+ },
+ onUploadPrep: qq.bind(this._onUploadPrep, this),
+ onUpload: function(id, name) {
+ self._onUpload(id, name);
+ self._options.callbacks.onUpload(id, name);
+ },
+ onUploadChunk: function(id, name, chunkData) {
+ self._onUploadChunk(id, chunkData);
+ self._options.callbacks.onUploadChunk(id, name, chunkData);
+ },
+ onUploadChunkSuccess: function(id, chunkData, result, xhr) {
+ self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
+ },
+ onResume: function(id, name, chunkData) {
+ return self._options.callbacks.onResume(id, name, chunkData);
+ },
+ onAutoRetry: function(id, name, responseJSON, xhr) {
+ return self._onAutoRetry.apply(self, arguments);
+ },
+ onUuidChanged: function(id, newUuid) {
+ self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
+ self.setUuid(id, newUuid);
+ },
+ getName: qq.bind(self.getName, self),
+ getUuid: qq.bind(self.getUuid, self),
+ getSize: qq.bind(self.getSize, self),
+ setSize: qq.bind(self._setSize, self),
+ getDataByUuid: function(uuid) {
+ return self.getUploads({
+ uuid: uuid
+ });
+ },
+ isQueued: function(id) {
+ var status = self.getUploads({
+ id: id
+ }).status;
+ return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED;
+ },
+ getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
+ getIdsInBatch: self._uploadData.getIdsInBatch
+ };
+ qq.each(this._options.request, function(prop, val) {
+ options[prop] = val;
+ });
+ options.customHeaders = this._customHeadersStore;
+ if (additionalOptions) {
+ qq.each(additionalOptions, function(key, val) {
+ options[key] = val;
+ });
+ }
+ return new qq.UploadHandlerController(options, namespace);
+ },
+ _fileOrBlobRejected: function(id) {
+ this._netUploadedOrQueued--;
+ this._uploadData.setStatus(id, qq.status.REJECTED);
+ },
+ _formatSize: function(bytes) {
+ if (bytes === 0) {
+ return bytes + this._options.text.sizeSymbols[0];
+ }
+ var i = -1;
+ do {
+ bytes = bytes / 1e3;
+ i++;
+ } while (bytes > 999);
+ return Math.max(bytes, .1).toFixed(1) + this._options.text.sizeSymbols[i];
+ },
+ _generateExtraButtonSpecs: function() {
+ var self = this;
+ this._extraButtonSpecs = {};
+ qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
+ var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
+ if (multiple === undefined) {
+ multiple = self._options.multiple;
+ }
+ if (extraButtonSpec.validation) {
+ qq.extend(validation, extraButtonOptionEntry.validation, true);
+ }
+ qq.extend(extraButtonSpec, {
+ multiple: multiple,
+ validation: validation
+ }, true);
+ self._initExtraButton(extraButtonSpec);
+ });
+ },
+ _getButton: function(buttonId) {
+ var extraButtonsSpec = this._extraButtonSpecs[buttonId];
+ if (extraButtonsSpec) {
+ return extraButtonsSpec.element;
+ } else if (buttonId === this._defaultButtonId) {
+ return this._options.button;
+ }
+ },
+ _getButtonId: function(buttonOrFileInputOrFile) {
+ var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile;
+ if (fileBlobOrInput instanceof qq.BlobProxy) {
+ fileBlobOrInput = fileBlobOrInput.referenceBlob;
+ }
+ if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
+ if (qq.isFile(fileBlobOrInput)) {
+ return fileBlobOrInput.qqButtonId;
+ } else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") {
+ return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
+ }
+ inputs = fileBlobOrInput.getElementsByTagName("input");
+ qq.each(inputs, function(idx, input) {
+ if (input.getAttribute("type") === "file") {
+ fileInput = input;
+ return false;
+ }
+ });
+ if (fileInput) {
+ return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
+ }
+ }
+ },
+ _getNotFinished: function() {
+ return this._uploadData.retrieve({
+ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ]
+ }).length;
+ },
+ _getValidationBase: function(buttonId) {
+ var extraButtonSpec = this._extraButtonSpecs[buttonId];
+ return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
+ },
+ _getValidationDescriptor: function(fileWrapper) {
+ if (fileWrapper.file instanceof qq.BlobProxy) {
+ return {
+ name: qq.getFilename(fileWrapper.file.referenceBlob),
+ size: fileWrapper.file.referenceBlob.size
+ };
+ }
+ return {
+ name: this.getUploads({
+ id: fileWrapper.id
+ }).name,
+ size: this.getUploads({
+ id: fileWrapper.id
+ }).size
+ };
+ },
+ _getValidationDescriptors: function(fileWrappers) {
+ var self = this, fileDescriptors = [];
+ qq.each(fileWrappers, function(idx, fileWrapper) {
+ fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
+ });
+ return fileDescriptors;
+ },
+ _handleCameraAccess: function() {
+ if (this._options.camera.ios && qq.ios()) {
+ var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options;
+ if (buttonId && buttonId !== this._defaultButtonId) {
+ optionRoot = this._extraButtonSpecs[buttonId];
+ }
+ optionRoot.multiple = false;
+ if (optionRoot.validation.acceptFiles === null) {
+ optionRoot.validation.acceptFiles = acceptIosCamera;
+ } else {
+ optionRoot.validation.acceptFiles += "," + acceptIosCamera;
+ }
+ qq.each(this._buttons, function(idx, button) {
+ if (button.getButtonId() === buttonId) {
+ button.setMultiple(optionRoot.multiple);
+ button.setAcceptFiles(optionRoot.acceptFiles);
+ return false;
+ }
+ });
+ }
+ },
+ _handleCheckedCallback: function(details) {
+ var self = this, callbackRetVal = details.callback();
+ if (qq.isGenericPromise(callbackRetVal)) {
+ this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
+ return callbackRetVal.then(function(successParam) {
+ self.log(details.name + " promise success for " + details.identifier);
+ details.onSuccess(successParam);
+ }, function() {
+ if (details.onFailure) {
+ self.log(details.name + " promise failure for " + details.identifier);
+ details.onFailure();
+ } else {
+ self.log(details.name + " promise failure for " + details.identifier);
+ }
+ });
+ }
+ if (callbackRetVal !== false) {
+ details.onSuccess(callbackRetVal);
+ } else {
+ if (details.onFailure) {
+ this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
+ details.onFailure();
+ } else {
+ this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
+ }
+ }
+ return callbackRetVal;
+ },
+ _handleNewFile: function(file, batchId, newFileWrapperList) {
+ var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self);
+ if (!qq.isInput(actualFile) && actualFile.size >= 0) {
+ size = actualFile.size;
+ }
+ handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
+ uploadData: self._uploadData,
+ paramsStore: self._paramsStore,
+ addFileToHandler: function(id, file) {
+ self._handler.add(id, file);
+ self._netUploadedOrQueued++;
+ self._trackButton(id);
+ }
+ });
+ },
+ _handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
+ var id = this._uploadData.addFile({
+ uuid: uuid,
+ name: name,
+ size: size,
+ batchId: batchId
+ });
+ this._handler.add(id, file);
+ this._trackButton(id);
+ this._netUploadedOrQueued++;
+ fileList.push({
+ id: id,
+ file: file
+ });
+ },
+ _handlePasteSuccess: function(blob, extSuppliedName) {
+ var extension = blob.type.split("/")[1], name = extSuppliedName;
+ if (name == null) {
+ name = this._options.paste.defaultName;
+ }
+ name += "." + extension;
+ this.addFiles({
+ name: name,
+ blob: blob
+ });
+ },
+ _handleDeleteSuccess: function(id) {
+ if (this.getUploads({
+ id: id
+ }).status !== qq.status.DELETED) {
+ var name = this.getName(id);
+ this._netUploadedOrQueued--;
+ this._netUploaded--;
+ this._handler.expunge(id);
+ this._uploadData.setStatus(id, qq.status.DELETED);
+ this.log("Delete request for '" + name + "' has succeeded.");
+ }
+ },
+ _handleDeleteFailed: function(id, xhrOrXdr) {
+ var name = this.getName(id);
+ this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
+ this.log("Delete request for '" + name + "' has failed.", "error");
+ if (!xhrOrXdr || xhrOrXdr.withCredentials === undefined) {
+ this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
+ } else {
+ this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
+ }
+ },
+ _initExtraButton: function(spec) {
+ var button = this._createUploadButton({
+ accept: spec.validation.acceptFiles,
+ allowedExtensions: spec.validation.allowedExtensions,
+ element: spec.element,
+ folders: spec.folders,
+ multiple: spec.multiple,
+ title: spec.fileInputTitle
+ });
+ this._extraButtonSpecs[button.getButtonId()] = spec;
+ },
+ _initFormSupportAndParams: function() {
+ this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
+ if (this._formSupport && this._formSupport.attachedToForm) {
+ this._paramsStore = this._createStore(this._options.request.params, this._formSupport.getFormInputsAsObject);
+ this._options.autoUpload = this._formSupport.newAutoUpload;
+ if (this._formSupport.newEndpoint) {
+ this._options.request.endpoint = this._formSupport.newEndpoint;
+ }
+ } else {
+ this._paramsStore = this._createStore(this._options.request.params);
+ }
+ },
+ _isDeletePossible: function() {
+ if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
+ return false;
+ }
+ if (this._options.cors.expected) {
+ if (qq.supportedFeatures.deleteFileCorsXhr) {
+ return true;
+ }
+ if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
+ return true;
+ }
+ return false;
+ }
+ return true;
+ },
+ _isAllowedExtension: function(allowed, fileName) {
+ var valid = false;
+ if (!allowed.length) {
+ return true;
+ }
+ qq.each(allowed, function(idx, allowedExt) {
+ if (qq.isString(allowedExt)) {
+ var extRegex = new RegExp("\\." + allowedExt + "$", "i");
+ if (fileName.match(extRegex) != null) {
+ valid = true;
+ return false;
+ }
+ }
+ });
+ return valid;
+ },
+ _itemError: function(code, maybeNameOrNames, item) {
+ var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch;
+ function r(name, replacement) {
+ message = message.replace(name, replacement);
+ }
+ qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
+ if (qq.isString(allowedExtension)) {
+ allowedExtensions.push(allowedExtension);
+ }
+ });
+ extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
+ r("{file}", this._options.formatFileName(name));
+ r("{extensions}", extensionsForMessage);
+ r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
+ r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
+ placeholderMatch = message.match(/(\{\w+\})/g);
+ if (placeholderMatch !== null) {
+ qq.each(placeholderMatch, function(idx, placeholder) {
+ r(placeholder, names[idx]);
+ });
+ }
+ this._options.callbacks.onError(null, name, message, undefined);
+ return message;
+ },
+ _manualRetry: function(id, callback) {
+ if (this._onBeforeManualRetry(id)) {
+ this._netUploadedOrQueued++;
+ this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
+ if (callback) {
+ callback(id);
+ } else {
+ this._handler.retry(id);
+ }
+ return true;
+ }
+ },
+ _maybeAllComplete: function(id, status) {
+ var self = this, notFinished = this._getNotFinished();
+ if (status === qq.status.UPLOAD_SUCCESSFUL) {
+ this._succeededSinceLastAllComplete.push(id);
+ } else if (status === qq.status.UPLOAD_FAILED) {
+ this._failedSinceLastAllComplete.push(id);
+ }
+ if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
+ setTimeout(function() {
+ self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
+ }, 0);
+ }
+ },
+ _maybeHandleIos8SafariWorkaround: function() {
+ var self = this;
+ if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
+ setTimeout(function() {
+ window.alert(self._options.messages.unsupportedBrowserIos8Safari);
+ }, 0);
+ throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
+ }
+ },
+ _maybeParseAndSendUploadError: function(id, name, response, xhr) {
+ if (!response.success) {
+ if (xhr && xhr.status !== 200 && !response.error) {
+ this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
+ } else {
+ var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
+ this._options.callbacks.onError(id, name, errorReason, xhr);
+ }
+ }
+ },
+ _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
+ var self = this;
+ if (items.length > index) {
+ if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
+ setTimeout(function() {
+ var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId);
+ self._handleCheckedCallback({
+ name: "onValidate",
+ callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
+ onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
+ onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
+ identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
+ });
+ }, 0);
+ } else if (!validItem) {
+ for (;index < items.length; index++) {
+ self._fileOrBlobRejected(items[index].id);
+ }
+ }
+ }
+ },
+ _onAllComplete: function(successful, failed) {
+ this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
+ this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
+ this._succeededSinceLastAllComplete = [];
+ this._failedSinceLastAllComplete = [];
+ },
+ _onAutoRetry: function(id, name, responseJSON, xhr, callback) {
+ var self = this;
+ self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
+ if (self._shouldAutoRetry(id, name, responseJSON)) {
+ var retryWaitPeriod = self._options.retry.autoAttemptDelay * 1e3;
+ self._maybeParseAndSendUploadError.apply(self, arguments);
+ self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
+ self._onBeforeAutoRetry(id, name);
+ self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
+ self._retryTimeouts[id] = setTimeout(function() {
+ self.log("Starting retry for " + name + "...");
+ if (callback) {
+ callback(id);
+ } else {
+ self._handler.retry(id);
+ }
+ }, retryWaitPeriod);
+ return true;
+ }
+ },
+ _onBeforeAutoRetry: function(id, name) {
+ this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
+ },
+ _onBeforeManualRetry: function(id) {
+ var itemLimit = this._currentItemLimit, fileName;
+ if (this._preventRetries[id]) {
+ this.log("Retries are forbidden for id " + id, "warn");
+ return false;
+ } else if (this._handler.isValid(id)) {
+ fileName = this.getName(id);
+ if (this._options.callbacks.onManualRetry(id, fileName) === false) {
+ return false;
+ }
+ if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
+ this._itemError("retryFailTooManyItems");
+ return false;
+ }
+ this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
+ return true;
+ } else {
+ this.log("'" + id + "' is not a valid file ID", "error");
+ return false;
+ }
+ },
+ _onCancel: function(id, name) {
+ this._netUploadedOrQueued--;
+ clearTimeout(this._retryTimeouts[id]);
+ var storedItemIndex = qq.indexOf(this._storedIds, id);
+ if (!this._options.autoUpload && storedItemIndex >= 0) {
+ this._storedIds.splice(storedItemIndex, 1);
+ }
+ this._uploadData.setStatus(id, qq.status.CANCELED);
+ },
+ _onComplete: function(id, name, result, xhr) {
+ if (!result.success) {
+ this._netUploadedOrQueued--;
+ this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
+ if (result[this._options.retry.preventRetryResponseProperty] === true) {
+ this._preventRetries[id] = true;
+ }
+ } else {
+ if (result.thumbnailUrl) {
+ this._thumbnailUrls[id] = result.thumbnailUrl;
+ }
+ this._netUploaded++;
+ this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
+ }
+ this._maybeParseAndSendUploadError(id, name, result, xhr);
+ return result.success ? true : false;
+ },
+ _onDelete: function(id) {
+ this._uploadData.setStatus(id, qq.status.DELETING);
+ },
+ _onDeleteComplete: function(id, xhrOrXdr, isError) {
+ var name = this.getName(id);
+ if (isError) {
+ this._handleDeleteFailed(id, xhrOrXdr);
+ } else {
+ this._handleDeleteSuccess(id);
+ }
+ },
+ _onInputChange: function(input) {
+ var fileIndex;
+ if (qq.supportedFeatures.ajaxUploading) {
+ for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
+ this._annotateWithButtonId(input.files[fileIndex], input);
+ }
+ this.addFiles(input.files);
+ } else if (input.value.length > 0) {
+ this.addFiles(input);
+ }
+ qq.each(this._buttons, function(idx, button) {
+ button.reset();
+ });
+ },
+ _onProgress: function(id, name, loaded, total) {
+ this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
+ },
+ _onSubmit: function(id, name) {},
+ _onSubmitCallbackSuccess: function(id, name) {
+ this._onSubmit.apply(this, arguments);
+ this._uploadData.setStatus(id, qq.status.SUBMITTED);
+ this._onSubmitted.apply(this, arguments);
+ if (this._options.autoUpload) {
+ this._options.callbacks.onSubmitted.apply(this, arguments);
+ this._uploadFile(id);
+ } else {
+ this._storeForLater(id);
+ this._options.callbacks.onSubmitted.apply(this, arguments);
+ }
+ },
+ _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
+ var uuid = this.getUuid(id), adjustedOnSuccessCallback;
+ if (onSuccessCallback) {
+ adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
+ }
+ if (this._isDeletePossible()) {
+ this._handleCheckedCallback({
+ name: "onSubmitDelete",
+ callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
+ onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
+ identifier: id
+ });
+ return true;
+ } else {
+ this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn");
+ return false;
+ }
+ },
+ _onSubmitted: function(id) {},
+ _onTotalProgress: function(loaded, total) {
+ this._options.callbacks.onTotalProgress(loaded, total);
+ },
+ _onUploadPrep: function(id) {},
+ _onUpload: function(id, name) {
+ this._uploadData.setStatus(id, qq.status.UPLOADING);
+ },
+ _onUploadChunk: function(id, chunkData) {},
+ _onUploadStatusChange: function(id, oldStatus, newStatus) {
+ if (newStatus === qq.status.PAUSED) {
+ clearTimeout(this._retryTimeouts[id]);
+ }
+ },
+ _onValidateBatchCallbackFailure: function(fileWrappers) {
+ var self = this;
+ qq.each(fileWrappers, function(idx, fileWrapper) {
+ self._fileOrBlobRejected(fileWrapper.id);
+ });
+ },
+ _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
+ var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
+ if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
+ if (items.length > 0) {
+ this._handleCheckedCallback({
+ name: "onValidate",
+ callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
+ onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
+ onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
+ identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
+ });
+ } else {
+ this._itemError("noFilesError");
+ }
+ } else {
+ this._onValidateBatchCallbackFailure(items);
+ errorMessage = this._options.messages.tooManyItemsError.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued).replace(/\{itemLimit\}/g, itemLimit);
+ this._batchError(errorMessage);
+ }
+ },
+ _onValidateCallbackFailure: function(items, index, params, endpoint) {
+ var nextIndex = index + 1;
+ this._fileOrBlobRejected(items[index].id, items[index].file.name);
+ this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
+ },
+ _onValidateCallbackSuccess: function(items, index, params, endpoint) {
+ var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]);
+ this._validateFileOrBlobData(items[index], validationDescriptor).then(function() {
+ self._upload(items[index].id, params, endpoint);
+ self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
+ }, function() {
+ self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
+ });
+ },
+ _prepareItemsForUpload: function(items, params, endpoint) {
+ if (items.length === 0) {
+ this._itemError("noFilesError");
+ return;
+ }
+ var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId);
+ this._handleCheckedCallback({
+ name: "onValidateBatch",
+ callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
+ onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
+ onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
+ identifier: "batch validation"
+ });
+ },
+ _preventLeaveInProgress: function() {
+ var self = this;
+ this._disposeSupport.attach(window, "beforeunload", function(e) {
+ if (self.getInProgress()) {
+ e = e || window.event;
+ e.returnValue = self._options.messages.onLeave;
+ return self._options.messages.onLeave;
+ }
+ });
+ },
+ _refreshSessionData: function() {
+ var self = this, options = this._options.session;
+ if (qq.Session && this._options.session.endpoint != null) {
+ if (!this._session) {
+ qq.extend(options, {
+ cors: this._options.cors
+ });
+ options.log = qq.bind(this.log, this);
+ options.addFileRecord = qq.bind(this._addCannedFile, this);
+ this._session = new qq.Session(options);
+ }
+ setTimeout(function() {
+ self._session.refresh().then(function(response, xhrOrXdr) {
+ self._sessionRequestComplete();
+ self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
+ }, function(response, xhrOrXdr) {
+ self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
+ });
+ }, 0);
+ }
+ },
+ _sessionRequestComplete: function() {},
+ _setSize: function(id, newSize) {
+ this._uploadData.updateSize(id, newSize);
+ this._totalProgress && this._totalProgress.onNewSize(id);
+ },
+ _shouldAutoRetry: function(id, name, responseJSON) {
+ var uploadData = this._uploadData.retrieve({
+ id: id
+ });
+ if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) {
+ if (this._autoRetries[id] === undefined) {
+ this._autoRetries[id] = 0;
+ }
+ if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
+ this._autoRetries[id] += 1;
+ return true;
+ }
+ }
+ return false;
+ },
+ _storeForLater: function(id) {
+ this._storedIds.push(id);
+ },
+ _trackButton: function(id) {
+ var buttonId;
+ if (qq.supportedFeatures.ajaxUploading) {
+ buttonId = this._handler.getFile(id).qqButtonId;
+ } else {
+ buttonId = this._getButtonId(this._handler.getInput(id));
+ }
+ if (buttonId) {
+ this._buttonIdsForFileIds[id] = buttonId;
+ }
+ },
+ _updateFormSupportAndParams: function(formElementOrId) {
+ this._options.form.element = formElementOrId;
+ this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
+ if (this._formSupport && this._formSupport.attachedToForm) {
+ this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);
+ this._options.autoUpload = this._formSupport.newAutoUpload;
+ if (this._formSupport.newEndpoint) {
+ this.setEndpoint(this._formSupport.newEndpoint);
+ }
+ }
+ },
+ _upload: function(id, params, endpoint) {
+ var name = this.getName(id);
+ if (params) {
+ this.setParams(params, id);
+ }
+ if (endpoint) {
+ this.setEndpoint(endpoint, id);
+ }
+ this._handleCheckedCallback({
+ name: "onSubmit",
+ callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
+ onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
+ onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
+ identifier: id
+ });
+ },
+ _uploadFile: function(id) {
+ if (!this._handler.upload(id)) {
+ this._uploadData.setStatus(id, qq.status.QUEUED);
+ }
+ },
+ _uploadStoredFiles: function() {
+ var idToUpload, stillSubmitting, self = this;
+ while (this._storedIds.length) {
+ idToUpload = this._storedIds.shift();
+ this._uploadFile(idToUpload);
+ }
+ stillSubmitting = this.getUploads({
+ status: qq.status.SUBMITTING
+ }).length;
+ if (stillSubmitting) {
+ qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly.");
+ setTimeout(function() {
+ self._uploadStoredFiles();
+ }, 1e3);
+ }
+ },
+ _validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
+ var self = this, file = function() {
+ if (fileWrapper.file instanceof qq.BlobProxy) {
+ return fileWrapper.file.referenceBlob;
+ }
+ return fileWrapper.file;
+ }(), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise();
+ validityChecker.then(function() {}, function() {
+ self._fileOrBlobRejected(fileWrapper.id, name);
+ });
+ if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
+ this._itemError("typeError", name, file);
+ return validityChecker.failure();
+ }
+ if (!this._options.validation.allowEmpty && size === 0) {
+ this._itemError("emptyError", name, file);
+ return validityChecker.failure();
+ }
+ if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
+ this._itemError("sizeError", name, file);
+ return validityChecker.failure();
+ }
+ if (size > 0 && size < validationBase.minSizeLimit) {
+ this._itemError("minSizeError", name, file);
+ return validityChecker.failure();
+ }
+ if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
+ new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(validityChecker.success, function(errorCode) {
+ self._itemError(errorCode + "ImageError", name, file);
+ validityChecker.failure();
+ });
+ } else {
+ validityChecker.success();
+ }
+ return validityChecker;
+ },
+ _wrapCallbacks: function() {
+ var self, safeCallback, prop;
+ self = this;
+ safeCallback = function(name, callback, args) {
+ var errorMsg;
+ try {
+ return callback.apply(self, args);
+ } catch (exception) {
+ errorMsg = exception.message || exception.toString();
+ self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
+ }
+ };
+ for (prop in this._options.callbacks) {
+ (function() {
+ var callbackName, callbackFunc;
+ callbackName = prop;
+ callbackFunc = self._options.callbacks[callbackName];
+ self._options.callbacks[callbackName] = function() {
+ return safeCallback(callbackName, callbackFunc, arguments);
+ };
+ })();
+ }
+ }
+ };
+ })();
+ (function() {
+ "use strict";
+ qq.FineUploaderBasic = function(o) {
+ var self = this;
+ this._options = {
+ debug: false,
+ button: null,
+ multiple: true,
+ maxConnections: 3,
+ disableCancelForFormUploads: false,
+ autoUpload: true,
+ request: {
+ customHeaders: {},
+ endpoint: "/server/upload",
+ filenameParam: "qqfilename",
+ forceMultipart: true,
+ inputName: "qqfile",
+ method: "POST",
+ params: {},
+ paramsInBody: true,
+ totalFileSizeName: "qqtotalfilesize",
+ uuidName: "qquuid"
+ },
+ validation: {
+ allowedExtensions: [],
+ sizeLimit: 0,
+ minSizeLimit: 0,
+ itemLimit: 0,
+ stopOnFirstInvalidFile: true,
+ acceptFiles: null,
+ image: {
+ maxHeight: 0,
+ maxWidth: 0,
+ minHeight: 0,
+ minWidth: 0
+ },
+ allowEmpty: false
+ },
+ callbacks: {
+ onSubmit: function(id, name) {},
+ onSubmitted: function(id, name) {},
+ onComplete: function(id, name, responseJSON, maybeXhr) {},
+ onAllComplete: function(successful, failed) {},
+ onCancel: function(id, name) {},
+ onUpload: function(id, name) {},
+ onUploadChunk: function(id, name, chunkData) {},
+ onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
+ onResume: function(id, fileName, chunkData) {},
+ onProgress: function(id, name, loaded, total) {},
+ onTotalProgress: function(loaded, total) {},
+ onError: function(id, name, reason, maybeXhrOrXdr) {},
+ onAutoRetry: function(id, name, attemptNumber) {},
+ onManualRetry: function(id, name) {},
+ onValidateBatch: function(fileOrBlobData) {},
+ onValidate: function(fileOrBlobData) {},
+ onSubmitDelete: function(id) {},
+ onDelete: function(id) {},
+ onDeleteComplete: function(id, xhrOrXdr, isError) {},
+ onPasteReceived: function(blob) {},
+ onStatusChange: function(id, oldStatus, newStatus) {},
+ onSessionRequestComplete: function(response, success, xhrOrXdr) {}
+ },
+ messages: {
+ typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
+ sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
+ minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
+ emptyError: "{file} is empty, please select files again without it.",
+ noFilesError: "No files to upload.",
+ tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
+ maxHeightImageError: "Image is too tall.",
+ maxWidthImageError: "Image is too wide.",
+ minHeightImageError: "Image is not tall enough.",
+ minWidthImageError: "Image is not wide enough.",
+ retryFailTooManyItems: "Retry failed - you have reached your file limit.",
+ onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
+ unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
+ },
+ retry: {
+ enableAuto: false,
+ maxAutoAttempts: 3,
+ autoAttemptDelay: 5,
+ preventRetryResponseProperty: "preventRetry"
+ },
+ classes: {
+ buttonHover: "qq-upload-button-hover",
+ buttonFocus: "qq-upload-button-focus"
+ },
+ chunking: {
+ enabled: false,
+ concurrent: {
+ enabled: false
+ },
+ mandatory: false,
+ paramNames: {
+ partIndex: "qqpartindex",
+ partByteOffset: "qqpartbyteoffset",
+ chunkSize: "qqchunksize",
+ totalFileSize: "qqtotalfilesize",
+ totalParts: "qqtotalparts"
+ },
+ partSize: 2e6,
+ success: {
+ endpoint: null
+ }
+ },
+ resume: {
+ enabled: false,
+ recordsExpireIn: 7,
+ paramNames: {
+ resuming: "qqresume"
+ }
+ },
+ formatFileName: function(fileOrBlobName) {
+ return fileOrBlobName;
+ },
+ text: {
+ defaultResponseError: "Upload failure reason unknown",
+ fileInputTitle: "file input",
+ sizeSymbols: [ "kB", "MB", "GB", "TB", "PB", "EB" ]
+ },
+ deleteFile: {
+ enabled: false,
+ method: "DELETE",
+ endpoint: "/server/upload",
+ customHeaders: {},
+ params: {}
+ },
+ cors: {
+ expected: false,
+ sendCredentials: false,
+ allowXdr: false
+ },
+ blobs: {
+ defaultName: "misc_data"
+ },
+ paste: {
+ targetElement: null,
+ defaultName: "pasted_image"
+ },
+ camera: {
+ ios: false,
+ button: null
+ },
+ extraButtons: [],
+ session: {
+ endpoint: null,
+ params: {},
+ customHeaders: {},
+ refreshOnReset: true
+ },
+ form: {
+ element: "qq-form",
+ autoUpload: false,
+ interceptSubmit: true
+ },
+ scaling: {
+ customResizer: null,
+ sendOriginal: true,
+ orient: true,
+ defaultType: null,
+ defaultQuality: 80,
+ failureText: "Failed to scale",
+ includeExif: false,
+ sizes: []
+ },
+ workarounds: {
+ iosEmptyVideos: true,
+ ios8SafariUploads: true,
+ ios8BrowserCrash: false
+ }
+ };
+ qq.extend(this._options, o, true);
+ this._buttons = [];
+ this._extraButtonSpecs = {};
+ this._buttonIdsForFileIds = [];
+ this._wrapCallbacks();
+ this._disposeSupport = new qq.DisposeSupport();
+ this._storedIds = [];
+ this._autoRetries = [];
+ this._retryTimeouts = [];
+ this._preventRetries = [];
+ this._thumbnailUrls = [];
+ this._netUploadedOrQueued = 0;
+ this._netUploaded = 0;
+ this._uploadData = this._createUploadDataTracker();
+ this._initFormSupportAndParams();
+ this._customHeadersStore = this._createStore(this._options.request.customHeaders);
+ this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
+ this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
+ this._endpointStore = this._createStore(this._options.request.endpoint);
+ this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
+ this._handler = this._createUploadHandler();
+ this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
+ if (this._options.button) {
+ this._defaultButtonId = this._createUploadButton({
+ element: this._options.button,
+ title: this._options.text.fileInputTitle
+ }).getButtonId();
+ }
+ this._generateExtraButtonSpecs();
+ this._handleCameraAccess();
+ if (this._options.paste.targetElement) {
+ if (qq.PasteSupport) {
+ this._pasteHandler = this._createPasteHandler();
+ } else {
+ this.log("Paste support module not found", "error");
+ }
+ }
+ this._preventLeaveInProgress();
+ this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
+ this._refreshSessionData();
+ this._succeededSinceLastAllComplete = [];
+ this._failedSinceLastAllComplete = [];
+ this._scaler = qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this)) || {};
+ if (this._scaler.enabled) {
+ this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
+ }
+ if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
+ this._totalProgress = new qq.TotalProgress(qq.bind(this._onTotalProgress, this), function(id) {
+ var entry = self._uploadData.retrieve({
+ id: id
+ });
+ return entry && entry.size || 0;
+ });
+ }
+ this._currentItemLimit = this._options.validation.itemLimit;
+ };
+ qq.FineUploaderBasic.prototype = qq.basePublicApi;
+ qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
+ })();
+ qq.AjaxRequester = function(o) {
+ "use strict";
+ var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = {
+ acceptHeader: null,
+ validMethods: [ "PATCH", "POST", "PUT" ],
+ method: "POST",
+ contentType: "application/x-www-form-urlencoded",
+ maxConnections: 3,
+ customHeaders: {},
+ endpointStore: {},
+ paramsStore: {},
+ mandatedParams: {},
+ allowXRequestedWithAndCacheControl: true,
+ successfulResponseCodes: {
+ DELETE: [ 200, 202, 204 ],
+ PATCH: [ 200, 201, 202, 203, 204 ],
+ POST: [ 200, 201, 202, 203, 204 ],
+ PUT: [ 200, 201, 202, 203, 204 ],
+ GET: [ 200 ]
+ },
+ cors: {
+ expected: false,
+ sendCredentials: false
+ },
+ log: function(str, level) {},
+ onSend: function(id) {},
+ onComplete: function(id, xhrOrXdr, isError) {},
+ onProgress: null
+ };
+ qq.extend(options, o);
+ log = options.log;
+ if (qq.indexOf(options.validMethods, options.method) < 0) {
+ throw new Error("'" + options.method + "' is not a supported method for this type of request!");
+ }
+ function isSimpleMethod() {
+ return qq.indexOf([ "GET", "POST", "HEAD" ], options.method) >= 0;
+ }
+ function containsNonSimpleHeaders(headers) {
+ var containsNonSimple = false;
+ qq.each(containsNonSimple, function(idx, header) {
+ if (qq.indexOf([ "Accept", "Accept-Language", "Content-Language", "Content-Type" ], header) < 0) {
+ containsNonSimple = true;
+ return false;
+ }
+ });
+ return containsNonSimple;
+ }
+ function isXdr(xhr) {
+ return options.cors.expected && xhr.withCredentials === undefined;
+ }
+ function getCorsAjaxTransport() {
+ var xhrOrXdr;
+ if (window.XMLHttpRequest || window.ActiveXObject) {
+ xhrOrXdr = qq.createXhrInstance();
+ if (xhrOrXdr.withCredentials === undefined) {
+ xhrOrXdr = new XDomainRequest();
+ xhrOrXdr.onload = function() {};
+ xhrOrXdr.onerror = function() {};
+ xhrOrXdr.ontimeout = function() {};
+ xhrOrXdr.onprogress = function() {};
+ }
+ }
+ return xhrOrXdr;
+ }
+ function getXhrOrXdr(id, suppliedXhr) {
+ var xhrOrXdr = requestData[id].xhr;
+ if (!xhrOrXdr) {
+ if (suppliedXhr) {
+ xhrOrXdr = suppliedXhr;
+ } else {
+ if (options.cors.expected) {
+ xhrOrXdr = getCorsAjaxTransport();
+ } else {
+ xhrOrXdr = qq.createXhrInstance();
+ }
+ }
+ requestData[id].xhr = xhrOrXdr;
+ }
+ return xhrOrXdr;
+ }
+ function dequeue(id) {
+ var i = qq.indexOf(queue, id), max = options.maxConnections, nextId;
+ delete requestData[id];
+ queue.splice(i, 1);
+ if (queue.length >= max && i < max) {
+ nextId = queue[max - 1];
+ sendRequest(nextId);
+ }
+ }
+ function onComplete(id, xdrError) {
+ var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true;
+ dequeue(id);
+ if (isError) {
+ log(method + " request for " + id + " has failed", "error");
+ } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
+ isError = true;
+ log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
+ }
+ options.onComplete(id, xhr, isError);
+ }
+ function getParams(id) {
+ var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params;
+ if (options.paramsStore.get) {
+ params = options.paramsStore.get(id);
+ }
+ if (onDemandParams) {
+ qq.each(onDemandParams, function(name, val) {
+ params = params || {};
+ params[name] = val;
+ });
+ }
+ if (mandatedParams) {
+ qq.each(mandatedParams, function(name, val) {
+ params = params || {};
+ params[name] = val;
+ });
+ }
+ return params;
+ }
+ function sendRequest(id, optXhr) {
+ var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url;
+ options.onSend(id);
+ url = createUrl(id, params, requestData[id].additionalQueryParams);
+ if (isXdr(xhr)) {
+ xhr.onload = getXdrLoadHandler(id);
+ xhr.onerror = getXdrErrorHandler(id);
+ } else {
+ xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
+ }
+ registerForUploadProgress(id);
+ xhr.open(method, url, true);
+ if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
+ xhr.withCredentials = true;
+ }
+ setHeaders(id);
+ log("Sending " + method + " request for " + id);
+ if (payload) {
+ xhr.send(payload);
+ } else if (shouldParamsBeInQueryString || !params) {
+ xhr.send();
+ } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
+ xhr.send(qq.obj2url(params, ""));
+ } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
+ xhr.send(JSON.stringify(params));
+ } else {
+ xhr.send(params);
+ }
+ return xhr;
+ }
+ function createUrl(id, params, additionalQueryParams) {
+ var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath;
+ if (addToPath != undefined) {
+ endpoint += "/" + addToPath;
+ }
+ if (shouldParamsBeInQueryString && params) {
+ endpoint = qq.obj2url(params, endpoint);
+ }
+ if (additionalQueryParams) {
+ endpoint = qq.obj2url(additionalQueryParams, endpoint);
+ }
+ return endpoint;
+ }
+ function getXhrReadyStateChangeHandler(id) {
+ return function() {
+ if (getXhrOrXdr(id).readyState === 4) {
+ onComplete(id);
+ }
+ };
+ }
+ function registerForUploadProgress(id) {
+ var onProgress = options.onProgress;
+ if (onProgress) {
+ getXhrOrXdr(id).upload.onprogress = function(e) {
+ if (e.lengthComputable) {
+ onProgress(id, e.loaded, e.total);
+ }
+ };
+ }
+ }
+ function getXdrLoadHandler(id) {
+ return function() {
+ onComplete(id);
+ };
+ }
+ function getXdrErrorHandler(id) {
+ return function() {
+ onComplete(id, true);
+ };
+ }
+ function setHeaders(id) {
+ var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {};
+ if (!isXdr(xhr)) {
+ options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
+ if (options.allowXRequestedWithAndCacheControl) {
+ if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.setRequestHeader("Cache-Control", "no-cache");
+ }
+ }
+ if (options.contentType && (method === "POST" || method === "PUT")) {
+ xhr.setRequestHeader("Content-Type", options.contentType);
+ }
+ qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
+ qq.extend(allHeaders, onDemandHeaders);
+ qq.each(allHeaders, function(name, val) {
+ xhr.setRequestHeader(name, val);
+ });
+ }
+ }
+ function isResponseSuccessful(responseCode) {
+ return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
+ }
+ function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) {
+ requestData[id] = {
+ addToPath: addToPath,
+ additionalParams: additionalParams,
+ additionalQueryParams: additionalQueryParams,
+ additionalHeaders: additionalHeaders,
+ payload: payload
+ };
+ var len = queue.push(id);
+ if (len <= options.maxConnections) {
+ return sendRequest(id, optXhr);
+ }
+ }
+ shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
+ qq.extend(this, {
+ initTransport: function(id) {
+ var path, params, headers, payload, cacheBuster, additionalQueryParams;
+ return {
+ withPath: function(appendToPath) {
+ path = appendToPath;
+ return this;
+ },
+ withParams: function(additionalParams) {
+ params = additionalParams;
+ return this;
+ },
+ withQueryParams: function(_additionalQueryParams_) {
+ additionalQueryParams = _additionalQueryParams_;
+ return this;
+ },
+ withHeaders: function(additionalHeaders) {
+ headers = additionalHeaders;
+ return this;
+ },
+ withPayload: function(thePayload) {
+ payload = thePayload;
+ return this;
+ },
+ withCacheBuster: function() {
+ cacheBuster = true;
+ return this;
+ },
+ send: function(optXhr) {
+ if (cacheBuster && qq.indexOf([ "GET", "DELETE" ], options.method) >= 0) {
+ params.qqtimestamp = new Date().getTime();
+ }
+ return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload);
+ }
+ };
+ },
+ canceled: function(id) {
+ dequeue(id);
+ }
+ });
+ };
+ qq.UploadHandler = function(spec) {
+ "use strict";
+ var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName;
+ qq.extend(this, {
+ add: function(id, fileItem) {
+ fileState[id] = fileItem;
+ fileState[id].temp = {};
+ },
+ cancel: function(id) {
+ var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
+ onCancelRetVal.then(function() {
+ if (self.isValid(id)) {
+ fileState[id].canceled = true;
+ self.expunge(id);
+ }
+ cancelFinalizationEffort.success();
+ });
+ },
+ expunge: function(id) {
+ delete fileState[id];
+ },
+ getThirdPartyFileId: function(id) {
+ return fileState[id].key;
+ },
+ isValid: function(id) {
+ return fileState[id] !== undefined;
+ },
+ reset: function() {
+ fileState = {};
+ },
+ _getFileState: function(id) {
+ return fileState[id];
+ },
+ _setThirdPartyFileId: function(id, thirdPartyFileId) {
+ fileState[id].key = thirdPartyFileId;
+ },
+ _wasCanceled: function(id) {
+ return !!fileState[id].canceled;
+ }
+ });
+ };
+ qq.UploadHandlerController = function(o, namespace) {
+ "use strict";
+ var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = {
+ paramsStore: {},
+ maxConnections: 3,
+ chunking: {
+ enabled: false,
+ multiple: {
+ enabled: false
+ }
+ },
+ log: function(str, level) {},
+ onProgress: function(id, fileName, loaded, total) {},
+ onComplete: function(id, fileName, response, xhr) {},
+ onCancel: function(id, fileName) {},
+ onUploadPrep: function(id) {},
+ onUpload: function(id, fileName) {},
+ onUploadChunk: function(id, fileName, chunkData) {},
+ onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
+ onAutoRetry: function(id, fileName, response, xhr) {},
+ onResume: function(id, fileName, chunkData) {},
+ onUuidChanged: function(id, newUuid) {},
+ getName: function(id) {},
+ setSize: function(id, newSize) {},
+ isQueued: function(id) {},
+ getIdsInProxyGroup: function(id) {},
+ getIdsInBatch: function(id) {}
+ }, chunked = {
+ done: function(id, chunkIdx, response, xhr) {
+ var chunkData = handler._getChunkData(id, chunkIdx);
+ handler._getFileState(id).attemptingResume = false;
+ delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
+ handler._getFileState(id).loaded += chunkData.size;
+ options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
+ },
+ finalize: function(id) {
+ var size = options.getSize(id), name = options.getName(id);
+ log("All chunks have been uploaded for " + id + " - finalizing....");
+ handler.finalizeChunks(id).then(function(response, xhr) {
+ log("Finalize successful for " + id);
+ var normaizedResponse = upload.normalizeResponse(response, true);
+ options.onProgress(id, name, size, size);
+ handler._maybeDeletePersistedChunkData(id);
+ upload.cleanup(id, normaizedResponse, xhr);
+ }, function(response, xhr) {
+ var normaizedResponse = upload.normalizeResponse(response, false);
+ log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
+ if (normaizedResponse.reset) {
+ chunked.reset(id);
+ }
+ if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
+ upload.cleanup(id, normaizedResponse, xhr);
+ }
+ });
+ },
+ handleFailure: function(chunkIdx, id, response, xhr) {
+ var name = options.getName(id);
+ log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
+ handler.clearCachedChunk(id, chunkIdx);
+ var responseToReport = upload.normalizeResponse(response, false), inProgressIdx;
+ if (responseToReport.reset) {
+ chunked.reset(id);
+ } else {
+ inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
+ if (inProgressIdx >= 0) {
+ handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
+ handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
+ }
+ }
+ if (!handler._getFileState(id).temp.ignoreFailure) {
+ if (concurrentChunkingPossible) {
+ handler._getFileState(id).temp.ignoreFailure = true;
+ log(qq.format("Going to attempt to abort these chunks: {}. These are currently in-progress: {}.", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress)));
+ qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
+ log(qq.format("Attempting to abort file {}.{}. XHR readyState {}. ", id, ckid, ckXhr.readyState));
+ ckXhr.abort();
+ ckXhr._cancelled = true;
+ });
+ handler.moveInProgressToRemaining(id);
+ connectionManager.free(id, true);
+ }
+ if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
+ upload.cleanup(id, responseToReport, xhr);
+ }
+ }
+ },
+ hasMoreParts: function(id) {
+ return !!handler._getFileState(id).chunking.remaining.length;
+ },
+ nextPart: function(id) {
+ var nextIdx = handler._getFileState(id).chunking.remaining.shift();
+ if (nextIdx >= handler._getTotalChunks(id)) {
+ nextIdx = null;
+ }
+ return nextIdx;
+ },
+ reset: function(id) {
+ log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
+ handler._maybeDeletePersistedChunkData(id);
+ handler.reevaluateChunking(id);
+ handler._getFileState(id).loaded = 0;
+ },
+ sendNext: function(id) {
+ var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
+ if (handler._getFileState(id).loaded == null) {
+ handler._getFileState(id).loaded = 0;
+ }
+ if (resuming && options.onResume(id, name, chunkData) === false) {
+ chunked.reset(id);
+ chunkIdx = chunked.nextPart(id);
+ chunkData = handler._getChunkData(id, chunkIdx);
+ resuming = false;
+ }
+ if (chunkIdx == null && inProgressChunks.length === 0) {
+ chunked.finalize(id);
+ } else {
+ log(qq.format("Sending chunked upload request for item {}.{}, bytes {}-{} of {}.", id, chunkIdx, chunkData.start + 1, chunkData.end, size));
+ options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
+ inProgressChunks.push(chunkIdx);
+ handler._getFileState(id).chunking.inProgress = inProgressChunks;
+ if (concurrentChunkingPossible) {
+ connectionManager.open(id, chunkIdx);
+ }
+ if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
+ chunked.sendNext(id);
+ }
+ if (chunkData.blob.size === 0) {
+ log(qq.format("Chunk {} for file {} will not be uploaded, zero sized chunk.", chunkIdx, id), "error");
+ chunked.handleFailure(chunkIdx, id, "File is no longer available", null);
+ } else {
+ handler.uploadChunk(id, chunkIdx, resuming).then(function success(response, xhr) {
+ log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
+ handler.clearCachedChunk(id, chunkIdx);
+ var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
+ log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
+ chunked.done(id, chunkIdx, responseToReport, xhr);
+ if (inProgressChunkIdx >= 0) {
+ inProgressChunks.splice(inProgressChunkIdx, 1);
+ }
+ handler._maybePersistChunkedState(id);
+ if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
+ chunked.finalize(id);
+ } else if (chunked.hasMoreParts(id)) {
+ chunked.sendNext(id);
+ } else {
+ log(qq.format("File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}", id, JSON.stringify(inProgressChunks)));
+ }
+ }, function failure(response, xhr) {
+ chunked.handleFailure(chunkIdx, id, response, xhr);
+ }).done(function() {
+ handler.clearXhr(id, chunkIdx);
+ });
+ }
+ }
+ }
+ }, connectionManager = {
+ _open: [],
+ _openChunks: {},
+ _waiting: [],
+ available: function() {
+ var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0;
+ qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
+ openChunkEntriesCount++;
+ openChunksCount += openChunkIndexes.length;
+ });
+ return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
+ },
+ free: function(id, dontAllowNext) {
+ var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId;
+ delete connectionManager._openChunks[id];
+ if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
+ log("Generated blob upload has ended for " + id + ", disposing generated blob.");
+ delete handler._getFileState(id).file;
+ }
+ if (waitingIndex >= 0) {
+ connectionManager._waiting.splice(waitingIndex, 1);
+ } else if (allowNext && connectionsIndex >= 0) {
+ connectionManager._open.splice(connectionsIndex, 1);
+ nextId = connectionManager._waiting.shift();
+ if (nextId >= 0) {
+ connectionManager._open.push(nextId);
+ upload.start(nextId);
+ }
+ }
+ },
+ getWaitingOrConnected: function() {
+ var waitingOrConnected = [];
+ qq.each(connectionManager._openChunks, function(fileId, chunks) {
+ if (chunks && chunks.length) {
+ waitingOrConnected.push(parseInt(fileId));
+ }
+ });
+ qq.each(connectionManager._open, function(idx, fileId) {
+ if (!connectionManager._openChunks[fileId]) {
+ waitingOrConnected.push(parseInt(fileId));
+ }
+ });
+ waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
+ return waitingOrConnected;
+ },
+ isUsingConnection: function(id) {
+ return qq.indexOf(connectionManager._open, id) >= 0;
+ },
+ open: function(id, chunkIdx) {
+ if (chunkIdx == null) {
+ connectionManager._waiting.push(id);
+ }
+ if (connectionManager.available()) {
+ if (chunkIdx == null) {
+ connectionManager._waiting.pop();
+ connectionManager._open.push(id);
+ } else {
+ (function() {
+ var openChunksEntry = connectionManager._openChunks[id] || [];
+ openChunksEntry.push(chunkIdx);
+ connectionManager._openChunks[id] = openChunksEntry;
+ })();
+ }
+ return true;
+ }
+ return false;
+ },
+ reset: function() {
+ connectionManager._waiting = [];
+ connectionManager._open = [];
+ }
+ }, simple = {
+ send: function(id, name) {
+ handler._getFileState(id).loaded = 0;
+ log("Sending simple upload request for " + id);
+ handler.uploadFile(id).then(function(response, optXhr) {
+ log("Simple upload request succeeded for " + id);
+ var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id);
+ options.onProgress(id, name, size, size);
+ upload.maybeNewUuid(id, responseToReport);
+ upload.cleanup(id, responseToReport, optXhr);
+ }, function(response, optXhr) {
+ log("Simple upload request failed for " + id);
+ var responseToReport = upload.normalizeResponse(response, false);
+ if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
+ upload.cleanup(id, responseToReport, optXhr);
+ }
+ });
+ }
+ }, upload = {
+ cancel: function(id) {
+ log("Cancelling " + id);
+ options.paramsStore.remove(id);
+ connectionManager.free(id);
+ },
+ cleanup: function(id, response, optXhr) {
+ var name = options.getName(id);
+ options.onComplete(id, name, response, optXhr);
+ if (handler._getFileState(id)) {
+ handler._clearXhrs && handler._clearXhrs(id);
+ }
+ connectionManager.free(id);
+ },
+ getProxyOrBlob: function(id) {
+ return handler.getProxy && handler.getProxy(id) || handler.getFile && handler.getFile(id);
+ },
+ initHandler: function() {
+ var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
+ handler = new handlerType[handlerModuleSubtype + "UploadHandler"](options, {
+ getDataByUuid: options.getDataByUuid,
+ getName: options.getName,
+ getSize: options.getSize,
+ getUuid: options.getUuid,
+ log: log,
+ onCancel: options.onCancel,
+ onProgress: options.onProgress,
+ onUuidChanged: options.onUuidChanged
+ });
+ if (handler._removeExpiredChunkingRecords) {
+ handler._removeExpiredChunkingRecords();
+ }
+ },
+ isDeferredEligibleForUpload: function(id) {
+ return options.isQueued(id);
+ },
+ maybeDefer: function(id, blob) {
+ if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
+ options.onUploadPrep(id);
+ log("Attempting to generate a blob on-demand for " + id);
+ blob.create().then(function(generatedBlob) {
+ log("Generated an on-demand blob for " + id);
+ handler.updateBlob(id, generatedBlob);
+ options.setSize(id, generatedBlob.size);
+ handler.reevaluateChunking(id);
+ upload.maybeSendDeferredFiles(id);
+ }, function(errorMessage) {
+ var errorResponse = {};
+ if (errorMessage) {
+ errorResponse.error = errorMessage;
+ }
+ log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
+ options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
+ upload.maybeSendDeferredFiles(id);
+ connectionManager.free(id);
+ });
+ } else {
+ return upload.maybeSendDeferredFiles(id);
+ }
+ return false;
+ },
+ maybeSendDeferredFiles: function(id) {
+ var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false;
+ if (idsInGroup && idsInGroup.length) {
+ log("Maybe ready to upload proxy group file " + id);
+ qq.each(idsInGroup, function(idx, idInGroup) {
+ if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
+ uploadedThisId = idInGroup === id;
+ upload.now(idInGroup);
+ } else if (upload.isDeferredEligibleForUpload(idInGroup)) {
+ return false;
+ }
+ });
+ } else {
+ uploadedThisId = true;
+ upload.now(id);
+ }
+ return uploadedThisId;
+ },
+ maybeNewUuid: function(id, response) {
+ if (response.newUuid !== undefined) {
+ options.onUuidChanged(id, response.newUuid);
+ }
+ },
+ normalizeResponse: function(originalResponse, successful) {
+ var response = originalResponse;
+ if (!qq.isObject(originalResponse)) {
+ response = {};
+ if (qq.isString(originalResponse) && !successful) {
+ response.error = originalResponse;
+ }
+ }
+ response.success = successful;
+ return response;
+ },
+ now: function(id) {
+ var name = options.getName(id);
+ if (!controller.isValid(id)) {
+ throw new qq.Error(id + " is not a valid file ID to upload!");
+ }
+ options.onUpload(id, name);
+ if (chunkingPossible && handler._shouldChunkThisFile(id)) {
+ chunked.sendNext(id);
+ } else {
+ simple.send(id, name);
+ }
+ },
+ start: function(id) {
+ var blobToUpload = upload.getProxyOrBlob(id);
+ if (blobToUpload) {
+ return upload.maybeDefer(id, blobToUpload);
+ } else {
+ upload.now(id);
+ return true;
+ }
+ }
+ };
+ qq.extend(this, {
+ add: function(id, file) {
+ handler.add.apply(this, arguments);
+ },
+ upload: function(id) {
+ if (connectionManager.open(id)) {
+ return upload.start(id);
+ }
+ return false;
+ },
+ retry: function(id) {
+ if (concurrentChunkingPossible) {
+ handler._getFileState(id).temp.ignoreFailure = false;
+ }
+ if (connectionManager.isUsingConnection(id)) {
+ return upload.start(id);
+ } else {
+ return controller.upload(id);
+ }
+ },
+ cancel: function(id) {
+ var cancelRetVal = handler.cancel(id);
+ if (qq.isGenericPromise(cancelRetVal)) {
+ cancelRetVal.then(function() {
+ upload.cancel(id);
+ });
+ } else if (cancelRetVal !== false) {
+ upload.cancel(id);
+ }
+ },
+ cancelAll: function() {
+ var waitingOrConnected = connectionManager.getWaitingOrConnected(), i;
+ if (waitingOrConnected.length) {
+ for (i = waitingOrConnected.length - 1; i >= 0; i--) {
+ controller.cancel(waitingOrConnected[i]);
+ }
+ }
+ connectionManager.reset();
+ },
+ getFile: function(id) {
+ if (handler.getProxy && handler.getProxy(id)) {
+ return handler.getProxy(id).referenceBlob;
+ }
+ return handler.getFile && handler.getFile(id);
+ },
+ isProxied: function(id) {
+ return !!(handler.getProxy && handler.getProxy(id));
+ },
+ getInput: function(id) {
+ if (handler.getInput) {
+ return handler.getInput(id);
+ }
+ },
+ reset: function() {
+ log("Resetting upload handler");
+ controller.cancelAll();
+ connectionManager.reset();
+ handler.reset();
+ },
+ expunge: function(id) {
+ if (controller.isValid(id)) {
+ return handler.expunge(id);
+ }
+ },
+ isValid: function(id) {
+ return handler.isValid(id);
+ },
+ getResumableFilesData: function() {
+ if (handler.getResumableFilesData) {
+ return handler.getResumableFilesData();
+ }
+ return [];
+ },
+ getThirdPartyFileId: function(id) {
+ if (controller.isValid(id)) {
+ return handler.getThirdPartyFileId(id);
+ }
+ },
+ pause: function(id) {
+ if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
+ connectionManager.free(id);
+ handler.moveInProgressToRemaining(id);
+ return true;
+ }
+ return false;
+ },
+ isResumable: function(id) {
+ return !!handler.isResumable && handler.isResumable(id);
+ }
+ });
+ qq.extend(options, o);
+ log = options.log;
+ chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
+ concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
+ preventRetryResponse = function() {
+ var response = {};
+ response[options.preventRetryParam] = true;
+ return response;
+ }();
+ upload.initHandler();
+ };
+ qq.WindowReceiveMessage = function(o) {
+ "use strict";
+ var options = {
+ log: function(message, level) {}
+ }, callbackWrapperDetachers = {};
+ qq.extend(options, o);
+ qq.extend(this, {
+ receiveMessage: function(id, callback) {
+ var onMessageCallbackWrapper = function(event) {
+ callback(event.data);
+ };
+ if (window.postMessage) {
+ callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
+ } else {
+ log("iframe message passing not supported in this browser!", "error");
+ }
+ },
+ stopReceivingMessages: function(id) {
+ if (window.postMessage) {
+ var detacher = callbackWrapperDetachers[id];
+ if (detacher) {
+ detacher();
+ }
+ }
+ }
+ });
+ };
+ qq.FormUploadHandler = function(spec) {
+ "use strict";
+ var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({
+ log: log
+ });
+ function expungeFile(id) {
+ delete detachLoadEvents[id];
+ if (isCors) {
+ clearTimeout(postMessageCallbackTimers[id]);
+ delete postMessageCallbackTimers[id];
+ corsMessageReceiver.stopReceivingMessages(id);
+ }
+ var iframe = document.getElementById(handler._getIframeName(id));
+ if (iframe) {
+ iframe.setAttribute("src", "javascript:false;");
+ qq(iframe).remove();
+ }
+ }
+ function getFileIdForIframeName(iframeName) {
+ return iframeName.split("_")[0];
+ }
+ function initIframeForUpload(name) {
+ var iframe = qq.toElement("");
+ iframe.setAttribute("id", name);
+ iframe.style.display = "none";
+ document.body.appendChild(iframe);
+ return iframe;
+ }
+ function registerPostMessageCallback(iframe, callback) {
+ var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId);
+ onloadCallbacks[uuid] = callback;
+ detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
+ if (handler.getInput(fileId)) {
+ log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
+ postMessageCallbackTimers[iframeName] = setTimeout(function() {
+ var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
+ log(errorMessage, "error");
+ callback({
+ error: errorMessage
+ });
+ }, 1e3);
+ }
+ });
+ corsMessageReceiver.receiveMessage(iframeName, function(message) {
+ log("Received the following window message: '" + message + "'");
+ var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback;
+ if (uuid && onloadCallbacks[uuid]) {
+ log("Handling response for iframe name " + iframeName);
+ clearTimeout(postMessageCallbackTimers[iframeName]);
+ delete postMessageCallbackTimers[iframeName];
+ handler._detachLoadEvent(iframeName);
+ onloadCallback = onloadCallbacks[uuid];
+ delete onloadCallbacks[uuid];
+ corsMessageReceiver.stopReceivingMessages(iframeName);
+ onloadCallback(response);
+ } else if (!uuid) {
+ log("'" + message + "' does not contain a UUID - ignoring.");
+ }
+ });
+ }
+ qq.extend(this, new qq.UploadHandler(spec));
+ qq.override(this, function(super_) {
+ return {
+ add: function(id, fileInput) {
+ super_.add(id, {
+ input: fileInput
+ });
+ fileInput.setAttribute("name", inputName);
+ if (fileInput.parentNode) {
+ qq(fileInput).remove();
+ }
+ },
+ expunge: function(id) {
+ expungeFile(id);
+ super_.expunge(id);
+ },
+ isValid: function(id) {
+ return super_.isValid(id) && handler._getFileState(id).input !== undefined;
+ }
+ };
+ });
+ qq.extend(this, {
+ getInput: function(id) {
+ return handler._getFileState(id).input;
+ },
+ _attachLoadEvent: function(iframe, callback) {
+ var responseDescriptor;
+ if (isCors) {
+ registerPostMessageCallback(iframe, callback);
+ } else {
+ detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
+ log("Received response for " + iframe.id);
+ if (!iframe.parentNode) {
+ return;
+ }
+ try {
+ if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") {
+ return;
+ }
+ } catch (error) {
+ log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
+ responseDescriptor = {
+ success: false
+ };
+ }
+ callback(responseDescriptor);
+ });
+ }
+ },
+ _createIframe: function(id) {
+ var iframeName = handler._getIframeName(id);
+ return initIframeForUpload(iframeName);
+ },
+ _detachLoadEvent: function(id) {
+ if (detachLoadEvents[id] !== undefined) {
+ detachLoadEvents[id]();
+ delete detachLoadEvents[id];
+ }
+ },
+ _getIframeName: function(fileId) {
+ return fileId + "_" + formHandlerInstanceId;
+ },
+ _initFormForUpload: function(spec) {
+ var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement(""), url = endpoint;
+ if (paramsInBody) {
+ qq.obj2Inputs(params, form);
+ } else {
+ url = qq.obj2url(params, endpoint);
+ }
+ form.setAttribute("action", url);
+ form.setAttribute("target", targetName);
+ form.style.display = "none";
+ document.body.appendChild(form);
+ return form;
+ },
+ _parseJsonResponse: function(innerHtmlOrMessage) {
+ var response = {};
+ try {
+ response = qq.parseJson(innerHtmlOrMessage);
+ } catch (error) {
+ log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
+ }
+ return response;
+ }
+ });
+ };
+ qq.XhrUploadHandler = function(spec) {
+ "use strict";
+ var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log;
+ function abort(id) {
+ qq.each(handler._getXhrs(id), function(xhrId, xhr) {
+ var ajaxRequester = handler._getAjaxRequester(id, xhrId);
+ xhr.onreadystatechange = null;
+ xhr.upload.onprogress = null;
+ xhr.abort();
+ ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
+ });
+ }
+ qq.extend(this, new qq.UploadHandler(spec));
+ qq.override(this, function(super_) {
+ return {
+ add: function(id, blobOrProxy) {
+ if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
+ super_.add(id, {
+ file: blobOrProxy
+ });
+ } else if (blobOrProxy instanceof qq.BlobProxy) {
+ super_.add(id, {
+ proxy: blobOrProxy
+ });
+ } else {
+ throw new Error("Passed obj is not a File, Blob, or proxy");
+ }
+ handler._initTempState(id);
+ resumeEnabled && handler._maybePrepareForResume(id);
+ },
+ expunge: function(id) {
+ abort(id);
+ handler._maybeDeletePersistedChunkData(id);
+ handler._clearXhrs(id);
+ super_.expunge(id);
+ }
+ };
+ });
+ qq.extend(this, {
+ clearCachedChunk: function(id, chunkIdx) {
+ delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
+ },
+ clearXhr: function(id, chunkIdx) {
+ var tempState = handler._getFileState(id).temp;
+ if (tempState.xhrs) {
+ delete tempState.xhrs[chunkIdx];
+ }
+ if (tempState.ajaxRequesters) {
+ delete tempState.ajaxRequesters[chunkIdx];
+ }
+ },
+ finalizeChunks: function(id, responseParser) {
+ var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx);
+ if (responseParser) {
+ return new qq.Promise().success(responseParser(xhr), xhr);
+ }
+ return new qq.Promise().success({}, xhr);
+ },
+ getFile: function(id) {
+ return handler.isValid(id) && handler._getFileState(id).file;
+ },
+ getProxy: function(id) {
+ return handler.isValid(id) && handler._getFileState(id).proxy;
+ },
+ getResumableFilesData: function() {
+ var resumableFilesData = [];
+ handler._iterateResumeRecords(function(key, uploadData) {
+ handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
+ var data = {
+ name: uploadData.name,
+ remaining: uploadData.chunking.remaining,
+ size: uploadData.size,
+ uuid: uploadData.uuid
+ };
+ if (uploadData.key) {
+ data.key = uploadData.key;
+ }
+ resumableFilesData.push(data);
+ });
+ return resumableFilesData;
+ },
+ isResumable: function(id) {
+ return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
+ },
+ moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
+ var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining;
+ if (inProgress) {
+ log(qq.format("Moving these chunks from in-progress {}, to remaining.", JSON.stringify(inProgress)));
+ inProgress.reverse();
+ qq.each(inProgress, function(idx, chunkIdx) {
+ remaining.unshift(chunkIdx);
+ });
+ inProgress.length = 0;
+ }
+ },
+ pause: function(id) {
+ if (handler.isValid(id)) {
+ log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
+ handler._getFileState(id).paused = true;
+ abort(id);
+ return true;
+ }
+ },
+ reevaluateChunking: function(id) {
+ if (chunking && handler.isValid(id)) {
+ var state = handler._getFileState(id), totalChunks, i;
+ delete state.chunking;
+ state.chunking = {};
+ totalChunks = handler._getTotalChunks(id);
+ if (totalChunks > 1 || chunking.mandatory) {
+ state.chunking.enabled = true;
+ state.chunking.parts = totalChunks;
+ state.chunking.remaining = [];
+ for (i = 0; i < totalChunks; i++) {
+ state.chunking.remaining.push(i);
+ }
+ handler._initTempState(id);
+ } else {
+ state.chunking.enabled = false;
+ }
+ }
+ },
+ updateBlob: function(id, newBlob) {
+ if (handler.isValid(id)) {
+ handler._getFileState(id).file = newBlob;
+ }
+ },
+ _clearXhrs: function(id) {
+ var tempState = handler._getFileState(id).temp;
+ qq.each(tempState.ajaxRequesters, function(chunkId) {
+ delete tempState.ajaxRequesters[chunkId];
+ });
+ qq.each(tempState.xhrs, function(chunkId) {
+ delete tempState.xhrs[chunkId];
+ });
+ },
+ _createXhr: function(id, optChunkIdx) {
+ return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
+ },
+ _getAjaxRequester: function(id, optChunkIdx) {
+ var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
+ return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
+ },
+ _getChunkData: function(id, chunkIndex) {
+ var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
+ cachedChunks[chunkIndex] = blob;
+ return {
+ part: chunkIndex,
+ start: startBytes,
+ end: endBytes,
+ count: totalChunks,
+ blob: blob,
+ size: endBytes - startBytes
+ };
+ },
+ _getChunkDataForCallback: function(chunkData) {
+ return {
+ partIndex: chunkData.part,
+ startByte: chunkData.start + 1,
+ endByte: chunkData.end,
+ totalParts: chunkData.count
+ };
+ },
+ _getLocalStorageId: function(id) {
+ var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id);
+ return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
+ },
+ _getMimeType: function(id) {
+ return handler.getFile(id).type;
+ },
+ _getPersistableData: function(id) {
+ return handler._getFileState(id).chunking;
+ },
+ _getTotalChunks: function(id) {
+ if (chunking) {
+ var fileSize = getSize(id), chunkSize = chunking.partSize;
+ return Math.ceil(fileSize / chunkSize);
+ }
+ },
+ _getXhr: function(id, optChunkIdx) {
+ var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
+ return handler._getFileState(id).temp.xhrs[chunkIdx];
+ },
+ _getXhrs: function(id) {
+ return handler._getFileState(id).temp.xhrs;
+ },
+ _iterateResumeRecords: function(callback) {
+ if (resumeEnabled) {
+ qq.each(localStorage, function(key, item) {
+ if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
+ var uploadData = JSON.parse(item);
+ callback(key, uploadData);
+ }
+ });
+ }
+ },
+ _initTempState: function(id) {
+ handler._getFileState(id).temp = {
+ ajaxRequesters: {},
+ chunkProgress: {},
+ xhrs: {},
+ cachedChunks: {}
+ };
+ },
+ _markNotResumable: function(id) {
+ handler._getFileState(id).notResumable = true;
+ },
+ _maybeDeletePersistedChunkData: function(id) {
+ var localStorageId;
+ if (resumeEnabled && handler.isResumable(id)) {
+ localStorageId = handler._getLocalStorageId(id);
+ if (localStorageId && localStorage.getItem(localStorageId)) {
+ localStorage.removeItem(localStorageId);
+ return true;
+ }
+ }
+ return false;
+ },
+ _maybePrepareForResume: function(id) {
+ var state = handler._getFileState(id), localStorageId, persistedData;
+ if (resumeEnabled && state.key === undefined) {
+ localStorageId = handler._getLocalStorageId(id);
+ persistedData = localStorage.getItem(localStorageId);
+ if (persistedData) {
+ persistedData = JSON.parse(persistedData);
+ if (getDataByUuid(persistedData.uuid)) {
+ handler._markNotResumable(id);
+ } else {
+ log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
+ onUuidChanged(id, persistedData.uuid);
+ state.key = persistedData.key;
+ state.chunking = persistedData.chunking;
+ state.loaded = persistedData.loaded;
+ state.attemptingResume = true;
+ handler.moveInProgressToRemaining(id);
+ }
+ }
+ }
+ },
+ _maybePersistChunkedState: function(id) {
+ var state = handler._getFileState(id), localStorageId, persistedData;
+ if (resumeEnabled && handler.isResumable(id)) {
+ localStorageId = handler._getLocalStorageId(id);
+ persistedData = {
+ name: getName(id),
+ size: getSize(id),
+ uuid: getUuid(id),
+ key: state.key,
+ chunking: state.chunking,
+ loaded: state.loaded,
+ lastUpdated: Date.now()
+ };
+ try {
+ localStorage.setItem(localStorageId, JSON.stringify(persistedData));
+ } catch (error) {
+ log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn");
+ }
+ }
+ },
+ _registerProgressHandler: function(id, chunkIdx, chunkSize) {
+ var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = {
+ simple: function(loaded, total) {
+ var fileSize = getSize(id);
+ if (loaded === total) {
+ onProgress(id, name, fileSize, fileSize);
+ } else {
+ onProgress(id, name, loaded >= fileSize ? fileSize - 1 : loaded, fileSize);
+ }
+ },
+ chunked: function(loaded, total) {
+ var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile;
+ chunkProgress[chunkIdx] = estActualChunkLoaded;
+ qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
+ totalLoadedForFile += chunkLoaded;
+ });
+ onProgress(id, name, totalLoadedForFile, totalFileSize);
+ }
+ };
+ xhr.upload.onprogress = function(e) {
+ if (e.lengthComputable) {
+ var type = chunkSize == null ? "simple" : "chunked";
+ progressCalculator[type](e.loaded, e.total);
+ }
+ };
+ },
+ _registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
+ var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp;
+ tempState.xhrs = tempState.xhrs || {};
+ tempState.ajaxRequesters = tempState.ajaxRequesters || {};
+ tempState.xhrs[xhrsId] = xhr;
+ if (optAjaxRequester) {
+ tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
+ }
+ return xhr;
+ },
+ _removeExpiredChunkingRecords: function() {
+ var expirationDays = resume.recordsExpireIn;
+ handler._iterateResumeRecords(function(key, uploadData) {
+ var expirationDate = new Date(uploadData.lastUpdated);
+ expirationDate.setDate(expirationDate.getDate() + expirationDays);
+ if (expirationDate.getTime() <= Date.now()) {
+ log("Removing expired resume record with key " + key);
+ localStorage.removeItem(key);
+ }
+ });
+ },
+ _shouldChunkThisFile: function(id) {
+ var state = handler._getFileState(id);
+ if (!state.chunking) {
+ handler.reevaluateChunking(id);
+ }
+ return state.chunking.enabled;
+ }
+ });
+ };
+ qq.DeleteFileAjaxRequester = function(o) {
+ "use strict";
+ var requester, options = {
+ method: "DELETE",
+ uuidParamName: "qquuid",
+ endpointStore: {},
+ maxConnections: 3,
+ customHeaders: function(id) {
+ return {};
+ },
+ paramsStore: {},
+ cors: {
+ expected: false,
+ sendCredentials: false
+ },
+ log: function(str, level) {},
+ onDelete: function(id) {},
+ onDeleteComplete: function(id, xhrOrXdr, isError) {}
+ };
+ qq.extend(options, o);
+ function getMandatedParams() {
+ if (options.method.toUpperCase() === "POST") {
+ return {
+ _method: "DELETE"
+ };
+ }
+ return {};
+ }
+ requester = qq.extend(this, new qq.AjaxRequester({
+ acceptHeader: "application/json",
+ validMethods: [ "POST", "DELETE" ],
+ method: options.method,
+ endpointStore: options.endpointStore,
+ paramsStore: options.paramsStore,
+ mandatedParams: getMandatedParams(),
+ maxConnections: options.maxConnections,
+ customHeaders: function(id) {
+ return options.customHeaders.get(id);
+ },
+ log: options.log,
+ onSend: options.onDelete,
+ onComplete: options.onDeleteComplete,
+ cors: options.cors
+ }));
+ qq.extend(this, {
+ sendDelete: function(id, uuid, additionalMandatedParams) {
+ var additionalOptions = additionalMandatedParams || {};
+ options.log("Submitting delete file request for " + id);
+ if (options.method === "DELETE") {
+ requester.initTransport(id).withPath(uuid).withParams(additionalOptions).send();
+ } else {
+ additionalOptions[options.uuidParamName] = uuid;
+ requester.initTransport(id).withParams(additionalOptions).send();
+ }
+ }
+ });
+ };
+ (function() {
+ function detectSubsampling(img) {
+ var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx;
+ if (iw * ih > 1024 * 1024) {
+ canvas.width = canvas.height = 1;
+ ctx = canvas.getContext("2d");
+ ctx.drawImage(img, -iw + 1, 0);
+ return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
+ } else {
+ return false;
+ }
+ }
+ function detectVerticalSquash(img, iw, ih) {
+ var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio;
+ canvas.width = 1;
+ canvas.height = ih;
+ ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
+ data = ctx.getImageData(0, 0, 1, ih).data;
+ while (py > sy) {
+ alpha = data[(py - 1) * 4 + 3];
+ if (alpha === 0) {
+ ey = py;
+ } else {
+ sy = py;
+ }
+ py = ey + sy >> 1;
+ }
+ ratio = py / ih;
+ return ratio === 0 ? 1 : ratio;
+ }
+ function renderImageToDataURL(img, blob, options, doSquash) {
+ var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg", promise = new qq.Promise();
+ renderImageToCanvas(img, blob, canvas, options, doSquash).then(function() {
+ promise.success(canvas.toDataURL(mime, options.quality || .8));
+ });
+ return promise;
+ }
+ function maybeCalculateDownsampledDimensions(spec) {
+ var maxPixels = 5241e3;
+ if (!qq.ios()) {
+ throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
+ }
+ if (spec.origHeight * spec.origWidth > maxPixels) {
+ return {
+ newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
+ newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
+ };
+ }
+ }
+ function renderImageToCanvas(img, blob, canvas, options, doSquash) {
+ var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), promise = new qq.Promise(), modifiedDimensions;
+ ctx.save();
+ if (options.resize) {
+ return renderImageToCanvasWithCustomResizer({
+ blob: blob,
+ canvas: canvas,
+ image: img,
+ imageHeight: ih,
+ imageWidth: iw,
+ orientation: options.orientation,
+ resize: options.resize,
+ targetHeight: height,
+ targetWidth: width
+ });
+ }
+ if (!qq.supportedFeatures.unlimitedScaledImageSize) {
+ modifiedDimensions = maybeCalculateDownsampledDimensions({
+ origWidth: width,
+ origHeight: height
+ });
+ if (modifiedDimensions) {
+ qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn");
+ width = modifiedDimensions.newWidth;
+ height = modifiedDimensions.newHeight;
+ }
+ }
+ transformCoordinate(canvas, width, height, options.orientation);
+ if (qq.ios()) {
+ (function() {
+ if (detectSubsampling(img)) {
+ iw /= 2;
+ ih /= 2;
+ }
+ var d = 1024, tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx;
+ tmpCanvas.width = tmpCanvas.height = d;
+ tmpCtx = tmpCanvas.getContext("2d");
+ while (sy < ih) {
+ sx = 0;
+ dx = 0;
+ while (sx < iw) {
+ tmpCtx.clearRect(0, 0, d, d);
+ tmpCtx.drawImage(img, -sx, -sy);
+ ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
+ sx += d;
+ dx += dw;
+ }
+ sy += d;
+ dy += dh;
+ }
+ ctx.restore();
+ tmpCanvas = tmpCtx = null;
+ })();
+ } else {
+ ctx.drawImage(img, 0, 0, width, height);
+ }
+ canvas.qqImageRendered && canvas.qqImageRendered();
+ promise.success();
+ return promise;
+ }
+ function renderImageToCanvasWithCustomResizer(resizeInfo) {
+ var blob = resizeInfo.blob, image = resizeInfo.image, imageHeight = resizeInfo.imageHeight, imageWidth = resizeInfo.imageWidth, orientation = resizeInfo.orientation, promise = new qq.Promise(), resize = resizeInfo.resize, sourceCanvas = document.createElement("canvas"), sourceCanvasContext = sourceCanvas.getContext("2d"), targetCanvas = resizeInfo.canvas, targetHeight = resizeInfo.targetHeight, targetWidth = resizeInfo.targetWidth;
+ transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation);
+ targetCanvas.height = targetHeight;
+ targetCanvas.width = targetWidth;
+ sourceCanvasContext.drawImage(image, 0, 0);
+ resize({
+ blob: blob,
+ height: targetHeight,
+ image: image,
+ sourceCanvas: sourceCanvas,
+ targetCanvas: targetCanvas,
+ width: targetWidth
+ }).then(function success() {
+ targetCanvas.qqImageRendered && targetCanvas.qqImageRendered();
+ promise.success();
+ }, promise.failure);
+ return promise;
+ }
+ function transformCoordinate(canvas, width, height, orientation) {
+ switch (orientation) {
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ canvas.width = height;
+ canvas.height = width;
+ break;
+
+ default:
+ canvas.width = width;
+ canvas.height = height;
+ }
+ var ctx = canvas.getContext("2d");
+ switch (orientation) {
+ case 2:
+ ctx.translate(width, 0);
+ ctx.scale(-1, 1);
+ break;
+
+ case 3:
+ ctx.translate(width, height);
+ ctx.rotate(Math.PI);
+ break;
+
+ case 4:
+ ctx.translate(0, height);
+ ctx.scale(1, -1);
+ break;
+
+ case 5:
+ ctx.rotate(.5 * Math.PI);
+ ctx.scale(1, -1);
+ break;
+
+ case 6:
+ ctx.rotate(.5 * Math.PI);
+ ctx.translate(0, -height);
+ break;
+
+ case 7:
+ ctx.rotate(.5 * Math.PI);
+ ctx.translate(width, -height);
+ ctx.scale(-1, 1);
+ break;
+
+ case 8:
+ ctx.rotate(-.5 * Math.PI);
+ ctx.translate(-width, 0);
+ break;
+
+ default:
+ break;
+ }
+ }
+ function MegaPixImage(srcImage, errorCallback) {
+ var self = this;
+ if (window.Blob && srcImage instanceof Blob) {
+ (function() {
+ var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
+ if (!URL) {
+ throw Error("No createObjectURL function found to create blob url");
+ }
+ img.src = URL.createObjectURL(srcImage);
+ self.blob = srcImage;
+ srcImage = img;
+ })();
+ }
+ if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
+ srcImage.onload = function() {
+ var listeners = self.imageLoadListeners;
+ if (listeners) {
+ self.imageLoadListeners = null;
+ setTimeout(function() {
+ for (var i = 0, len = listeners.length; i < len; i++) {
+ listeners[i]();
+ }
+ }, 0);
+ }
+ };
+ srcImage.onerror = errorCallback;
+ this.imageLoadListeners = [];
+ }
+ this.srcImage = srcImage;
+ }
+ MegaPixImage.prototype.render = function(target, options) {
+ options = options || {};
+ var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt;
+ if (this.imageLoadListeners) {
+ this.imageLoadListeners.push(function() {
+ self.render(target, options);
+ });
+ return;
+ }
+ if (width && !height) {
+ height = imgHeight * width / imgWidth << 0;
+ } else if (height && !width) {
+ width = imgWidth * height / imgHeight << 0;
+ } else {
+ width = imgWidth;
+ height = imgHeight;
+ }
+ if (maxWidth && width > maxWidth) {
+ width = maxWidth;
+ height = imgHeight * width / imgWidth << 0;
+ }
+ if (maxHeight && height > maxHeight) {
+ height = maxHeight;
+ width = imgWidth * height / imgHeight << 0;
+ }
+ opt = {
+ width: width,
+ height: height
+ }, qq.each(options, function(optionsKey, optionsValue) {
+ opt[optionsKey] = optionsValue;
+ });
+ if (tagName === "img") {
+ (function() {
+ var oldTargetSrc = target.src;
+ renderImageToDataURL(self.srcImage, self.blob, opt, doSquash).then(function(dataUri) {
+ target.src = dataUri;
+ oldTargetSrc === target.src && target.onload();
+ });
+ })();
+ } else if (tagName === "canvas") {
+ renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash);
+ }
+ if (typeof this.onrender === "function") {
+ this.onrender(target);
+ }
+ };
+ qq.MegaPixImage = MegaPixImage;
+ })();
+ qq.ImageGenerator = function(log) {
+ "use strict";
+ function isImg(el) {
+ return el.tagName.toLowerCase() === "img";
+ }
+ function isCanvas(el) {
+ return el.tagName.toLowerCase() === "canvas";
+ }
+ function isImgCorsSupported() {
+ return new Image().crossOrigin !== undefined;
+ }
+ function isCanvasSupported() {
+ var canvas = document.createElement("canvas");
+ return canvas.getContext && canvas.getContext("2d");
+ }
+ function determineMimeOfFileName(nameWithPath) {
+ var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1].split("?")[0], extension = qq.getExtension(name);
+ extension = extension && extension.toLowerCase();
+ switch (extension) {
+ case "jpeg":
+ case "jpg":
+ return "image/jpeg";
+
+ case "png":
+ return "image/png";
+
+ case "bmp":
+ return "image/bmp";
+
+ case "gif":
+ return "image/gif";
+
+ case "tiff":
+ case "tif":
+ return "image/tiff";
+ }
+ }
+ function isCrossOrigin(url) {
+ var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort;
+ targetAnchor.href = url;
+ targetProtocol = targetAnchor.protocol;
+ targetPort = targetAnchor.port;
+ targetHostname = targetAnchor.hostname;
+ if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
+ return true;
+ }
+ if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
+ return true;
+ }
+ if (targetPort !== window.location.port && !qq.ie()) {
+ return true;
+ }
+ return false;
+ }
+ function registerImgLoadListeners(img, promise) {
+ img.onload = function() {
+ img.onload = null;
+ img.onerror = null;
+ promise.success(img);
+ };
+ img.onerror = function() {
+ img.onload = null;
+ img.onerror = null;
+ log("Problem drawing thumbnail!", "error");
+ promise.failure(img, "Problem drawing thumbnail!");
+ };
+ }
+ function registerCanvasDrawImageListener(canvas, promise) {
+ canvas.qqImageRendered = function() {
+ promise.success(canvas);
+ };
+ }
+ function registerThumbnailRenderedListener(imgOrCanvas, promise) {
+ var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
+ if (isImg(imgOrCanvas)) {
+ registerImgLoadListeners(imgOrCanvas, promise);
+ } else if (isCanvas(imgOrCanvas)) {
+ registerCanvasDrawImageListener(imgOrCanvas, promise);
+ } else {
+ promise.failure(imgOrCanvas);
+ log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
+ }
+ return registered;
+ }
+ function draw(fileOrBlob, container, options) {
+ var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() {
+ container.onerror = null;
+ container.onload = null;
+ log("Could not render preview, file may be too large!", "error");
+ drawPreview.failure(container, "Browser cannot render image!");
+ };
+ identifier.isPreviewable().then(function(mime) {
+ var dummyExif = {
+ parse: function() {
+ return new qq.Promise().success();
+ }
+ }, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
+ if (registerThumbnailRenderedListener(container, drawPreview)) {
+ exif.parse().then(function(exif) {
+ var orientation = exif && exif.Orientation;
+ mpImg.render(container, {
+ maxWidth: maxSize,
+ maxHeight: maxSize,
+ orientation: orientation,
+ mime: mime,
+ resize: options.customResizeFunction
+ });
+ }, function(failureMsg) {
+ log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
+ mpImg.render(container, {
+ maxWidth: maxSize,
+ maxHeight: maxSize,
+ mime: mime,
+ resize: options.customResizeFunction
+ });
+ });
+ }
+ }, function() {
+ log("Not previewable");
+ drawPreview.failure(container, "Not previewable");
+ });
+ return drawPreview;
+ }
+ function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) {
+ var tempImg = new Image(), tempImgRender = new qq.Promise();
+ registerThumbnailRenderedListener(tempImg, tempImgRender);
+ if (isCrossOrigin(url)) {
+ tempImg.crossOrigin = "anonymous";
+ }
+ tempImg.src = url;
+ tempImgRender.then(function rendered() {
+ registerThumbnailRenderedListener(canvasOrImg, draw);
+ var mpImg = new qq.MegaPixImage(tempImg);
+ mpImg.render(canvasOrImg, {
+ maxWidth: maxSize,
+ maxHeight: maxSize,
+ mime: determineMimeOfFileName(url),
+ resize: customResizeFunction
+ });
+ }, draw.failure);
+ }
+ function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
+ registerThumbnailRenderedListener(img, draw);
+ qq(img).css({
+ maxWidth: maxSize + "px",
+ maxHeight: maxSize + "px"
+ });
+ img.src = url;
+ }
+ function drawFromUrl(url, container, options) {
+ var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null;
+ if (scale && isImg(container)) {
+ if (isCanvasSupported()) {
+ if (isCrossOrigin(url) && !isImgCorsSupported()) {
+ drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
+ } else {
+ drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
+ }
+ } else {
+ drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
+ }
+ } else if (isCanvas(container)) {
+ drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
+ } else if (registerThumbnailRenderedListener(container, draw)) {
+ container.src = url;
+ }
+ return draw;
+ }
+ qq.extend(this, {
+ generate: function(fileBlobOrUrl, container, options) {
+ if (qq.isString(fileBlobOrUrl)) {
+ log("Attempting to update thumbnail based on server response.");
+ return drawFromUrl(fileBlobOrUrl, container, options || {});
+ } else {
+ log("Attempting to draw client-side image preview.");
+ return draw(fileBlobOrUrl, container, options || {});
+ }
+ }
+ });
+ this._testing = {};
+ this._testing.isImg = isImg;
+ this._testing.isCanvas = isCanvas;
+ this._testing.isCrossOrigin = isCrossOrigin;
+ this._testing.determineMimeOfFileName = determineMimeOfFileName;
+ };
+ qq.Exif = function(fileOrBlob, log) {
+ "use strict";
+ var TAG_IDS = [ 274 ], TAG_INFO = {
+ 274: {
+ name: "Orientation",
+ bytes: 2
+ }
+ };
+ function parseLittleEndian(hex) {
+ var result = 0, pow = 0;
+ while (hex.length > 0) {
+ result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
+ hex = hex.substring(2, hex.length);
+ pow += 8;
+ }
+ return result;
+ }
+ function seekToApp1(offset, promise) {
+ var theOffset = offset, thePromise = promise;
+ if (theOffset === undefined) {
+ theOffset = 2;
+ thePromise = new qq.Promise();
+ }
+ qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
+ var match = /^ffe([0-9])/.exec(hex), segmentLength;
+ if (match) {
+ if (match[1] !== "1") {
+ segmentLength = parseInt(hex.slice(4, 8), 16);
+ seekToApp1(theOffset + segmentLength + 2, thePromise);
+ } else {
+ thePromise.success(theOffset);
+ }
+ } else {
+ thePromise.failure("No EXIF header to be found!");
+ }
+ });
+ return thePromise;
+ }
+ function getApp1Offset() {
+ var promise = new qq.Promise();
+ qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
+ if (hex.indexOf("ffd8") !== 0) {
+ promise.failure("Not a valid JPEG!");
+ } else {
+ seekToApp1().then(function(offset) {
+ promise.success(offset);
+ }, function(error) {
+ promise.failure(error);
+ });
+ }
+ });
+ return promise;
+ }
+ function isLittleEndian(app1Start) {
+ var promise = new qq.Promise();
+ qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
+ promise.success(hex === "4949");
+ });
+ return promise;
+ }
+ function getDirEntryCount(app1Start, littleEndian) {
+ var promise = new qq.Promise();
+ qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
+ if (littleEndian) {
+ return promise.success(parseLittleEndian(hex));
+ } else {
+ promise.success(parseInt(hex, 16));
+ }
+ });
+ return promise;
+ }
+ function getIfd(app1Start, dirEntries) {
+ var offset = app1Start + 20, bytes = dirEntries * 12;
+ return qq.readBlobToHex(fileOrBlob, offset, bytes);
+ }
+ function getDirEntries(ifdHex) {
+ var entries = [], offset = 0;
+ while (offset + 24 <= ifdHex.length) {
+ entries.push(ifdHex.slice(offset, offset + 24));
+ offset += 24;
+ }
+ return entries;
+ }
+ function getTagValues(littleEndian, dirEntries) {
+ var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {};
+ qq.each(dirEntries, function(idx, entry) {
+ var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength;
+ if (tagsToFindIdx >= 0) {
+ tagName = TAG_INFO[id].name;
+ tagValLength = TAG_INFO[id].bytes;
+ tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + tagValLength * 2);
+ vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
+ tagsToFind.splice(tagsToFindIdx, 1);
+ }
+ if (tagsToFind.length === 0) {
+ return false;
+ }
+ });
+ return vals;
+ }
+ qq.extend(this, {
+ parse: function() {
+ var parser = new qq.Promise(), onParseFailure = function(message) {
+ log(qq.format("EXIF header parse failed: '{}' ", message));
+ parser.failure(message);
+ };
+ getApp1Offset().then(function(app1Offset) {
+ log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
+ isLittleEndian(app1Offset).then(function(littleEndian) {
+ log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
+ getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
+ log(qq.format("Found {} APP1 directory entries", dirEntryCount));
+ getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
+ var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries);
+ log("Successfully parsed some EXIF tags");
+ parser.success(tagValues);
+ }, onParseFailure);
+ }, onParseFailure);
+ }, onParseFailure);
+ }, onParseFailure);
+ return parser;
+ }
+ });
+ this._testing = {};
+ this._testing.parseLittleEndian = parseLittleEndian;
+ };
+ qq.Identify = function(fileOrBlob, log) {
+ "use strict";
+ function isIdentifiable(magicBytes, questionableBytes) {
+ var identifiable = false, magicBytesEntries = [].concat(magicBytes);
+ qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
+ if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
+ identifiable = true;
+ return false;
+ }
+ });
+ return identifiable;
+ }
+ qq.extend(this, {
+ isPreviewable: function() {
+ var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
+ log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
+ log("First pass: check type attribute of blob object.");
+ if (this.isPreviewableSync()) {
+ log("Second pass: check for magic bytes in file header.");
+ qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
+ qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
+ if (isIdentifiable(bytes, hex)) {
+ if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
+ previewable = true;
+ identifier.success(mime);
+ }
+ return false;
+ }
+ });
+ log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
+ if (!previewable) {
+ identifier.failure();
+ }
+ }, function() {
+ log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
+ identifier.failure();
+ });
+ } else {
+ identifier.failure();
+ }
+ return identifier;
+ },
+ isPreviewableSync: function() {
+ var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
+ if (isRecognizedImage) {
+ if (fileMime === "image/tiff") {
+ previewable = qq.supportedFeatures.tiffPreviews;
+ } else {
+ previewable = true;
+ }
+ }
+ !previewable && log(name + " is not previewable in this browser per the blob's type attr");
+ return previewable;
+ }
+ });
+ };
+ qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
+ "image/jpeg": "ffd8ff",
+ "image/gif": "474946",
+ "image/png": "89504e",
+ "image/bmp": "424d",
+ "image/tiff": [ "49492a00", "4d4d002a" ]
+ };
+ qq.ImageValidation = function(blob, log) {
+ "use strict";
+ function hasNonZeroLimits(limits) {
+ var atLeastOne = false;
+ qq.each(limits, function(limit, value) {
+ if (value > 0) {
+ atLeastOne = true;
+ return false;
+ }
+ });
+ return atLeastOne;
+ }
+ function getWidthHeight() {
+ var sizeDetermination = new qq.Promise();
+ new qq.Identify(blob, log).isPreviewable().then(function() {
+ var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
+ if (url) {
+ image.onerror = function() {
+ log("Cannot determine dimensions for image. May be too large.", "error");
+ sizeDetermination.failure();
+ };
+ image.onload = function() {
+ sizeDetermination.success({
+ width: this.width,
+ height: this.height
+ });
+ };
+ image.src = url.createObjectURL(blob);
+ } else {
+ log("No createObjectURL function available to generate image URL!", "error");
+ sizeDetermination.failure();
+ }
+ }, sizeDetermination.failure);
+ return sizeDetermination;
+ }
+ function getFailingLimit(limits, dimensions) {
+ var failingLimit;
+ qq.each(limits, function(limitName, limitValue) {
+ if (limitValue > 0) {
+ var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName];
+ switch (limitMatcher[1]) {
+ case "min":
+ if (actualValue < limitValue) {
+ failingLimit = limitName;
+ return false;
+ }
+ break;
+
+ case "max":
+ if (actualValue > limitValue) {
+ failingLimit = limitName;
+ return false;
+ }
+ break;
+ }
+ }
+ });
+ return failingLimit;
+ }
+ this.validate = function(limits) {
+ var validationEffort = new qq.Promise();
+ log("Attempting to validate image.");
+ if (hasNonZeroLimits(limits)) {
+ getWidthHeight().then(function(dimensions) {
+ var failingLimit = getFailingLimit(limits, dimensions);
+ if (failingLimit) {
+ validationEffort.failure(failingLimit);
+ } else {
+ validationEffort.success();
+ }
+ }, validationEffort.success);
+ } else {
+ validationEffort.success();
+ }
+ return validationEffort;
+ };
+ };
+ qq.Session = function(spec) {
+ "use strict";
+ var options = {
+ endpoint: null,
+ params: {},
+ customHeaders: {},
+ cors: {},
+ addFileRecord: function(sessionData) {},
+ log: function(message, level) {}
+ };
+ qq.extend(options, spec, true);
+ function isJsonResponseValid(response) {
+ if (qq.isArray(response)) {
+ return true;
+ }
+ options.log("Session response is not an array.", "error");
+ }
+ function handleFileItems(fileItems, success, xhrOrXdr, promise) {
+ var someItemsIgnored = false;
+ success = success && isJsonResponseValid(fileItems);
+ if (success) {
+ qq.each(fileItems, function(idx, fileItem) {
+ if (fileItem.uuid == null) {
+ someItemsIgnored = true;
+ options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
+ } else if (fileItem.name == null) {
+ someItemsIgnored = true;
+ options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
+ } else {
+ try {
+ options.addFileRecord(fileItem);
+ return true;
+ } catch (err) {
+ someItemsIgnored = true;
+ options.log(err.message, "error");
+ }
+ }
+ return false;
+ });
+ }
+ promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
+ }
+ this.refresh = function() {
+ var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) {
+ handleFileItems(response, success, xhrOrXdr, refreshEffort);
+ }, requesterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester(qq.extend(requesterOptions, {
+ onComplete: refreshCompleteCallback
+ }));
+ requester.queryServer();
+ return refreshEffort;
+ };
+ };
+ qq.SessionAjaxRequester = function(spec) {
+ "use strict";
+ var requester, options = {
+ endpoint: null,
+ customHeaders: {},
+ params: {},
+ cors: {
+ expected: false,
+ sendCredentials: false
+ },
+ onComplete: function(response, success, xhrOrXdr) {},
+ log: function(str, level) {}
+ };
+ qq.extend(options, spec);
+ function onComplete(id, xhrOrXdr, isError) {
+ var response = null;
+ if (xhrOrXdr.responseText != null) {
+ try {
+ response = qq.parseJson(xhrOrXdr.responseText);
+ } catch (err) {
+ options.log("Problem parsing session response: " + err.message, "error");
+ isError = true;
+ }
+ }
+ options.onComplete(response, !isError, xhrOrXdr);
+ }
+ requester = qq.extend(this, new qq.AjaxRequester({
+ acceptHeader: "application/json",
+ validMethods: [ "GET" ],
+ method: "GET",
+ endpointStore: {
+ get: function() {
+ return options.endpoint;
+ }
+ },
+ customHeaders: options.customHeaders,
+ log: options.log,
+ onComplete: onComplete,
+ cors: options.cors
+ }));
+ qq.extend(this, {
+ queryServer: function() {
+ var params = qq.extend({}, options.params);
+ options.log("Session query request.");
+ requester.initTransport("sessionRefresh").withParams(params).withCacheBuster().send();
+ }
+ });
+ };
+ qq.Scaler = function(spec, log) {
+ "use strict";
+ var self = this, customResizeFunction = spec.customResizer, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes);
+ qq.extend(this, {
+ enabled: qq.supportedFeatures.scaling && sizes.length > 0,
+ getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
+ var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, identifier = new qq.Identify(originalBlob, log);
+ if (identifier.isPreviewableSync()) {
+ qq.each(sizes, function(idx, sizeRecord) {
+ var outputType = self._determineOutputType({
+ defaultType: defaultType,
+ requestedType: sizeRecord.type,
+ refType: originalBlob.type
+ });
+ records.push({
+ uuid: qq.getUniqueId(),
+ name: self._getName(originalFileName, {
+ name: sizeRecord.name,
+ type: outputType,
+ refType: originalBlob.type
+ }),
+ blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, {
+ customResizeFunction: customResizeFunction,
+ maxSize: sizeRecord.maxSize,
+ orient: orient,
+ type: outputType,
+ quality: defaultQuality,
+ failedText: failedToScaleText,
+ includeExif: includeExif,
+ log: log
+ }))
+ });
+ });
+ records.push({
+ uuid: originalFileUuid,
+ name: originalFileName,
+ size: originalBlob.size,
+ blob: includeOriginal ? originalBlob : null
+ });
+ } else {
+ records.push({
+ uuid: originalFileUuid,
+ name: originalFileName,
+ size: originalBlob.size,
+ blob: originalBlob
+ });
+ }
+ return records;
+ },
+ handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
+ var self = this, buttonId = file.qqButtonId || file.blob && file.blob.qqButtonId, scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId();
+ qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
+ var blobSize = record.size, id;
+ if (record.blob instanceof qq.BlobProxy) {
+ blobSize = -1;
+ }
+ id = uploadData.addFile({
+ uuid: record.uuid,
+ name: record.name,
+ size: blobSize,
+ batchId: batchId,
+ proxyGroupId: proxyGroupId
+ });
+ if (record.blob instanceof qq.BlobProxy) {
+ scaledIds.push(id);
+ } else {
+ originalId = id;
+ }
+ if (record.blob) {
+ addFileToHandler(id, record.blob);
+ fileList.push({
+ id: id,
+ file: record.blob
+ });
+ } else {
+ uploadData.setStatus(id, qq.status.REJECTED);
+ }
+ });
+ if (originalId !== null) {
+ qq.each(scaledIds, function(idx, scaledId) {
+ var params = {
+ qqparentuuid: uploadData.retrieve({
+ id: originalId
+ }).uuid,
+ qqparentsize: uploadData.retrieve({
+ id: originalId
+ }).size
+ };
+ params[uuidParamName] = uploadData.retrieve({
+ id: scaledId
+ }).uuid;
+ uploadData.setParentId(scaledId, originalId);
+ paramsStore.addReadOnly(scaledId, params);
+ });
+ if (scaledIds.length) {
+ (function() {
+ var param = {};
+ param[uuidParamName] = uploadData.retrieve({
+ id: originalId
+ }).uuid;
+ paramsStore.addReadOnly(originalId, param);
+ })();
+ }
+ }
+ }
+ });
+ };
+ qq.extend(qq.Scaler.prototype, {
+ scaleImage: function(id, specs, api) {
+ "use strict";
+ if (!qq.supportedFeatures.scaling) {
+ throw new qq.Error("Scaling is not supported in this browser!");
+ }
+ var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({
+ id: id
+ }), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = {
+ customResizer: specs.customResizer,
+ sendOriginal: false,
+ orient: specs.orient,
+ defaultType: specs.type || null,
+ defaultQuality: specs.quality,
+ failedToScaleText: "Unable to scale",
+ sizes: [ {
+ name: "",
+ maxSize: specs.maxSize
+ } ]
+ }, scaler = new qq.Scaler(scalingOptions, log);
+ if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
+ scalingEffort.failure();
+ log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error");
+ } else {
+ qq.bind(function() {
+ var record = scaler.getFileRecords(uuid, name, file)[0];
+ if (record && record.blob instanceof qq.BlobProxy) {
+ record.blob.create().then(scalingEffort.success, scalingEffort.failure);
+ } else {
+ log(id + " is not a scalable image!", "error");
+ scalingEffort.failure();
+ }
+ }, this)();
+ }
+ return scalingEffort;
+ },
+ _determineOutputType: function(spec) {
+ "use strict";
+ var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType;
+ if (!defaultType && !requestedType) {
+ if (referenceType !== "image/jpeg") {
+ return "image/png";
+ }
+ return referenceType;
+ }
+ if (!requestedType) {
+ return defaultType;
+ }
+ if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
+ if (requestedType === "image/tiff") {
+ return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
+ }
+ return requestedType;
+ }
+ return defaultType;
+ },
+ _getName: function(originalName, scaledVersionProperties) {
+ "use strict";
+ var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = "";
+ if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
+ nameAppendage = " (" + scaledVersionProperties.name + ")";
+ }
+ if (startOfExt >= 0) {
+ scaledName = originalName.substr(0, startOfExt);
+ if (referenceType !== versionType) {
+ scaledExt = versionType.split("/")[1];
+ }
+ scaledName += nameAppendage + "." + scaledExt;
+ } else {
+ scaledName = originalName + nameAppendage;
+ }
+ return scaledName;
+ },
+ _getSortedSizes: function(sizes) {
+ "use strict";
+ sizes = qq.extend([], sizes);
+ return sizes.sort(function(a, b) {
+ if (a.maxSize > b.maxSize) {
+ return 1;
+ }
+ if (a.maxSize < b.maxSize) {
+ return -1;
+ }
+ return 0;
+ });
+ },
+ _generateScaledImage: function(spec, sourceFile) {
+ "use strict";
+ var self = this, customResizeFunction = spec.customResizeFunction, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas");
+ log("Attempting to generate scaled version for " + sourceFile.name);
+ imageGenerator.generate(sourceFile, canvas, {
+ maxSize: maxSize,
+ orient: orient,
+ customResizeFunction: customResizeFunction
+ }).then(function() {
+ var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() {
+ log("Success generating scaled version for " + sourceFile.name);
+ var blob = qq.dataUriToBlob(scaledImageDataUri);
+ scalingEffort.success(blob);
+ };
+ if (includeExif) {
+ self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
+ scaledImageDataUri = scaledImageDataUriWithExif;
+ signalSuccess();
+ }, function() {
+ log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
+ signalSuccess();
+ });
+ } else {
+ signalSuccess();
+ }
+ }, function() {
+ log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
+ scalingEffort.failure(failedText);
+ });
+ return scalingEffort;
+ },
+ _insertExifHeader: function(originalImage, scaledImageDataUri, log) {
+ "use strict";
+ var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = "";
+ reader.onload = function() {
+ originalImageDataUri = reader.result;
+ insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
+ };
+ reader.onerror = function() {
+ log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
+ insertionEffort.failure();
+ };
+ reader.readAsDataURL(originalImage);
+ return insertionEffort;
+ },
+ _dataUriToBlob: function(dataUri) {
+ "use strict";
+ var byteString, mimeString, arrayBuffer, intArray;
+ if (dataUri.split(",")[0].indexOf("base64") >= 0) {
+ byteString = atob(dataUri.split(",")[1]);
+ } else {
+ byteString = decodeURI(dataUri.split(",")[1]);
+ }
+ mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
+ arrayBuffer = new ArrayBuffer(byteString.length);
+ intArray = new Uint8Array(arrayBuffer);
+ qq.each(byteString, function(idx, character) {
+ intArray[idx] = character.charCodeAt(0);
+ });
+ return this._createBlob(arrayBuffer, mimeString);
+ },
+ _createBlob: function(data, mime) {
+ "use strict";
+ var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
+ if (blobBuilder) {
+ blobBuilder.append(data);
+ return blobBuilder.getBlob(mime);
+ } else {
+ return new Blob([ data ], {
+ type: mime
+ });
+ }
+ }
+ });
+ qq.ExifRestorer = function() {
+ var ExifRestorer = {};
+ ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
+ ExifRestorer.encode64 = function(input) {
+ var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0;
+ do {
+ chr1 = input[i++];
+ chr2 = input[i++];
+ chr3 = input[i++];
+ enc1 = chr1 >> 2;
+ enc2 = (chr1 & 3) << 4 | chr2 >> 4;
+ enc3 = (chr2 & 15) << 2 | chr3 >> 6;
+ enc4 = chr3 & 63;
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ } else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
+ output = output + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4);
+ chr1 = chr2 = chr3 = "";
+ enc1 = enc2 = enc3 = enc4 = "";
+ } while (i < input.length);
+ return output;
+ };
+ ExifRestorer.restore = function(origFileBase64, resizedFileBase64) {
+ var expectedBase64Header = "data:image/jpeg;base64,";
+ if (!origFileBase64.match(expectedBase64Header)) {
+ return resizedFileBase64;
+ }
+ var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
+ var segments = this.slice2Segments(rawImage);
+ var image = this.exifManipulation(resizedFileBase64, segments);
+ return expectedBase64Header + this.encode64(image);
+ };
+ ExifRestorer.exifManipulation = function(resizedFileBase64, segments) {
+ var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray);
+ return aBuffer;
+ };
+ ExifRestorer.getExifArray = function(segments) {
+ var seg;
+ for (var x = 0; x < segments.length; x++) {
+ seg = segments[x];
+ if (seg[0] == 255 & seg[1] == 225) {
+ return seg;
+ }
+ }
+ return [];
+ };
+ ExifRestorer.insertExif = function(resizedFileBase64, exifArray) {
+ var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae;
+ array = array.concat(exifArray);
+ array = array.concat(ato);
+ return array;
+ };
+ ExifRestorer.slice2Segments = function(rawImageArray) {
+ var head = 0, segments = [];
+ while (1) {
+ if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218) {
+ break;
+ }
+ if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) {
+ head += 2;
+ } else {
+ var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint);
+ segments.push(seg);
+ head = endPoint;
+ }
+ if (head > rawImageArray.length) {
+ break;
+ }
+ }
+ return segments;
+ };
+ ExifRestorer.decode64 = function(input) {
+ var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = [];
+ var base64test = /[^A-Za-z0-9\+\/\=]/g;
+ if (base64test.exec(input)) {
+ throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
+ }
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
+ do {
+ enc1 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc2 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc3 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc4 = this.KEY_STR.indexOf(input.charAt(i++));
+ chr1 = enc1 << 2 | enc2 >> 4;
+ chr2 = (enc2 & 15) << 4 | enc3 >> 2;
+ chr3 = (enc3 & 3) << 6 | enc4;
+ buf.push(chr1);
+ if (enc3 != 64) {
+ buf.push(chr2);
+ }
+ if (enc4 != 64) {
+ buf.push(chr3);
+ }
+ chr1 = chr2 = chr3 = "";
+ enc1 = enc2 = enc3 = enc4 = "";
+ } while (i < input.length);
+ return buf;
+ };
+ return ExifRestorer;
+ }();
+ qq.TotalProgress = function(callback, getSize) {
+ "use strict";
+ var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) {
+ if (loaded !== lastLoadedSent || total !== lastTotalSent) {
+ callback(loaded, total);
+ }
+ lastLoadedSent = loaded;
+ lastTotalSent = total;
+ }, noRetryableFiles = function(failed, retryable) {
+ var none = true;
+ qq.each(failed, function(idx, failedId) {
+ if (qq.indexOf(retryable, failedId) >= 0) {
+ none = false;
+ return false;
+ }
+ });
+ return none;
+ }, onCancel = function(id) {
+ updateTotalProgress(id, -1, -1);
+ delete perFileProgress[id];
+ }, onAllComplete = function(successful, failed, retryable) {
+ if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
+ callbackProxy(totalSize, totalSize);
+ this.reset();
+ }
+ }, onNew = function(id) {
+ var size = getSize(id);
+ if (size > 0) {
+ updateTotalProgress(id, 0, size);
+ perFileProgress[id] = {
+ loaded: 0,
+ total: size
+ };
+ }
+ }, updateTotalProgress = function(id, newLoaded, newTotal) {
+ var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
+ if (newLoaded === -1 && newTotal === -1) {
+ totalLoaded -= oldLoaded;
+ totalSize -= oldTotal;
+ } else {
+ if (newLoaded) {
+ totalLoaded += newLoaded - oldLoaded;
+ }
+ if (newTotal) {
+ totalSize += newTotal - oldTotal;
+ }
+ }
+ callbackProxy(totalLoaded, totalSize);
+ };
+ qq.extend(this, {
+ onAllComplete: onAllComplete,
+ onStatusChange: function(id, oldStatus, newStatus) {
+ if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
+ onCancel(id);
+ } else if (newStatus === qq.status.SUBMITTING) {
+ onNew(id);
+ }
+ },
+ onIndividualProgress: function(id, loaded, total) {
+ updateTotalProgress(id, loaded, total);
+ perFileProgress[id] = {
+ loaded: loaded,
+ total: total
+ };
+ },
+ onNewSize: function(id) {
+ onNew(id);
+ },
+ reset: function() {
+ perFileProgress = {};
+ totalLoaded = 0;
+ totalSize = 0;
+ }
+ });
+ };
+ qq.PasteSupport = function(o) {
+ "use strict";
+ var options, detachPasteHandler;
+ options = {
+ targetElement: null,
+ callbacks: {
+ log: function(message, level) {},
+ pasteReceived: function(blob) {}
+ }
+ };
+ function isImage(item) {
+ return item.type && item.type.indexOf("image/") === 0;
+ }
+ function registerPasteHandler() {
+ detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
+ var clipboardData = event.clipboardData;
+ if (clipboardData) {
+ qq.each(clipboardData.items, function(idx, item) {
+ if (isImage(item)) {
+ var blob = item.getAsFile();
+ options.callbacks.pasteReceived(blob);
+ }
+ });
+ }
+ });
+ }
+ function unregisterPasteHandler() {
+ if (detachPasteHandler) {
+ detachPasteHandler();
+ }
+ }
+ qq.extend(options, o);
+ registerPasteHandler();
+ qq.extend(this, {
+ reset: function() {
+ unregisterPasteHandler();
+ }
+ });
+ };
+ qq.FormSupport = function(options, startUpload, log) {
+ "use strict";
+ var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload;
+ qq.extend(this, {
+ newEndpoint: null,
+ newAutoUpload: autoUpload,
+ attachedToForm: false,
+ getFormInputsAsObject: function() {
+ if (formEl == null) {
+ return null;
+ }
+ return self._form2Obj(formEl);
+ }
+ });
+ function determineNewEndpoint(formEl) {
+ if (formEl.getAttribute("action")) {
+ self.newEndpoint = formEl.getAttribute("action");
+ }
+ }
+ function validateForm(formEl, nativeSubmit) {
+ if (formEl.checkValidity && !formEl.checkValidity()) {
+ log("Form did not pass validation checks - will not upload.", "error");
+ nativeSubmit();
+ } else {
+ return true;
+ }
+ }
+ function maybeUploadOnSubmit(formEl) {
+ var nativeSubmit = formEl.submit;
+ qq(formEl).attach("submit", function(event) {
+ event = event || window.event;
+ if (event.preventDefault) {
+ event.preventDefault();
+ } else {
+ event.returnValue = false;
+ }
+ validateForm(formEl, nativeSubmit) && startUpload();
+ });
+ formEl.submit = function() {
+ validateForm(formEl, nativeSubmit) && startUpload();
+ };
+ }
+ function determineFormEl(formEl) {
+ if (formEl) {
+ if (qq.isString(formEl)) {
+ formEl = document.getElementById(formEl);
+ }
+ if (formEl) {
+ log("Attaching to form element.");
+ determineNewEndpoint(formEl);
+ interceptSubmit && maybeUploadOnSubmit(formEl);
+ }
+ }
+ return formEl;
+ }
+ formEl = determineFormEl(formEl);
+ this.attachedToForm = !!formEl;
+ };
+ qq.extend(qq.FormSupport.prototype, {
+ _form2Obj: function(form) {
+ "use strict";
+ var obj = {}, notIrrelevantType = function(type) {
+ var irrelevantTypes = [ "button", "image", "reset", "submit" ];
+ return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
+ }, radioOrCheckbox = function(type) {
+ return qq.indexOf([ "checkbox", "radio" ], type.toLowerCase()) >= 0;
+ }, ignoreValue = function(el) {
+ if (radioOrCheckbox(el.type) && !el.checked) {
+ return true;
+ }
+ return el.disabled && el.type.toLowerCase() !== "hidden";
+ }, selectValue = function(select) {
+ var value = null;
+ qq.each(qq(select).children(), function(idx, child) {
+ if (child.tagName.toLowerCase() === "option" && child.selected) {
+ value = child.value;
+ return false;
+ }
+ });
+ return value;
+ };
+ qq.each(form.elements, function(idx, el) {
+ if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) {
+ obj[el.name] = el.value;
+ } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
+ var value = selectValue(el);
+ if (value !== null) {
+ obj[el.name] = value;
+ }
+ }
+ });
+ return obj;
+ }
+ });
+ qq.traditional = qq.traditional || {};
+ qq.traditional.FormUploadHandler = function(options, proxy) {
+ "use strict";
+ var handler = this, getName = proxy.getName, getUuid = proxy.getUuid, log = proxy.log;
+ function getIframeContentJson(id, iframe) {
+ var response, doc, innerHtml;
+ try {
+ doc = iframe.contentDocument || iframe.contentWindow.document;
+ innerHtml = doc.body.innerHTML;
+ log("converting iframe's innerHTML to JSON");
+ log("innerHTML = " + innerHtml);
+ if (innerHtml && innerHtml.match(/^ 1 && !options.allowMultipleItems) {
+ options.callbacks.processingDroppedFilesComplete([]);
+ options.callbacks.dropError("tooManyFilesError", "");
+ uploadDropZone.dropDisabled(false);
+ handleDataTransferPromise.failure();
+ } else {
+ droppedFiles = [];
+ if (qq.isFolderDropSupported(dataTransfer)) {
+ qq.each(dataTransfer.items, function(idx, item) {
+ var entry = item.webkitGetAsEntry();
+ if (entry) {
+ if (entry.isFile) {
+ droppedFiles.push(item.getAsFile());
+ } else {
+ pendingFolderPromises.push(traverseFileTree(entry).done(function() {
+ pendingFolderPromises.pop();
+ if (pendingFolderPromises.length === 0) {
+ handleDataTransferPromise.success();
+ }
+ }));
+ }
+ }
+ });
+ } else {
+ droppedFiles = dataTransfer.files;
+ }
+ if (pendingFolderPromises.length === 0) {
+ handleDataTransferPromise.success();
+ }
+ }
+ return handleDataTransferPromise;
+ }
+ function setupDropzone(dropArea) {
+ var dropZone = new qq.UploadDropZone({
+ HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME,
+ element: dropArea,
+ onEnter: function(e) {
+ qq(dropArea).addClass(options.classes.dropActive);
+ e.stopPropagation();
+ },
+ onLeaveNotDescendants: function(e) {
+ qq(dropArea).removeClass(options.classes.dropActive);
+ },
+ onDrop: function(e) {
+ handleDataTransfer(e.dataTransfer, dropZone).then(function() {
+ uploadDroppedFiles(droppedFiles, dropZone);
+ }, function() {
+ options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error");
+ });
+ }
+ });
+ disposeSupport.addDisposer(function() {
+ dropZone.dispose();
+ });
+ qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide();
+ uploadDropZones.push(dropZone);
+ return dropZone;
+ }
+ function isFileDrag(dragEvent) {
+ var fileDrag;
+ qq.each(dragEvent.dataTransfer.types, function(key, val) {
+ if (val === "Files") {
+ fileDrag = true;
+ return false;
+ }
+ });
+ return fileDrag;
+ }
+ function leavingDocumentOut(e) {
+ if (qq.safari()) {
+ return e.x < 0 || e.y < 0;
+ }
+ return e.x === 0 && e.y === 0;
+ }
+ function setupDragDrop() {
+ var dropZones = options.dropZoneElements, maybeHideDropZones = function() {
+ setTimeout(function() {
+ qq.each(dropZones, function(idx, dropZone) {
+ qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide();
+ qq(dropZone).removeClass(options.classes.dropActive);
+ });
+ }, 10);
+ };
+ qq.each(dropZones, function(idx, dropZone) {
+ var uploadDropZone = setupDropzone(dropZone);
+ if (dropZones.length && qq.supportedFeatures.fileDrop) {
+ disposeSupport.attach(document, "dragenter", function(e) {
+ if (!uploadDropZone.dropDisabled() && isFileDrag(e)) {
+ qq.each(dropZones, function(idx, dropZone) {
+ if (dropZone instanceof HTMLElement && qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) {
+ qq(dropZone).css({
+ display: "block"
+ });
+ }
+ });
+ }
+ });
+ }
+ });
+ disposeSupport.attach(document, "dragleave", function(e) {
+ if (leavingDocumentOut(e)) {
+ maybeHideDropZones();
+ }
+ });
+ disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) {
+ maybeHideDropZones();
+ });
+ disposeSupport.attach(document, "drop", function(e) {
+ if (isFileDrag(e)) {
+ e.preventDefault();
+ maybeHideDropZones();
+ }
+ });
+ disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones);
+ }
+ setupDragDrop();
+ qq.extend(this, {
+ setupExtraDropzone: function(element) {
+ options.dropZoneElements.push(element);
+ setupDropzone(element);
+ },
+ removeDropzone: function(element) {
+ var i, dzs = options.dropZoneElements;
+ for (i in dzs) {
+ if (dzs[i] === element) {
+ return dzs.splice(i, 1);
+ }
+ }
+ },
+ dispose: function() {
+ disposeSupport.dispose();
+ qq.each(uploadDropZones, function(idx, dropZone) {
+ dropZone.dispose();
+ });
+ }
+ });
+ };
+ qq.DragAndDrop.callbacks = function() {
+ "use strict";
+ return {
+ processingDroppedFiles: function() {},
+ processingDroppedFilesComplete: function(files, targetEl) {},
+ dropError: function(code, errorSpecifics) {
+ qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error");
+ },
+ dropLog: function(message, level) {
+ qq.log(message, level);
+ }
+ };
+ };
+ qq.UploadDropZone = function(o) {
+ "use strict";
+ var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled;
+ options = {
+ element: null,
+ onEnter: function(e) {},
+ onLeave: function(e) {},
+ onLeaveNotDescendants: function(e) {},
+ onDrop: function(e) {}
+ };
+ qq.extend(options, o);
+ element = options.element;
+ function dragoverShouldBeCanceled() {
+ return qq.safari() || qq.firefox() && qq.windows();
+ }
+ function disableDropOutside(e) {
+ if (!dropOutsideDisabled) {
+ if (dragoverShouldBeCanceled) {
+ disposeSupport.attach(document, "dragover", function(e) {
+ e.preventDefault();
+ });
+ } else {
+ disposeSupport.attach(document, "dragover", function(e) {
+ if (e.dataTransfer) {
+ e.dataTransfer.dropEffect = "none";
+ e.preventDefault();
+ }
+ });
+ }
+ dropOutsideDisabled = true;
+ }
+ }
+ function isValidFileDrag(e) {
+ if (!qq.supportedFeatures.fileDrop) {
+ return false;
+ }
+ var effectTest, dt = e.dataTransfer, isSafari = qq.safari();
+ effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none";
+ return dt && effectTest && (dt.files && dt.files.length || !isSafari && dt.types.contains && dt.types.contains("Files") || dt.types.includes && dt.types.includes("Files"));
+ }
+ function isOrSetDropDisabled(isDisabled) {
+ if (isDisabled !== undefined) {
+ preventDrop = isDisabled;
+ }
+ return preventDrop;
+ }
+ function triggerHidezonesEvent() {
+ var hideZonesEvent;
+ function triggerUsingOldApi() {
+ hideZonesEvent = document.createEvent("Event");
+ hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true);
+ }
+ if (window.CustomEvent) {
+ try {
+ hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME);
+ } catch (err) {
+ triggerUsingOldApi();
+ }
+ } else {
+ triggerUsingOldApi();
+ }
+ document.dispatchEvent(hideZonesEvent);
+ }
+ function attachEvents() {
+ disposeSupport.attach(element, "dragover", function(e) {
+ if (!isValidFileDrag(e)) {
+ return;
+ }
+ var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed;
+ if (effect === "move" || effect === "linkMove") {
+ e.dataTransfer.dropEffect = "move";
+ } else {
+ e.dataTransfer.dropEffect = "copy";
+ }
+ e.stopPropagation();
+ e.preventDefault();
+ });
+ disposeSupport.attach(element, "dragenter", function(e) {
+ if (!isOrSetDropDisabled()) {
+ if (!isValidFileDrag(e)) {
+ return;
+ }
+ options.onEnter(e);
+ }
+ });
+ disposeSupport.attach(element, "dragleave", function(e) {
+ if (!isValidFileDrag(e)) {
+ return;
+ }
+ options.onLeave(e);
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
+ if (qq(this).contains(relatedTarget)) {
+ return;
+ }
+ options.onLeaveNotDescendants(e);
+ });
+ disposeSupport.attach(element, "drop", function(e) {
+ if (!isOrSetDropDisabled()) {
+ if (!isValidFileDrag(e)) {
+ return;
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ options.onDrop(e);
+ triggerHidezonesEvent();
+ }
+ });
+ }
+ disableDropOutside();
+ attachEvents();
+ qq.extend(this, {
+ dropDisabled: function(isDisabled) {
+ return isOrSetDropDisabled(isDisabled);
+ },
+ dispose: function() {
+ disposeSupport.dispose();
+ },
+ getElement: function() {
+ return element;
+ }
+ });
+ this._testing = {};
+ this._testing.isValidFileDrag = isValidFileDrag;
+ };
+ (function() {
+ "use strict";
+ qq.uiPublicApi = {
+ addInitialFiles: function(cannedFileList) {
+ this._parent.prototype.addInitialFiles.apply(this, arguments);
+ this._templating.addCacheToDom();
+ },
+ clearStoredFiles: function() {
+ this._parent.prototype.clearStoredFiles.apply(this, arguments);
+ this._templating.clearFiles();
+ },
+ addExtraDropzone: function(element) {
+ this._dnd && this._dnd.setupExtraDropzone(element);
+ },
+ removeExtraDropzone: function(element) {
+ if (this._dnd) {
+ return this._dnd.removeDropzone(element);
+ }
+ },
+ getItemByFileId: function(id) {
+ if (!this._templating.isHiddenForever(id)) {
+ return this._templating.getFileContainer(id);
+ }
+ },
+ reset: function() {
+ this._parent.prototype.reset.apply(this, arguments);
+ this._templating.reset();
+ if (!this._options.button && this._templating.getButton()) {
+ this._defaultButtonId = this._createUploadButton({
+ element: this._templating.getButton(),
+ title: this._options.text.fileInputTitle
+ }).getButtonId();
+ }
+ if (this._dnd) {
+ this._dnd.dispose();
+ this._dnd = this._setupDragAndDrop();
+ }
+ this._totalFilesInBatch = 0;
+ this._filesInBatchAddedToUi = 0;
+ this._setupClickAndEditEventHandlers();
+ },
+ setName: function(id, newName) {
+ var formattedFilename = this._options.formatFileName(newName);
+ this._parent.prototype.setName.apply(this, arguments);
+ this._templating.updateFilename(id, formattedFilename);
+ },
+ pauseUpload: function(id) {
+ var paused = this._parent.prototype.pauseUpload.apply(this, arguments);
+ paused && this._templating.uploadPaused(id);
+ return paused;
+ },
+ continueUpload: function(id) {
+ var continued = this._parent.prototype.continueUpload.apply(this, arguments);
+ continued && this._templating.uploadContinued(id);
+ return continued;
+ },
+ getId: function(fileContainerOrChildEl) {
+ return this._templating.getFileId(fileContainerOrChildEl);
+ },
+ getDropTarget: function(fileId) {
+ var file = this.getFile(fileId);
+ return file.qqDropTarget;
+ }
+ };
+ qq.uiPrivateApi = {
+ _getButton: function(buttonId) {
+ var button = this._parent.prototype._getButton.apply(this, arguments);
+ if (!button) {
+ if (buttonId === this._defaultButtonId) {
+ button = this._templating.getButton();
+ }
+ }
+ return button;
+ },
+ _removeFileItem: function(fileId) {
+ this._templating.removeFile(fileId);
+ },
+ _setupClickAndEditEventHandlers: function() {
+ this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent();
+ this._focusinEventSupported = !qq.firefox();
+ if (this._isEditFilenameEnabled()) {
+ this._filenameClickHandler = this._bindFilenameClickEvent();
+ this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent();
+ this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent();
+ }
+ },
+ _setupDragAndDrop: function() {
+ var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone();
+ defaultDropZone && dropZoneElements.push(defaultDropZone);
+ return new qq.DragAndDrop({
+ dropZoneElements: dropZoneElements,
+ allowMultipleItems: this._options.multiple,
+ classes: {
+ dropActive: this._options.classes.dropActive
+ },
+ callbacks: {
+ processingDroppedFiles: function() {
+ templating.showDropProcessing();
+ },
+ processingDroppedFilesComplete: function(files, targetEl) {
+ templating.hideDropProcessing();
+ qq.each(files, function(idx, file) {
+ file.qqDropTarget = targetEl;
+ });
+ if (files.length) {
+ self.addFiles(files, null, null);
+ }
+ },
+ dropError: function(code, errorData) {
+ self._itemError(code, errorData);
+ },
+ dropLog: function(message, level) {
+ self.log(message, level);
+ }
+ }
+ });
+ },
+ _bindFileButtonsClickEvent: function() {
+ var self = this;
+ return new qq.FileButtonsClickHandler({
+ templating: this._templating,
+ log: function(message, lvl) {
+ self.log(message, lvl);
+ },
+ onDeleteFile: function(fileId) {
+ self.deleteFile(fileId);
+ },
+ onCancel: function(fileId) {
+ self.cancel(fileId);
+ },
+ onRetry: function(fileId) {
+ self.retry(fileId);
+ },
+ onPause: function(fileId) {
+ self.pauseUpload(fileId);
+ },
+ onContinue: function(fileId) {
+ self.continueUpload(fileId);
+ },
+ onGetName: function(fileId) {
+ return self.getName(fileId);
+ }
+ });
+ },
+ _isEditFilenameEnabled: function() {
+ return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler;
+ },
+ _filenameEditHandler: function() {
+ var self = this, templating = this._templating;
+ return {
+ templating: templating,
+ log: function(message, lvl) {
+ self.log(message, lvl);
+ },
+ onGetUploadStatus: function(fileId) {
+ return self.getUploads({
+ id: fileId
+ }).status;
+ },
+ onGetName: function(fileId) {
+ return self.getName(fileId);
+ },
+ onSetName: function(id, newName) {
+ self.setName(id, newName);
+ },
+ onEditingStatusChange: function(id, isEditing) {
+ var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id));
+ if (isEditing) {
+ qqInput.addClass("qq-editing");
+ templating.hideFilename(id);
+ templating.hideEditIcon(id);
+ } else {
+ qqInput.removeClass("qq-editing");
+ templating.showFilename(id);
+ templating.showEditIcon(id);
+ }
+ qqFileContainer.addClass("qq-temp").removeClass("qq-temp");
+ }
+ };
+ },
+ _onUploadStatusChange: function(id, oldStatus, newStatus) {
+ this._parent.prototype._onUploadStatusChange.apply(this, arguments);
+ if (this._isEditFilenameEnabled()) {
+ if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) {
+ this._templating.markFilenameEditable(id);
+ this._templating.hideEditIcon(id);
+ }
+ }
+ if (oldStatus === qq.status.UPLOAD_RETRYING && newStatus === qq.status.UPLOADING) {
+ this._templating.hideRetry(id);
+ this._templating.setStatusText(id);
+ qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying);
+ } else if (newStatus === qq.status.UPLOAD_FAILED) {
+ this._templating.hidePause(id);
+ }
+ },
+ _bindFilenameInputFocusInEvent: function() {
+ var spec = qq.extend({}, this._filenameEditHandler());
+ return new qq.FilenameInputFocusInHandler(spec);
+ },
+ _bindFilenameInputFocusEvent: function() {
+ var spec = qq.extend({}, this._filenameEditHandler());
+ return new qq.FilenameInputFocusHandler(spec);
+ },
+ _bindFilenameClickEvent: function() {
+ var spec = qq.extend({}, this._filenameEditHandler());
+ return new qq.FilenameClickHandler(spec);
+ },
+ _storeForLater: function(id) {
+ this._parent.prototype._storeForLater.apply(this, arguments);
+ this._templating.hideSpinner(id);
+ },
+ _onAllComplete: function(successful, failed) {
+ this._parent.prototype._onAllComplete.apply(this, arguments);
+ this._templating.resetTotalProgress();
+ },
+ _onSubmit: function(id, name) {
+ var file = this.getFile(id);
+ if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) {
+ this._paramsStore.addReadOnly(id, {
+ qqpath: file.qqPath
+ });
+ }
+ this._parent.prototype._onSubmit.apply(this, arguments);
+ this._addToList(id, name);
+ },
+ _onSubmitted: function(id) {
+ if (this._isEditFilenameEnabled()) {
+ this._templating.markFilenameEditable(id);
+ this._templating.showEditIcon(id);
+ if (!this._focusinEventSupported) {
+ this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id));
+ }
+ }
+ },
+ _onProgress: function(id, name, loaded, total) {
+ this._parent.prototype._onProgress.apply(this, arguments);
+ this._templating.updateProgress(id, loaded, total);
+ if (total === 0 || Math.round(loaded / total * 100) === 100) {
+ this._templating.hideCancel(id);
+ this._templating.hidePause(id);
+ this._templating.hideProgress(id);
+ this._templating.setStatusText(id, this._options.text.waitingForResponse);
+ this._displayFileSize(id);
+ } else {
+ this._displayFileSize(id, loaded, total);
+ }
+ },
+ _onTotalProgress: function(loaded, total) {
+ this._parent.prototype._onTotalProgress.apply(this, arguments);
+ this._templating.updateTotalProgress(loaded, total);
+ },
+ _onComplete: function(id, name, result, xhr) {
+ var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, fileContainer = templating.getFileContainer(id), self = this;
+ function completeUpload(result) {
+ if (!fileContainer) {
+ return;
+ }
+ templating.setStatusText(id);
+ qq(fileContainer).removeClass(self._classes.retrying);
+ templating.hideProgress(id);
+ if (self.getUploads({
+ id: id
+ }).status !== qq.status.UPLOAD_FAILED) {
+ templating.hideCancel(id);
+ }
+ templating.hideSpinner(id);
+ if (result.success) {
+ self._markFileAsSuccessful(id);
+ } else {
+ qq(fileContainer).addClass(self._classes.fail);
+ templating.showCancel(id);
+ if (templating.isRetryPossible() && !self._preventRetries[id]) {
+ qq(fileContainer).addClass(self._classes.retryable);
+ templating.showRetry(id);
+ }
+ self._controlFailureTextDisplay(id, result);
+ }
+ }
+ if (parentRetVal instanceof qq.Promise) {
+ parentRetVal.done(function(newResult) {
+ completeUpload(newResult);
+ });
+ } else {
+ completeUpload(result);
+ }
+ return parentRetVal;
+ },
+ _markFileAsSuccessful: function(id) {
+ var templating = this._templating;
+ if (this._isDeletePossible()) {
+ templating.showDeleteButton(id);
+ }
+ qq(templating.getFileContainer(id)).addClass(this._classes.success);
+ this._maybeUpdateThumbnail(id);
+ },
+ _onUploadPrep: function(id) {
+ this._parent.prototype._onUploadPrep.apply(this, arguments);
+ this._templating.showSpinner(id);
+ },
+ _onUpload: function(id, name) {
+ var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments);
+ this._templating.showSpinner(id);
+ return parentRetVal;
+ },
+ _onUploadChunk: function(id, chunkData) {
+ this._parent.prototype._onUploadChunk.apply(this, arguments);
+ if (chunkData.partIndex > 0 && this._handler.isResumable(id)) {
+ this._templating.allowPause(id);
+ }
+ },
+ _onCancel: function(id, name) {
+ this._parent.prototype._onCancel.apply(this, arguments);
+ this._removeFileItem(id);
+ if (this._getNotFinished() === 0) {
+ this._templating.resetTotalProgress();
+ }
+ },
+ _onBeforeAutoRetry: function(id) {
+ var retryNumForDisplay, maxAuto, retryNote;
+ this._parent.prototype._onBeforeAutoRetry.apply(this, arguments);
+ this._showCancelLink(id);
+ if (this._options.retry.showAutoRetryNote) {
+ retryNumForDisplay = this._autoRetries[id];
+ maxAuto = this._options.retry.maxAutoAttempts;
+ retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay);
+ retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto);
+ this._templating.setStatusText(id, retryNote);
+ qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying);
+ }
+ },
+ _onBeforeManualRetry: function(id) {
+ if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) {
+ this._templating.resetProgress(id);
+ qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail);
+ this._templating.setStatusText(id);
+ this._templating.showSpinner(id);
+ this._showCancelLink(id);
+ return true;
+ } else {
+ qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable);
+ this._templating.showRetry(id);
+ return false;
+ }
+ },
+ _onSubmitDelete: function(id) {
+ var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this);
+ this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback);
+ },
+ _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) {
+ if (this._options.deleteFile.forceConfirm) {
+ this._showDeleteConfirm.apply(this, arguments);
+ } else {
+ this._sendDeleteRequest.apply(this, arguments);
+ }
+ },
+ _onDeleteComplete: function(id, xhr, isError) {
+ this._parent.prototype._onDeleteComplete.apply(this, arguments);
+ this._templating.hideSpinner(id);
+ if (isError) {
+ this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText);
+ this._templating.showDeleteButton(id);
+ } else {
+ this._removeFileItem(id);
+ }
+ },
+ _sendDeleteRequest: function(id, uuid, additionalMandatedParams) {
+ this._templating.hideDeleteButton(id);
+ this._templating.showSpinner(id);
+ this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText);
+ this._deleteHandler.sendDelete.apply(this, arguments);
+ },
+ _showDeleteConfirm: function(id, uuid, mandatedParams) {
+ var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal;
+ retVal = this._options.showConfirm(confirmMessage);
+ if (qq.isGenericPromise(retVal)) {
+ retVal.then(function() {
+ self._sendDeleteRequest.apply(self, deleteRequestArgs);
+ });
+ } else if (retVal !== false) {
+ self._sendDeleteRequest.apply(self, deleteRequestArgs);
+ }
+ },
+ _addToList: function(id, name, canned) {
+ var prependData, prependIndex = 0, dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled, record;
+ if (this._options.display.prependFiles) {
+ if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {
+ prependIndex = this._filesInBatchAddedToUi - 1;
+ }
+ prependData = {
+ index: prependIndex
+ };
+ }
+ if (!canned) {
+ if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {
+ this._templating.disableCancel();
+ }
+ if (!this._options.multiple) {
+ record = this.getUploads({
+ id: id
+ });
+ this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId;
+ if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) {
+ this._handler.cancelAll();
+ this._clearList();
+ this._handledProxyGroup = null;
+ }
+ }
+ }
+ if (canned) {
+ this._templating.addFileToCache(id, this._options.formatFileName(name), prependData, dontDisplay);
+ this._templating.updateThumbnail(id, this._thumbnailUrls[id], true, this._options.thumbnails.customResizer);
+ } else {
+ this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay);
+ this._templating.generatePreview(id, this.getFile(id), this._options.thumbnails.customResizer);
+ }
+ this._filesInBatchAddedToUi += 1;
+ if (canned || this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading) {
+ this._displayFileSize(id);
+ }
+ },
+ _clearList: function() {
+ this._templating.clearFiles();
+ this.clearStoredFiles();
+ },
+ _displayFileSize: function(id, loadedSize, totalSize) {
+ var size = this.getSize(id), sizeForDisplay = this._formatSize(size);
+ if (size >= 0) {
+ if (loadedSize !== undefined && totalSize !== undefined) {
+ sizeForDisplay = this._formatProgress(loadedSize, totalSize);
+ }
+ this._templating.updateSize(id, sizeForDisplay);
+ }
+ },
+ _formatProgress: function(uploadedSize, totalSize) {
+ var message = this._options.text.formatProgress;
+ function r(name, replacement) {
+ message = message.replace(name, replacement);
+ }
+ r("{percent}", Math.round(uploadedSize / totalSize * 100));
+ r("{total_size}", this._formatSize(totalSize));
+ return message;
+ },
+ _controlFailureTextDisplay: function(id, response) {
+ var mode, responseProperty, failureReason;
+ mode = this._options.failedUploadTextDisplay.mode;
+ responseProperty = this._options.failedUploadTextDisplay.responseProperty;
+ if (mode === "custom") {
+ failureReason = response[responseProperty];
+ if (!failureReason) {
+ failureReason = this._options.text.failUpload;
+ }
+ this._templating.setStatusText(id, failureReason);
+ if (this._options.failedUploadTextDisplay.enableTooltip) {
+ this._showTooltip(id, failureReason);
+ }
+ } else if (mode === "default") {
+ this._templating.setStatusText(id, this._options.text.failUpload);
+ } else if (mode !== "none") {
+ this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn");
+ }
+ },
+ _showTooltip: function(id, text) {
+ this._templating.getFileContainer(id).title = text;
+ },
+ _showCancelLink: function(id) {
+ if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
+ this._templating.showCancel(id);
+ }
+ },
+ _itemError: function(code, name, item) {
+ var message = this._parent.prototype._itemError.apply(this, arguments);
+ this._options.showMessage(message);
+ },
+ _batchError: function(message) {
+ this._parent.prototype._batchError.apply(this, arguments);
+ this._options.showMessage(message);
+ },
+ _setupPastePrompt: function() {
+ var self = this;
+ this._options.callbacks.onPasteReceived = function() {
+ var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName;
+ return self._options.showPrompt(message, defaultVal);
+ };
+ },
+ _fileOrBlobRejected: function(id, name) {
+ this._totalFilesInBatch -= 1;
+ this._parent.prototype._fileOrBlobRejected.apply(this, arguments);
+ },
+ _prepareItemsForUpload: function(items, params, endpoint) {
+ this._totalFilesInBatch = items.length;
+ this._filesInBatchAddedToUi = 0;
+ this._parent.prototype._prepareItemsForUpload.apply(this, arguments);
+ },
+ _maybeUpdateThumbnail: function(fileId) {
+ var thumbnailUrl = this._thumbnailUrls[fileId], fileStatus = this.getUploads({
+ id: fileId
+ }).status;
+ if (fileStatus !== qq.status.DELETED && (thumbnailUrl || this._options.thumbnails.placeholders.waitUntilResponse || !qq.supportedFeatures.imagePreviews)) {
+ this._templating.updateThumbnail(fileId, thumbnailUrl, this._options.thumbnails.customResizer);
+ }
+ },
+ _addCannedFile: function(sessionData) {
+ var id = this._parent.prototype._addCannedFile.apply(this, arguments);
+ this._addToList(id, this.getName(id), true);
+ this._templating.hideSpinner(id);
+ this._templating.hideCancel(id);
+ this._markFileAsSuccessful(id);
+ return id;
+ },
+ _setSize: function(id, newSize) {
+ this._parent.prototype._setSize.apply(this, arguments);
+ this._templating.updateSize(id, this._formatSize(newSize));
+ },
+ _sessionRequestComplete: function() {
+ this._templating.addCacheToDom();
+ this._parent.prototype._sessionRequestComplete.apply(this, arguments);
+ }
+ };
+ })();
+ qq.FineUploader = function(o, namespace) {
+ "use strict";
+ var self = this;
+ this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic;
+ this._parent.apply(this, arguments);
+ qq.extend(this._options, {
+ element: null,
+ button: null,
+ listElement: null,
+ dragAndDrop: {
+ extraDropzones: [],
+ reportDirectoryPaths: false
+ },
+ text: {
+ formatProgress: "{percent}% of {total_size}",
+ failUpload: "Upload failed",
+ waitingForResponse: "Processing...",
+ paused: "Paused"
+ },
+ template: "qq-template",
+ classes: {
+ retrying: "qq-upload-retrying",
+ retryable: "qq-upload-retryable",
+ success: "qq-upload-success",
+ fail: "qq-upload-fail",
+ editable: "qq-editable",
+ hide: "qq-hide",
+ dropActive: "qq-upload-drop-area-active"
+ },
+ failedUploadTextDisplay: {
+ mode: "default",
+ responseProperty: "error",
+ enableTooltip: true
+ },
+ messages: {
+ tooManyFilesError: "You may only drop one file",
+ unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind."
+ },
+ retry: {
+ showAutoRetryNote: true,
+ autoRetryNote: "Retrying {retryNum}/{maxAuto}..."
+ },
+ deleteFile: {
+ forceConfirm: false,
+ confirmMessage: "Are you sure you want to delete {filename}?",
+ deletingStatusText: "Deleting...",
+ deletingFailedText: "Delete failed"
+ },
+ display: {
+ fileSizeOnSubmit: false,
+ prependFiles: false
+ },
+ paste: {
+ promptForName: false,
+ namePromptMessage: "Please name this image"
+ },
+ thumbnails: {
+ customResizer: null,
+ maxCount: 0,
+ placeholders: {
+ waitUntilResponse: false,
+ notAvailablePath: null,
+ waitingPath: null
+ },
+ timeBetweenThumbs: 750
+ },
+ scaling: {
+ hideScaled: false
+ },
+ showMessage: function(message) {
+ if (self._templating.hasDialog("alert")) {
+ return self._templating.showDialog("alert", message);
+ } else {
+ setTimeout(function() {
+ window.alert(message);
+ }, 0);
+ }
+ },
+ showConfirm: function(message) {
+ if (self._templating.hasDialog("confirm")) {
+ return self._templating.showDialog("confirm", message);
+ } else {
+ return window.confirm(message);
+ }
+ },
+ showPrompt: function(message, defaultValue) {
+ if (self._templating.hasDialog("prompt")) {
+ return self._templating.showDialog("prompt", message, defaultValue);
+ } else {
+ return window.prompt(message, defaultValue);
+ }
+ }
+ }, true);
+ qq.extend(this._options, o, true);
+ this._templating = new qq.Templating({
+ log: qq.bind(this.log, this),
+ templateIdOrEl: this._options.template,
+ containerEl: this._options.element,
+ fileContainerEl: this._options.listElement,
+ button: this._options.button,
+ imageGenerator: this._imageGenerator,
+ classes: {
+ hide: this._options.classes.hide,
+ editable: this._options.classes.editable
+ },
+ limits: {
+ maxThumbs: this._options.thumbnails.maxCount,
+ timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs
+ },
+ placeholders: {
+ waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse,
+ thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath,
+ waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath
+ },
+ text: this._options.text
+ });
+ if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
+ this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari);
+ } else if (!qq.supportedFeatures.uploading || this._options.cors.expected && !qq.supportedFeatures.uploadCors) {
+ this._templating.renderFailure(this._options.messages.unsupportedBrowser);
+ } else {
+ this._wrapCallbacks();
+ this._templating.render();
+ this._classes = this._options.classes;
+ if (!this._options.button && this._templating.getButton()) {
+ this._defaultButtonId = this._createUploadButton({
+ element: this._templating.getButton(),
+ title: this._options.text.fileInputTitle
+ }).getButtonId();
+ }
+ this._setupClickAndEditEventHandlers();
+ if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) {
+ this._dnd = this._setupDragAndDrop();
+ }
+ if (this._options.paste.targetElement && this._options.paste.promptForName) {
+ if (qq.PasteSupport) {
+ this._setupPastePrompt();
+ } else {
+ this.log("Paste support module not found.", "error");
+ }
+ }
+ this._totalFilesInBatch = 0;
+ this._filesInBatchAddedToUi = 0;
+ }
+ };
+ qq.extend(qq.FineUploader.prototype, qq.basePublicApi);
+ qq.extend(qq.FineUploader.prototype, qq.basePrivateApi);
+ qq.extend(qq.FineUploader.prototype, qq.uiPublicApi);
+ qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi);
+ qq.Templating = function(spec) {
+ "use strict";
+ var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", HIDE_DROPZONE_ATTR = "qq-hide-dropzone", DROPZPONE_TEXT_ATTR = "qq-drop-area-text", IN_PROGRESS_CLASS = "qq-in-progress", HIDDEN_FOREVER_CLASS = "qq-hidden-forever", fileBatch = {
+ content: document.createDocumentFragment(),
+ map: {}
+ }, isCancelDisabled = false, generatedThumbnails = 0, thumbnailQueueMonitorRunning = false, thumbGenerationQueue = [], thumbnailMaxSize = -1, options = {
+ log: null,
+ limits: {
+ maxThumbs: 0,
+ timeBetweenThumbs: 750
+ },
+ templateIdOrEl: "qq-template",
+ containerEl: null,
+ fileContainerEl: null,
+ button: null,
+ imageGenerator: null,
+ classes: {
+ hide: "qq-hide",
+ editable: "qq-editable"
+ },
+ placeholders: {
+ waitUntilUpdate: false,
+ thumbnailNotAvailable: null,
+ waitingForThumbnail: null
+ },
+ text: {
+ paused: "Paused"
+ }
+ }, selectorClasses = {
+ button: "qq-upload-button-selector",
+ alertDialog: "qq-alert-dialog-selector",
+ dialogCancelButton: "qq-cancel-button-selector",
+ confirmDialog: "qq-confirm-dialog-selector",
+ dialogMessage: "qq-dialog-message-selector",
+ dialogOkButton: "qq-ok-button-selector",
+ promptDialog: "qq-prompt-dialog-selector",
+ uploader: "qq-uploader-selector",
+ drop: "qq-upload-drop-area-selector",
+ list: "qq-upload-list-selector",
+ progressBarContainer: "qq-progress-bar-container-selector",
+ progressBar: "qq-progress-bar-selector",
+ totalProgressBarContainer: "qq-total-progress-bar-container-selector",
+ totalProgressBar: "qq-total-progress-bar-selector",
+ file: "qq-upload-file-selector",
+ spinner: "qq-upload-spinner-selector",
+ size: "qq-upload-size-selector",
+ cancel: "qq-upload-cancel-selector",
+ pause: "qq-upload-pause-selector",
+ continueButton: "qq-upload-continue-selector",
+ deleteButton: "qq-upload-delete-selector",
+ retry: "qq-upload-retry-selector",
+ statusText: "qq-upload-status-text-selector",
+ editFilenameInput: "qq-edit-filename-selector",
+ editNameIcon: "qq-edit-filename-icon-selector",
+ dropText: "qq-upload-drop-area-text-selector",
+ dropProcessing: "qq-drop-processing-selector",
+ dropProcessingSpinner: "qq-drop-processing-spinner-selector",
+ thumbnail: "qq-thumbnail-selector"
+ }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateDom, container, fileList, showThumbnails, serverScale, cacheThumbnailPlaceholders = function() {
+ var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = {
+ maxSize: thumbnailMaxSize,
+ scale: serverScale
+ };
+ if (showThumbnails) {
+ if (notAvailableUrl) {
+ options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(function(updatedImg) {
+ cachedThumbnailNotAvailableImg.success(updatedImg);
+ }, function() {
+ cachedThumbnailNotAvailableImg.failure();
+ log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error");
+ });
+ } else {
+ cachedThumbnailNotAvailableImg.failure();
+ }
+ if (waitingUrl) {
+ options.imageGenerator.generate(waitingUrl, new Image(), spec).then(function(updatedImg) {
+ cachedWaitingForThumbnailImg.success(updatedImg);
+ }, function() {
+ cachedWaitingForThumbnailImg.failure();
+ log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error");
+ });
+ } else {
+ cachedWaitingForThumbnailImg.failure();
+ }
+ }
+ }, displayWaitingImg = function(thumbnail) {
+ var waitingImgPlacement = new qq.Promise();
+ cachedWaitingForThumbnailImg.then(function(img) {
+ maybeScalePlaceholderViaCss(img, thumbnail);
+ if (!thumbnail.src) {
+ thumbnail.src = img.src;
+ thumbnail.onload = function() {
+ thumbnail.onload = null;
+ show(thumbnail);
+ waitingImgPlacement.success();
+ };
+ } else {
+ waitingImgPlacement.success();
+ }
+ }, function() {
+ hide(thumbnail);
+ waitingImgPlacement.success();
+ });
+ return waitingImgPlacement;
+ }, generateNewPreview = function(id, blob, spec) {
+ var thumbnail = getThumbnail(id);
+ log("Generating new thumbnail for " + id);
+ blob.qqThumbnailId = id;
+ return options.imageGenerator.generate(blob, thumbnail, spec).then(function() {
+ generatedThumbnails++;
+ show(thumbnail);
+ previewGeneration[id].success();
+ }, function() {
+ previewGeneration[id].failure();
+ if (!options.placeholders.waitUntilUpdate) {
+ maybeSetDisplayNotAvailableImg(id, thumbnail);
+ }
+ });
+ }, generateNextQueuedPreview = function() {
+ if (thumbGenerationQueue.length) {
+ thumbnailQueueMonitorRunning = true;
+ var queuedThumbRequest = thumbGenerationQueue.shift();
+ if (queuedThumbRequest.update) {
+ processUpdateQueuedPreviewRequest(queuedThumbRequest);
+ } else {
+ processNewQueuedPreviewRequest(queuedThumbRequest);
+ }
+ } else {
+ thumbnailQueueMonitorRunning = false;
+ }
+ }, getCancel = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.cancel);
+ }, getContinue = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.continueButton);
+ }, getDialog = function(type) {
+ return getTemplateEl(container, selectorClasses[type + "Dialog"]);
+ }, getDelete = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.deleteButton);
+ }, getDropProcessing = function() {
+ return getTemplateEl(container, selectorClasses.dropProcessing);
+ }, getEditIcon = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.editNameIcon);
+ }, getFile = function(id) {
+ return fileBatch.map[id] || qq(fileList).getFirstByClass(FILE_CLASS_PREFIX + id);
+ }, getFilename = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.file);
+ }, getPause = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.pause);
+ }, getProgress = function(id) {
+ if (id == null) {
+ return getTemplateEl(container, selectorClasses.totalProgressBarContainer) || getTemplateEl(container, selectorClasses.totalProgressBar);
+ }
+ return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar);
+ }, getRetry = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.retry);
+ }, getSize = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.size);
+ }, getSpinner = function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.spinner);
+ }, getTemplateEl = function(context, cssClass) {
+ return context && qq(context).getFirstByClass(cssClass);
+ }, getThumbnail = function(id) {
+ return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail);
+ }, hide = function(el) {
+ el && qq(el).addClass(options.classes.hide);
+ }, maybeScalePlaceholderViaCss = function(placeholder, thumbnail) {
+ var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight;
+ if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) {
+ qq(thumbnail).css({
+ maxWidth: maxWidth,
+ maxHeight: maxHeight
+ });
+ }
+ }, maybeSetDisplayNotAvailableImg = function(id, thumbnail) {
+ var previewing = previewGeneration[id] || new qq.Promise().failure(), notAvailableImgPlacement = new qq.Promise();
+ cachedThumbnailNotAvailableImg.then(function(img) {
+ previewing.then(function() {
+ notAvailableImgPlacement.success();
+ }, function() {
+ maybeScalePlaceholderViaCss(img, thumbnail);
+ thumbnail.onload = function() {
+ thumbnail.onload = null;
+ notAvailableImgPlacement.success();
+ };
+ thumbnail.src = img.src;
+ show(thumbnail);
+ });
+ });
+ return notAvailableImgPlacement;
+ }, parseAndGetTemplate = function() {
+ var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListEl, defaultButton, dropArea, thumbnail, dropProcessing, dropTextEl, uploaderEl;
+ log("Parsing template");
+ if (options.templateIdOrEl == null) {
+ throw new Error("You MUST specify either a template element or ID!");
+ }
+ if (qq.isString(options.templateIdOrEl)) {
+ scriptEl = document.getElementById(options.templateIdOrEl);
+ if (scriptEl === null) {
+ throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl));
+ }
+ scriptHtml = scriptEl.innerHTML;
+ } else {
+ if (options.templateIdOrEl.innerHTML === undefined) {
+ throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element.");
+ }
+ scriptHtml = options.templateIdOrEl.innerHTML;
+ }
+ scriptHtml = qq.trimStr(scriptHtml);
+ tempTemplateEl = document.createElement("div");
+ tempTemplateEl.appendChild(qq.toElement(scriptHtml));
+ uploaderEl = qq(tempTemplateEl).getFirstByClass(selectorClasses.uploader);
+ if (options.button) {
+ defaultButton = qq(tempTemplateEl).getFirstByClass(selectorClasses.button);
+ if (defaultButton) {
+ qq(defaultButton).remove();
+ }
+ }
+ if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) {
+ dropProcessing = qq(tempTemplateEl).getFirstByClass(selectorClasses.dropProcessing);
+ if (dropProcessing) {
+ qq(dropProcessing).remove();
+ }
+ }
+ dropArea = qq(tempTemplateEl).getFirstByClass(selectorClasses.drop);
+ if (dropArea && !qq.DragAndDrop) {
+ log("DnD module unavailable.", "info");
+ qq(dropArea).remove();
+ }
+ if (!qq.supportedFeatures.fileDrop) {
+ uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
+ if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) {
+ qq(dropArea).css({
+ display: "none"
+ });
+ }
+ } else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) {
+ dropTextEl = qq(dropArea).getFirstByClass(selectorClasses.dropText);
+ dropTextEl && qq(dropTextEl).remove();
+ }
+ thumbnail = qq(tempTemplateEl).getFirstByClass(selectorClasses.thumbnail);
+ if (!showThumbnails) {
+ thumbnail && qq(thumbnail).remove();
+ } else if (thumbnail) {
+ thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR));
+ thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null;
+ serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR);
+ }
+ showThumbnails = showThumbnails && thumbnail;
+ isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0;
+ isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0;
+ fileListNode = qq(tempTemplateEl).getFirstByClass(selectorClasses.list);
+ if (fileListNode == null) {
+ throw new Error("Could not find the file list container in the template!");
+ }
+ fileListEl = fileListNode.children[0].cloneNode(true);
+ fileListNode.innerHTML = "";
+ if (tempTemplateEl.getElementsByTagName("DIALOG").length) {
+ document.createElement("dialog");
+ }
+ log("Template parsing complete");
+ return {
+ template: tempTemplateEl,
+ fileTemplate: fileListEl
+ };
+ }, prependFile = function(el, index, fileList) {
+ var parentEl = fileList, beforeEl = parentEl.firstChild;
+ if (index > 0) {
+ beforeEl = qq(parentEl).children()[index].nextSibling;
+ }
+ parentEl.insertBefore(el, beforeEl);
+ }, processNewQueuedPreviewRequest = function(queuedThumbRequest) {
+ var id = queuedThumbRequest.id, optFileOrBlob = queuedThumbRequest.optFileOrBlob, relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId, thumbnail = getThumbnail(id), spec = {
+ customResizeFunction: queuedThumbRequest.customResizeFunction,
+ maxSize: thumbnailMaxSize,
+ orient: true,
+ scale: true
+ };
+ if (qq.supportedFeatures.imagePreviews) {
+ if (thumbnail) {
+ if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
+ maybeSetDisplayNotAvailableImg(id, thumbnail);
+ generateNextQueuedPreview();
+ } else {
+ displayWaitingImg(thumbnail).done(function() {
+ previewGeneration[id] = new qq.Promise();
+ previewGeneration[id].done(function() {
+ setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
+ });
+ if (relatedThumbnailId != null) {
+ useCachedPreview(id, relatedThumbnailId);
+ } else {
+ generateNewPreview(id, optFileOrBlob, spec);
+ }
+ });
+ }
+ } else {
+ generateNextQueuedPreview();
+ }
+ } else if (thumbnail) {
+ displayWaitingImg(thumbnail);
+ generateNextQueuedPreview();
+ }
+ }, processUpdateQueuedPreviewRequest = function(queuedThumbRequest) {
+ var id = queuedThumbRequest.id, thumbnailUrl = queuedThumbRequest.thumbnailUrl, showWaitingImg = queuedThumbRequest.showWaitingImg, thumbnail = getThumbnail(id), spec = {
+ customResizeFunction: queuedThumbRequest.customResizeFunction,
+ scale: serverScale,
+ maxSize: thumbnailMaxSize
+ };
+ if (thumbnail) {
+ if (thumbnailUrl) {
+ if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
+ maybeSetDisplayNotAvailableImg(id, thumbnail);
+ generateNextQueuedPreview();
+ } else {
+ if (showWaitingImg) {
+ displayWaitingImg(thumbnail);
+ }
+ return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(function() {
+ show(thumbnail);
+ generatedThumbnails++;
+ setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
+ }, function() {
+ maybeSetDisplayNotAvailableImg(id, thumbnail);
+ setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
+ });
+ }
+ } else {
+ maybeSetDisplayNotAvailableImg(id, thumbnail);
+ generateNextQueuedPreview();
+ }
+ }
+ }, setProgressBarWidth = function(id, percent) {
+ var bar = getProgress(id), progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar;
+ if (bar && !qq(bar).hasClass(progressBarSelector)) {
+ bar = qq(bar).getFirstByClass(progressBarSelector);
+ }
+ if (bar) {
+ qq(bar).css({
+ width: percent + "%"
+ });
+ bar.setAttribute("aria-valuenow", percent);
+ }
+ }, show = function(el) {
+ el && qq(el).removeClass(options.classes.hide);
+ }, useCachedPreview = function(targetThumbnailId, cachedThumbnailId) {
+ var targetThumbnail = getThumbnail(targetThumbnailId), cachedThumbnail = getThumbnail(cachedThumbnailId);
+ log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId));
+ previewGeneration[cachedThumbnailId].then(function() {
+ generatedThumbnails++;
+ previewGeneration[targetThumbnailId].success();
+ log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId));
+ targetThumbnail.src = cachedThumbnail.src;
+ show(targetThumbnail);
+ }, function() {
+ previewGeneration[targetThumbnailId].failure();
+ if (!options.placeholders.waitUntilUpdate) {
+ maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumbnail);
+ }
+ });
+ };
+ qq.extend(options, spec);
+ log = options.log;
+ if (!qq.supportedFeatures.imagePreviews) {
+ options.limits.timeBetweenThumbs = 0;
+ options.limits.maxThumbs = 0;
+ }
+ container = options.containerEl;
+ showThumbnails = options.imageGenerator !== undefined;
+ templateDom = parseAndGetTemplate();
+ cacheThumbnailPlaceholders();
+ qq.extend(this, {
+ render: function() {
+ log("Rendering template in DOM.");
+ generatedThumbnails = 0;
+ container.appendChild(templateDom.template.cloneNode(true));
+ hide(getDropProcessing());
+ this.hideTotalProgress();
+ fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list);
+ log("Template rendering complete");
+ },
+ renderFailure: function(message) {
+ var cantRenderEl = qq.toElement(message);
+ container.innerHTML = "";
+ container.appendChild(cantRenderEl);
+ },
+ reset: function() {
+ this.render();
+ },
+ clearFiles: function() {
+ fileList.innerHTML = "";
+ },
+ disableCancel: function() {
+ isCancelDisabled = true;
+ },
+ addFile: function(id, name, prependInfo, hideForever, batch) {
+ var fileEl = templateDom.fileTemplate.cloneNode(true), fileNameEl = getTemplateEl(fileEl, selectorClasses.file), uploaderEl = getTemplateEl(container, selectorClasses.uploader), fileContainer = batch ? fileBatch.content : fileList, thumb;
+ if (batch) {
+ fileBatch.map[id] = fileEl;
+ }
+ qq(fileEl).addClass(FILE_CLASS_PREFIX + id);
+ uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
+ if (fileNameEl) {
+ qq(fileNameEl).setText(name);
+ fileNameEl.setAttribute("title", name);
+ }
+ fileEl.setAttribute(FILE_ID_ATTR, id);
+ if (prependInfo) {
+ prependFile(fileEl, prependInfo.index, fileContainer);
+ } else {
+ fileContainer.appendChild(fileEl);
+ }
+ if (hideForever) {
+ fileEl.style.display = "none";
+ qq(fileEl).addClass(HIDDEN_FOREVER_CLASS);
+ } else {
+ hide(getProgress(id));
+ hide(getSize(id));
+ hide(getDelete(id));
+ hide(getRetry(id));
+ hide(getPause(id));
+ hide(getContinue(id));
+ if (isCancelDisabled) {
+ this.hideCancel(id);
+ }
+ thumb = getThumbnail(id);
+ if (thumb && !thumb.src) {
+ cachedWaitingForThumbnailImg.then(function(waitingImg) {
+ thumb.src = waitingImg.src;
+ if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) {
+ qq(thumb).css({
+ maxHeight: waitingImg.style.maxHeight,
+ maxWidth: waitingImg.style.maxWidth
+ });
+ }
+ show(thumb);
+ });
+ }
+ }
+ },
+ addFileToCache: function(id, name, prependInfo, hideForever) {
+ this.addFile(id, name, prependInfo, hideForever, true);
+ },
+ addCacheToDom: function() {
+ fileList.appendChild(fileBatch.content);
+ fileBatch.content = document.createDocumentFragment();
+ fileBatch.map = {};
+ },
+ removeFile: function(id) {
+ qq(getFile(id)).remove();
+ },
+ getFileId: function(el) {
+ var currentNode = el;
+ if (currentNode) {
+ while (currentNode.getAttribute(FILE_ID_ATTR) == null) {
+ currentNode = currentNode.parentNode;
+ }
+ return parseInt(currentNode.getAttribute(FILE_ID_ATTR));
+ }
+ },
+ getFileList: function() {
+ return fileList;
+ },
+ markFilenameEditable: function(id) {
+ var filename = getFilename(id);
+ filename && qq(filename).addClass(options.classes.editable);
+ },
+ updateFilename: function(id, name) {
+ var filenameEl = getFilename(id);
+ if (filenameEl) {
+ qq(filenameEl).setText(name);
+ filenameEl.setAttribute("title", name);
+ }
+ },
+ hideFilename: function(id) {
+ hide(getFilename(id));
+ },
+ showFilename: function(id) {
+ show(getFilename(id));
+ },
+ isFileName: function(el) {
+ return qq(el).hasClass(selectorClasses.file);
+ },
+ getButton: function() {
+ return options.button || getTemplateEl(container, selectorClasses.button);
+ },
+ hideDropProcessing: function() {
+ hide(getDropProcessing());
+ },
+ showDropProcessing: function() {
+ show(getDropProcessing());
+ },
+ getDropZone: function() {
+ return getTemplateEl(container, selectorClasses.drop);
+ },
+ isEditFilenamePossible: function() {
+ return isEditElementsExist;
+ },
+ hideRetry: function(id) {
+ hide(getRetry(id));
+ },
+ isRetryPossible: function() {
+ return isRetryElementExist;
+ },
+ showRetry: function(id) {
+ show(getRetry(id));
+ },
+ getFileContainer: function(id) {
+ return getFile(id);
+ },
+ showEditIcon: function(id) {
+ var icon = getEditIcon(id);
+ icon && qq(icon).addClass(options.classes.editable);
+ },
+ isHiddenForever: function(id) {
+ return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS);
+ },
+ hideEditIcon: function(id) {
+ var icon = getEditIcon(id);
+ icon && qq(icon).removeClass(options.classes.editable);
+ },
+ isEditIcon: function(el) {
+ return qq(el).hasClass(selectorClasses.editNameIcon, true);
+ },
+ getEditInput: function(id) {
+ return getTemplateEl(getFile(id), selectorClasses.editFilenameInput);
+ },
+ isEditInput: function(el) {
+ return qq(el).hasClass(selectorClasses.editFilenameInput, true);
+ },
+ updateProgress: function(id, loaded, total) {
+ var bar = getProgress(id), percent;
+ if (bar && total > 0) {
+ percent = Math.round(loaded / total * 100);
+ if (percent === 100) {
+ hide(bar);
+ } else {
+ show(bar);
+ }
+ setProgressBarWidth(id, percent);
+ }
+ },
+ updateTotalProgress: function(loaded, total) {
+ this.updateProgress(null, loaded, total);
+ },
+ hideProgress: function(id) {
+ var bar = getProgress(id);
+ bar && hide(bar);
+ },
+ hideTotalProgress: function() {
+ this.hideProgress();
+ },
+ resetProgress: function(id) {
+ setProgressBarWidth(id, 0);
+ this.hideTotalProgress(id);
+ },
+ resetTotalProgress: function() {
+ this.resetProgress();
+ },
+ showCancel: function(id) {
+ if (!isCancelDisabled) {
+ var cancel = getCancel(id);
+ cancel && qq(cancel).removeClass(options.classes.hide);
+ }
+ },
+ hideCancel: function(id) {
+ hide(getCancel(id));
+ },
+ isCancel: function(el) {
+ return qq(el).hasClass(selectorClasses.cancel, true);
+ },
+ allowPause: function(id) {
+ show(getPause(id));
+ hide(getContinue(id));
+ },
+ uploadPaused: function(id) {
+ this.setStatusText(id, options.text.paused);
+ this.allowContinueButton(id);
+ hide(getSpinner(id));
+ },
+ hidePause: function(id) {
+ hide(getPause(id));
+ },
+ isPause: function(el) {
+ return qq(el).hasClass(selectorClasses.pause, true);
+ },
+ isContinueButton: function(el) {
+ return qq(el).hasClass(selectorClasses.continueButton, true);
+ },
+ allowContinueButton: function(id) {
+ show(getContinue(id));
+ hide(getPause(id));
+ },
+ uploadContinued: function(id) {
+ this.setStatusText(id, "");
+ this.allowPause(id);
+ show(getSpinner(id));
+ },
+ showDeleteButton: function(id) {
+ show(getDelete(id));
+ },
+ hideDeleteButton: function(id) {
+ hide(getDelete(id));
+ },
+ isDeleteButton: function(el) {
+ return qq(el).hasClass(selectorClasses.deleteButton, true);
+ },
+ isRetry: function(el) {
+ return qq(el).hasClass(selectorClasses.retry, true);
+ },
+ updateSize: function(id, text) {
+ var size = getSize(id);
+ if (size) {
+ show(size);
+ qq(size).setText(text);
+ }
+ },
+ setStatusText: function(id, text) {
+ var textEl = getTemplateEl(getFile(id), selectorClasses.statusText);
+ if (textEl) {
+ if (text == null) {
+ qq(textEl).clearText();
+ } else {
+ qq(textEl).setText(text);
+ }
+ }
+ },
+ hideSpinner: function(id) {
+ qq(getFile(id)).removeClass(IN_PROGRESS_CLASS);
+ hide(getSpinner(id));
+ },
+ showSpinner: function(id) {
+ qq(getFile(id)).addClass(IN_PROGRESS_CLASS);
+ show(getSpinner(id));
+ },
+ generatePreview: function(id, optFileOrBlob, customResizeFunction) {
+ if (!this.isHiddenForever(id)) {
+ thumbGenerationQueue.push({
+ id: id,
+ customResizeFunction: customResizeFunction,
+ optFileOrBlob: optFileOrBlob
+ });
+ !thumbnailQueueMonitorRunning && generateNextQueuedPreview();
+ }
+ },
+ updateThumbnail: function(id, thumbnailUrl, showWaitingImg, customResizeFunction) {
+ if (!this.isHiddenForever(id)) {
+ thumbGenerationQueue.push({
+ customResizeFunction: customResizeFunction,
+ update: true,
+ id: id,
+ thumbnailUrl: thumbnailUrl,
+ showWaitingImg: showWaitingImg
+ });
+ !thumbnailQueueMonitorRunning && generateNextQueuedPreview();
+ }
+ },
+ hasDialog: function(type) {
+ return qq.supportedFeatures.dialogElement && !!getDialog(type);
+ },
+ showDialog: function(type, message, defaultValue) {
+ var dialog = getDialog(type), messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage), inputEl = dialog.getElementsByTagName("INPUT")[0], cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton), okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton), promise = new qq.Promise(), closeHandler = function() {
+ cancelBtn.removeEventListener("click", cancelClickHandler);
+ okBtn && okBtn.removeEventListener("click", okClickHandler);
+ promise.failure();
+ }, cancelClickHandler = function() {
+ cancelBtn.removeEventListener("click", cancelClickHandler);
+ dialog.close();
+ }, okClickHandler = function() {
+ dialog.removeEventListener("close", closeHandler);
+ okBtn.removeEventListener("click", okClickHandler);
+ dialog.close();
+ promise.success(inputEl && inputEl.value);
+ };
+ dialog.addEventListener("close", closeHandler);
+ cancelBtn.addEventListener("click", cancelClickHandler);
+ okBtn && okBtn.addEventListener("click", okClickHandler);
+ if (inputEl) {
+ inputEl.value = defaultValue;
+ }
+ messageEl.textContent = message;
+ dialog.showModal();
+ return promise;
+ }
+ });
+ };
+ qq.UiEventHandler = function(s, protectedApi) {
+ "use strict";
+ var disposer = new qq.DisposeSupport(), spec = {
+ eventType: "click",
+ attachTo: null,
+ onHandled: function(target, event) {}
+ };
+ qq.extend(this, {
+ addHandler: function(element) {
+ addHandler(element);
+ },
+ dispose: function() {
+ disposer.dispose();
+ }
+ });
+ function addHandler(element) {
+ disposer.attach(element, spec.eventType, function(event) {
+ event = event || window.event;
+ var target = event.target || event.srcElement;
+ spec.onHandled(target, event);
+ });
+ }
+ qq.extend(protectedApi, {
+ getFileIdFromItem: function(item) {
+ return item.qqFileId;
+ },
+ getDisposeSupport: function() {
+ return disposer;
+ }
+ });
+ qq.extend(spec, s);
+ if (spec.attachTo) {
+ addHandler(spec.attachTo);
+ }
+ };
+ qq.FileButtonsClickHandler = function(s) {
+ "use strict";
+ var inheritedInternalApi = {}, spec = {
+ templating: null,
+ log: function(message, lvl) {},
+ onDeleteFile: function(fileId) {},
+ onCancel: function(fileId) {},
+ onRetry: function(fileId) {},
+ onPause: function(fileId) {},
+ onContinue: function(fileId) {},
+ onGetName: function(fileId) {}
+ }, buttonHandlers = {
+ cancel: function(id) {
+ spec.onCancel(id);
+ },
+ retry: function(id) {
+ spec.onRetry(id);
+ },
+ deleteButton: function(id) {
+ spec.onDeleteFile(id);
+ },
+ pause: function(id) {
+ spec.onPause(id);
+ },
+ continueButton: function(id) {
+ spec.onContinue(id);
+ }
+ };
+ function examineEvent(target, event) {
+ qq.each(buttonHandlers, function(buttonType, handler) {
+ var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId;
+ if (spec.templating["is" + firstLetterCapButtonType](target)) {
+ fileId = spec.templating.getFileId(target);
+ qq.preventDefault(event);
+ spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
+ handler(fileId);
+ return false;
+ }
+ });
+ }
+ qq.extend(spec, s);
+ spec.eventType = "click";
+ spec.onHandled = examineEvent;
+ spec.attachTo = spec.templating.getFileList();
+ qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
+ };
+ qq.FilenameClickHandler = function(s) {
+ "use strict";
+ var inheritedInternalApi = {}, spec = {
+ templating: null,
+ log: function(message, lvl) {},
+ classes: {
+ file: "qq-upload-file",
+ editNameIcon: "qq-edit-filename-icon"
+ },
+ onGetUploadStatus: function(fileId) {},
+ onGetName: function(fileId) {}
+ };
+ qq.extend(spec, s);
+ function examineEvent(target, event) {
+ if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {
+ var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId);
+ if (status === qq.status.SUBMITTED) {
+ spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
+ qq.preventDefault(event);
+ inheritedInternalApi.handleFilenameEdit(fileId, target, true);
+ }
+ }
+ }
+ spec.eventType = "click";
+ spec.onHandled = examineEvent;
+ qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
+ };
+ qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) {
+ "use strict";
+ var spec = {
+ templating: null,
+ onGetUploadStatus: function(fileId) {},
+ log: function(message, lvl) {}
+ };
+ if (!inheritedInternalApi) {
+ inheritedInternalApi = {};
+ }
+ function handleInputFocus(target, event) {
+ if (spec.templating.isEditInput(target)) {
+ var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId);
+ if (status === qq.status.SUBMITTED) {
+ spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
+ inheritedInternalApi.handleFilenameEdit(fileId, target);
+ }
+ }
+ }
+ spec.eventType = "focusin";
+ spec.onHandled = handleInputFocus;
+ qq.extend(spec, s);
+ qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
+ };
+ qq.FilenameInputFocusHandler = function(spec) {
+ "use strict";
+ spec.eventType = "focus";
+ spec.attachTo = null;
+ qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {}));
+ };
+ qq.FilenameEditHandler = function(s, inheritedInternalApi) {
+ "use strict";
+ var spec = {
+ templating: null,
+ log: function(message, lvl) {},
+ onGetUploadStatus: function(fileId) {},
+ onGetName: function(fileId) {},
+ onSetName: function(fileId, newName) {},
+ onEditingStatusChange: function(fileId, isEditing) {}
+ };
+ function getFilenameSansExtension(fileId) {
+ var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf(".");
+ if (extIdx > 0) {
+ filenameSansExt = filenameSansExt.substr(0, extIdx);
+ }
+ return filenameSansExt;
+ }
+ function getOriginalExtension(fileId) {
+ var origName = spec.onGetName(fileId);
+ return qq.getExtension(origName);
+ }
+ function handleNameUpdate(newFilenameInputEl, fileId) {
+ var newName = newFilenameInputEl.value, origExtension;
+ if (newName !== undefined && qq.trimStr(newName).length > 0) {
+ origExtension = getOriginalExtension(fileId);
+ if (origExtension !== undefined) {
+ newName = newName + "." + origExtension;
+ }
+ spec.onSetName(fileId, newName);
+ }
+ spec.onEditingStatusChange(fileId, false);
+ }
+ function registerInputBlurHandler(inputEl, fileId) {
+ inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() {
+ handleNameUpdate(inputEl, fileId);
+ });
+ }
+ function registerInputEnterKeyHandler(inputEl, fileId) {
+ inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) {
+ var code = event.keyCode || event.which;
+ if (code === 13) {
+ handleNameUpdate(inputEl, fileId);
+ }
+ });
+ }
+ qq.extend(spec, s);
+ spec.attachTo = spec.templating.getFileList();
+ qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
+ qq.extend(inheritedInternalApi, {
+ handleFilenameEdit: function(id, target, focusInput) {
+ var newFilenameInputEl = spec.templating.getEditInput(id);
+ spec.onEditingStatusChange(id, true);
+ newFilenameInputEl.value = getFilenameSansExtension(id);
+ if (focusInput) {
+ newFilenameInputEl.focus();
+ }
+ registerInputBlurHandler(newFilenameInputEl, id);
+ registerInputEnterKeyHandler(newFilenameInputEl, id);
+ }
+ });
+ };
+})(window);
+//# sourceMappingURL=fine-uploader.js.map
diff --git a/services/web/frontend/js/vendor/libs/jquery-layout.js b/services/web/frontend/js/vendor/libs/jquery-layout.js
new file mode 100644
index 0000000000..43ecc886c1
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/jquery-layout.js
@@ -0,0 +1,8503 @@
+/*! jQuery UI - v1.11.4 - 2016-02-10
+* http://jqueryui.com
+* Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js
+* Copyright jQuery Foundation and other contributors; Licensed MIT */
+
+/*!
+ * jQuery UI Core 1.11.4
+ * http://jqueryui.com
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/category/ui-core/
+ */
+
+
+// $.ui might exist from components with no dependencies, e.g., $.ui.position
+$.ui = $.ui || {};
+
+$.extend( $.ui, {
+ version: "1.11.4",
+
+ keyCode: {
+ BACKSPACE: 8,
+ COMMA: 188,
+ DELETE: 46,
+ DOWN: 40,
+ END: 35,
+ ENTER: 13,
+ ESCAPE: 27,
+ HOME: 36,
+ LEFT: 37,
+ PAGE_DOWN: 34,
+ PAGE_UP: 33,
+ PERIOD: 190,
+ RIGHT: 39,
+ SPACE: 32,
+ TAB: 9,
+ UP: 38
+ }
+});
+
+// plugins
+$.fn.extend({
+ scrollParent: function( includeHidden ) {
+ var position = this.css( "position" ),
+ excludeStaticParent = position === "absolute",
+ overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
+ scrollParent = this.parents().filter( function() {
+ var parent = $( this );
+ if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
+ return false;
+ }
+ return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
+ }).eq( 0 );
+
+ return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
+ },
+
+ uniqueId: (function() {
+ var uuid = 0;
+
+ return function() {
+ return this.each(function() {
+ if ( !this.id ) {
+ this.id = "ui-id-" + ( ++uuid );
+ }
+ });
+ };
+ })(),
+
+ removeUniqueId: function() {
+ return this.each(function() {
+ if ( /^ui-id-\d+$/.test( this.id ) ) {
+ $( this ).removeAttr( "id" );
+ }
+ });
+ }
+});
+
+// selectors
+function focusable( element, isTabIndexNotNaN ) {
+ var map, mapName, img,
+ nodeName = element.nodeName.toLowerCase();
+ if ( "area" === nodeName ) {
+ map = element.parentNode;
+ mapName = map.name;
+ if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
+ return false;
+ }
+ img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
+ return !!img && visible( img );
+ }
+ return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ?
+ !element.disabled :
+ "a" === nodeName ?
+ element.href || isTabIndexNotNaN :
+ isTabIndexNotNaN) &&
+ // the element and all of its ancestors must be visible
+ visible( element );
+}
+
+function visible( element ) {
+ return $.expr.filters.visible( element ) &&
+ !$( element ).parents().addBack().filter(function() {
+ return $.css( this, "visibility" ) === "hidden";
+ }).length;
+}
+
+$.extend( $.expr[ ":" ], {
+ data: $.expr.createPseudo ?
+ $.expr.createPseudo(function( dataName ) {
+ return function( elem ) {
+ return !!$.data( elem, dataName );
+ };
+ }) :
+ // support: jQuery <1.8
+ function( elem, i, match ) {
+ return !!$.data( elem, match[ 3 ] );
+ },
+
+ focusable: function( element ) {
+ return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
+ },
+
+ tabbable: function( element ) {
+ var tabIndex = $.attr( element, "tabindex" ),
+ isTabIndexNaN = isNaN( tabIndex );
+ return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
+ }
+});
+
+// support: jQuery <1.8
+if ( !$( "" ).outerWidth( 1 ).jquery ) {
+ $.each( [ "Width", "Height" ], function( i, name ) {
+ var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
+ type = name.toLowerCase(),
+ orig = {
+ innerWidth: $.fn.innerWidth,
+ innerHeight: $.fn.innerHeight,
+ outerWidth: $.fn.outerWidth,
+ outerHeight: $.fn.outerHeight
+ };
+
+ function reduce( elem, size, border, margin ) {
+ $.each( side, function() {
+ size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
+ if ( border ) {
+ size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
+ }
+ if ( margin ) {
+ size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
+ }
+ });
+ return size;
+ }
+
+ $.fn[ "inner" + name ] = function( size ) {
+ if ( size === undefined ) {
+ return orig[ "inner" + name ].call( this );
+ }
+
+ return this.each(function() {
+ $( this ).css( type, reduce( this, size ) + "px" );
+ });
+ };
+
+ $.fn[ "outer" + name] = function( size, margin ) {
+ if ( typeof size !== "number" ) {
+ return orig[ "outer" + name ].call( this, size );
+ }
+
+ return this.each(function() {
+ $( this).css( type, reduce( this, size, true, margin ) + "px" );
+ });
+ };
+ });
+}
+
+// support: jQuery <1.8
+if ( !$.fn.addBack ) {
+ $.fn.addBack = function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter( selector )
+ );
+ };
+}
+
+// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
+if ( $( " " ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
+ $.fn.removeData = (function( removeData ) {
+ return function( key ) {
+ if ( arguments.length ) {
+ return removeData.call( this, $.camelCase( key ) );
+ } else {
+ return removeData.call( this );
+ }
+ };
+ })( $.fn.removeData );
+}
+
+// deprecated
+$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
+
+$.fn.extend({
+ focus: (function( orig ) {
+ return function( delay, fn ) {
+ return typeof delay === "number" ?
+ this.each(function() {
+ var elem = this;
+ setTimeout(function() {
+ $( elem ).focus();
+ if ( fn ) {
+ fn.call( elem );
+ }
+ }, delay );
+ }) :
+ orig.apply( this, arguments );
+ };
+ })( $.fn.focus ),
+
+ disableSelection: (function() {
+ var eventType = "onselectstart" in document.createElement( "div" ) ?
+ "selectstart" :
+ "mousedown";
+
+ return function() {
+ return this.bind( eventType + ".ui-disableSelection", function( event ) {
+ event.preventDefault();
+ });
+ };
+ })(),
+
+ enableSelection: function() {
+ return this.unbind( ".ui-disableSelection" );
+ },
+
+ zIndex: function( zIndex ) {
+ if ( zIndex !== undefined ) {
+ return this.css( "zIndex", zIndex );
+ }
+
+ if ( this.length ) {
+ var elem = $( this[ 0 ] ), position, value;
+ while ( elem.length && elem[ 0 ] !== document ) {
+ // Ignore z-index if position is set to a value where z-index is ignored by the browser
+ // This makes behavior of this function consistent across browsers
+ // WebKit always returns auto if the element is positioned
+ position = elem.css( "position" );
+ if ( position === "absolute" || position === "relative" || position === "fixed" ) {
+ // IE returns 0 when zIndex is not specified
+ // other browsers return a string
+ // we ignore the case of nested elements with an explicit value of 0
+ //
+ value = parseInt( elem.css( "zIndex" ), 10 );
+ if ( !isNaN( value ) && value !== 0 ) {
+ return value;
+ }
+ }
+ elem = elem.parent();
+ }
+ }
+
+ return 0;
+ }
+});
+
+// $.ui.plugin is deprecated. Use $.widget() extensions instead.
+$.ui.plugin = {
+ add: function( module, option, set ) {
+ var i,
+ proto = $.ui[ module ].prototype;
+ for ( i in set ) {
+ proto.plugins[ i ] = proto.plugins[ i ] || [];
+ proto.plugins[ i ].push( [ option, set[ i ] ] );
+ }
+ },
+ call: function( instance, name, args, allowDisconnected ) {
+ var i,
+ set = instance.plugins[ name ];
+
+ if ( !set ) {
+ return;
+ }
+
+ if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
+ return;
+ }
+
+ for ( i = 0; i < set.length; i++ ) {
+ if ( instance.options[ set[ i ][ 0 ] ] ) {
+ set[ i ][ 1 ].apply( instance.element, args );
+ }
+ }
+ }
+};
+
+
+/*!
+ * jQuery UI Widget 1.11.4
+ * http://jqueryui.com
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/jQuery.widget/
+ */
+
+
+var widget_uuid = 0,
+ widget_slice = Array.prototype.slice;
+
+$.cleanData = (function( orig ) {
+ return function( elems ) {
+ var events, elem, i;
+ for ( i = 0; (elem = elems[i]) != null; i++ ) {
+ try {
+
+ // Only trigger remove when necessary to save time
+ events = $._data( elem, "events" );
+ if ( events && events.remove ) {
+ $( elem ).triggerHandler( "remove" );
+ }
+
+ // http://bugs.jquery.com/ticket/8235
+ } catch ( e ) {}
+ }
+ orig( elems );
+ };
+})( $.cleanData );
+
+$.widget = function( name, base, prototype ) {
+ var fullName, existingConstructor, constructor, basePrototype,
+ // proxiedPrototype allows the provided prototype to remain unmodified
+ // so that it can be used as a mixin for multiple widgets (#8876)
+ proxiedPrototype = {},
+ namespace = name.split( "." )[ 0 ];
+
+ name = name.split( "." )[ 1 ];
+ fullName = namespace + "-" + name;
+
+ if ( !prototype ) {
+ prototype = base;
+ base = $.Widget;
+ }
+
+ // create selector for plugin
+ $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
+ return !!$.data( elem, fullName );
+ };
+
+ $[ namespace ] = $[ namespace ] || {};
+ existingConstructor = $[ namespace ][ name ];
+ constructor = $[ namespace ][ name ] = function( options, element ) {
+ // allow instantiation without "new" keyword
+ if ( !this._createWidget ) {
+ return new constructor( options, element );
+ }
+
+ // allow instantiation without initializing for simple inheritance
+ // must use "new" keyword (the code above always passes args)
+ if ( arguments.length ) {
+ this._createWidget( options, element );
+ }
+ };
+ // extend with the existing constructor to carry over any static properties
+ $.extend( constructor, existingConstructor, {
+ version: prototype.version,
+ // copy the object used to create the prototype in case we need to
+ // redefine the widget later
+ _proto: $.extend( {}, prototype ),
+ // track widgets that inherit from this widget in case this widget is
+ // redefined after a widget inherits from it
+ _childConstructors: []
+ });
+
+ basePrototype = new base();
+ // we need to make the options hash a property directly on the new instance
+ // otherwise we'll modify the options hash on the prototype that we're
+ // inheriting from
+ basePrototype.options = $.widget.extend( {}, basePrototype.options );
+ $.each( prototype, function( prop, value ) {
+ if ( !$.isFunction( value ) ) {
+ proxiedPrototype[ prop ] = value;
+ return;
+ }
+ proxiedPrototype[ prop ] = (function() {
+ var _super = function() {
+ return base.prototype[ prop ].apply( this, arguments );
+ },
+ _superApply = function( args ) {
+ return base.prototype[ prop ].apply( this, args );
+ };
+ return function() {
+ var __super = this._super,
+ __superApply = this._superApply,
+ returnValue;
+
+ this._super = _super;
+ this._superApply = _superApply;
+
+ returnValue = value.apply( this, arguments );
+
+ this._super = __super;
+ this._superApply = __superApply;
+
+ return returnValue;
+ };
+ })();
+ });
+ constructor.prototype = $.widget.extend( basePrototype, {
+ // TODO: remove support for widgetEventPrefix
+ // always use the name + a colon as the prefix, e.g., draggable:start
+ // don't prefix for widgets that aren't DOM-based
+ widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
+ }, proxiedPrototype, {
+ constructor: constructor,
+ namespace: namespace,
+ widgetName: name,
+ widgetFullName: fullName
+ });
+
+ // If this widget is being redefined then we need to find all widgets that
+ // are inheriting from it and redefine all of them so that they inherit from
+ // the new version of this widget. We're essentially trying to replace one
+ // level in the prototype chain.
+ if ( existingConstructor ) {
+ $.each( existingConstructor._childConstructors, function( i, child ) {
+ var childPrototype = child.prototype;
+
+ // redefine the child widget using the same prototype that was
+ // originally used, but inherit from the new version of the base
+ $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
+ });
+ // remove the list of existing child constructors from the old constructor
+ // so the old child constructors can be garbage collected
+ delete existingConstructor._childConstructors;
+ } else {
+ base._childConstructors.push( constructor );
+ }
+
+ $.widget.bridge( name, constructor );
+
+ return constructor;
+};
+
+$.widget.extend = function( target ) {
+ var input = widget_slice.call( arguments, 1 ),
+ inputIndex = 0,
+ inputLength = input.length,
+ key,
+ value;
+ for ( ; inputIndex < inputLength; inputIndex++ ) {
+ for ( key in input[ inputIndex ] ) {
+ value = input[ inputIndex ][ key ];
+ if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
+ // Clone objects
+ if ( $.isPlainObject( value ) ) {
+ target[ key ] = $.isPlainObject( target[ key ] ) ?
+ $.widget.extend( {}, target[ key ], value ) :
+ // Don't extend strings, arrays, etc. with objects
+ $.widget.extend( {}, value );
+ // Copy everything else by reference
+ } else {
+ target[ key ] = value;
+ }
+ }
+ }
+ }
+ return target;
+};
+
+$.widget.bridge = function( name, object ) {
+ var fullName = object.prototype.widgetFullName || name;
+ $.fn[ name ] = function( options ) {
+ var isMethodCall = typeof options === "string",
+ args = widget_slice.call( arguments, 1 ),
+ returnValue = this;
+
+ if ( isMethodCall ) {
+ this.each(function() {
+ var methodValue,
+ instance = $.data( this, fullName );
+ if ( options === "instance" ) {
+ returnValue = instance;
+ return false;
+ }
+ if ( !instance ) {
+ return $.error( "cannot call methods on " + name + " prior to initialization; " +
+ "attempted to call method '" + options + "'" );
+ }
+ if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
+ return $.error( "no such method '" + options + "' for " + name + " widget instance" );
+ }
+ methodValue = instance[ options ].apply( instance, args );
+ if ( methodValue !== instance && methodValue !== undefined ) {
+ returnValue = methodValue && methodValue.jquery ?
+ returnValue.pushStack( methodValue.get() ) :
+ methodValue;
+ return false;
+ }
+ });
+ } else {
+
+ // Allow multiple hashes to be passed on init
+ if ( args.length ) {
+ options = $.widget.extend.apply( null, [ options ].concat(args) );
+ }
+
+ this.each(function() {
+ var instance = $.data( this, fullName );
+ if ( instance ) {
+ instance.option( options || {} );
+ if ( instance._init ) {
+ instance._init();
+ }
+ } else {
+ $.data( this, fullName, new object( options, this ) );
+ }
+ });
+ }
+
+ return returnValue;
+ };
+};
+
+$.Widget = function( /* options, element */ ) {};
+$.Widget._childConstructors = [];
+
+$.Widget.prototype = {
+ widgetName: "widget",
+ widgetEventPrefix: "",
+ defaultElement: "",
+ options: {
+ disabled: false,
+
+ // callbacks
+ create: null
+ },
+ _createWidget: function( options, element ) {
+ element = $( element || this.defaultElement || this )[ 0 ];
+ this.element = $( element );
+ this.uuid = widget_uuid++;
+ this.eventNamespace = "." + this.widgetName + this.uuid;
+
+ this.bindings = $();
+ this.hoverable = $();
+ this.focusable = $();
+
+ if ( element !== this ) {
+ $.data( element, this.widgetFullName, this );
+ this._on( true, this.element, {
+ remove: function( event ) {
+ if ( event.target === element ) {
+ this.destroy();
+ }
+ }
+ });
+ this.document = $( element.style ?
+ // element within the document
+ element.ownerDocument :
+ // element is window or document
+ element.document || element );
+ this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
+ }
+
+ this.options = $.widget.extend( {},
+ this.options,
+ this._getCreateOptions(),
+ options );
+
+ this._create();
+ this._trigger( "create", null, this._getCreateEventData() );
+ this._init();
+ },
+ _getCreateOptions: $.noop,
+ _getCreateEventData: $.noop,
+ _create: $.noop,
+ _init: $.noop,
+
+ destroy: function() {
+ this._destroy();
+ // we can probably remove the unbind calls in 2.0
+ // all event bindings should go through this._on()
+ this.element
+ .unbind( this.eventNamespace )
+ .removeData( this.widgetFullName )
+ // support: jquery <1.6.3
+ // http://bugs.jquery.com/ticket/9413
+ .removeData( $.camelCase( this.widgetFullName ) );
+ this.widget()
+ .unbind( this.eventNamespace )
+ .removeAttr( "aria-disabled" )
+ .removeClass(
+ this.widgetFullName + "-disabled " +
+ "ui-state-disabled" );
+
+ // clean up events and states
+ this.bindings.unbind( this.eventNamespace );
+ this.hoverable.removeClass( "ui-state-hover" );
+ this.focusable.removeClass( "ui-state-focus" );
+ },
+ _destroy: $.noop,
+
+ widget: function() {
+ return this.element;
+ },
+
+ option: function( key, value ) {
+ var options = key,
+ parts,
+ curOption,
+ i;
+
+ if ( arguments.length === 0 ) {
+ // don't return a reference to the internal hash
+ return $.widget.extend( {}, this.options );
+ }
+
+ if ( typeof key === "string" ) {
+ // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
+ options = {};
+ parts = key.split( "." );
+ key = parts.shift();
+ if ( parts.length ) {
+ curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
+ for ( i = 0; i < parts.length - 1; i++ ) {
+ curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
+ curOption = curOption[ parts[ i ] ];
+ }
+ key = parts.pop();
+ if ( arguments.length === 1 ) {
+ return curOption[ key ] === undefined ? null : curOption[ key ];
+ }
+ curOption[ key ] = value;
+ } else {
+ if ( arguments.length === 1 ) {
+ return this.options[ key ] === undefined ? null : this.options[ key ];
+ }
+ options[ key ] = value;
+ }
+ }
+
+ this._setOptions( options );
+
+ return this;
+ },
+ _setOptions: function( options ) {
+ var key;
+
+ for ( key in options ) {
+ this._setOption( key, options[ key ] );
+ }
+
+ return this;
+ },
+ _setOption: function( key, value ) {
+ this.options[ key ] = value;
+
+ if ( key === "disabled" ) {
+ this.widget()
+ .toggleClass( this.widgetFullName + "-disabled", !!value );
+
+ // If the widget is becoming disabled, then nothing is interactive
+ if ( value ) {
+ this.hoverable.removeClass( "ui-state-hover" );
+ this.focusable.removeClass( "ui-state-focus" );
+ }
+ }
+
+ return this;
+ },
+
+ enable: function() {
+ return this._setOptions({ disabled: false });
+ },
+ disable: function() {
+ return this._setOptions({ disabled: true });
+ },
+
+ _on: function( suppressDisabledCheck, element, handlers ) {
+ var delegateElement,
+ instance = this;
+
+ // no suppressDisabledCheck flag, shuffle arguments
+ if ( typeof suppressDisabledCheck !== "boolean" ) {
+ handlers = element;
+ element = suppressDisabledCheck;
+ suppressDisabledCheck = false;
+ }
+
+ // no element argument, shuffle and use this.element
+ if ( !handlers ) {
+ handlers = element;
+ element = this.element;
+ delegateElement = this.widget();
+ } else {
+ element = delegateElement = $( element );
+ this.bindings = this.bindings.add( element );
+ }
+
+ $.each( handlers, function( event, handler ) {
+ function handlerProxy() {
+ // allow widgets to customize the disabled handling
+ // - disabled as an array instead of boolean
+ // - disabled class as method for disabling individual parts
+ if ( !suppressDisabledCheck &&
+ ( instance.options.disabled === true ||
+ $( this ).hasClass( "ui-state-disabled" ) ) ) {
+ return;
+ }
+ return ( typeof handler === "string" ? instance[ handler ] : handler )
+ .apply( instance, arguments );
+ }
+
+ // copy the guid so direct unbinding works
+ if ( typeof handler !== "string" ) {
+ handlerProxy.guid = handler.guid =
+ handler.guid || handlerProxy.guid || $.guid++;
+ }
+
+ var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
+ eventName = match[1] + instance.eventNamespace,
+ selector = match[2];
+ if ( selector ) {
+ delegateElement.delegate( selector, eventName, handlerProxy );
+ } else {
+ element.bind( eventName, handlerProxy );
+ }
+ });
+ },
+
+ _off: function( element, eventName ) {
+ eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
+ this.eventNamespace;
+ element.unbind( eventName ).undelegate( eventName );
+
+ // Clear the stack to avoid memory leaks (#10056)
+ this.bindings = $( this.bindings.not( element ).get() );
+ this.focusable = $( this.focusable.not( element ).get() );
+ this.hoverable = $( this.hoverable.not( element ).get() );
+ },
+
+ _delay: function( handler, delay ) {
+ function handlerProxy() {
+ return ( typeof handler === "string" ? instance[ handler ] : handler )
+ .apply( instance, arguments );
+ }
+ var instance = this;
+ return setTimeout( handlerProxy, delay || 0 );
+ },
+
+ _hoverable: function( element ) {
+ this.hoverable = this.hoverable.add( element );
+ this._on( element, {
+ mouseenter: function( event ) {
+ $( event.currentTarget ).addClass( "ui-state-hover" );
+ },
+ mouseleave: function( event ) {
+ $( event.currentTarget ).removeClass( "ui-state-hover" );
+ }
+ });
+ },
+
+ _focusable: function( element ) {
+ this.focusable = this.focusable.add( element );
+ this._on( element, {
+ focusin: function( event ) {
+ $( event.currentTarget ).addClass( "ui-state-focus" );
+ },
+ focusout: function( event ) {
+ $( event.currentTarget ).removeClass( "ui-state-focus" );
+ }
+ });
+ },
+
+ _trigger: function( type, event, data ) {
+ var prop, orig,
+ callback = this.options[ type ];
+
+ data = data || {};
+ event = $.Event( event );
+ event.type = ( type === this.widgetEventPrefix ?
+ type :
+ this.widgetEventPrefix + type ).toLowerCase();
+ // the original event may come from any element
+ // so we need to reset the target on the new event
+ event.target = this.element[ 0 ];
+
+ // copy original event properties over to the new event
+ orig = event.originalEvent;
+ if ( orig ) {
+ for ( prop in orig ) {
+ if ( !( prop in event ) ) {
+ event[ prop ] = orig[ prop ];
+ }
+ }
+ }
+
+ this.element.trigger( event, data );
+ return !( $.isFunction( callback ) &&
+ callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
+ event.isDefaultPrevented() );
+ }
+};
+
+$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
+ $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
+ if ( typeof options === "string" ) {
+ options = { effect: options };
+ }
+ var hasOptions,
+ effectName = !options ?
+ method :
+ options === true || typeof options === "number" ?
+ defaultEffect :
+ options.effect || defaultEffect;
+ options = options || {};
+ if ( typeof options === "number" ) {
+ options = { duration: options };
+ }
+ hasOptions = !$.isEmptyObject( options );
+ options.complete = callback;
+ if ( options.delay ) {
+ element.delay( options.delay );
+ }
+ if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
+ element[ method ]( options );
+ } else if ( effectName !== method && element[ effectName ] ) {
+ element[ effectName ]( options.duration, options.easing, callback );
+ } else {
+ element.queue(function( next ) {
+ $( this )[ method ]();
+ if ( callback ) {
+ callback.call( element[ 0 ] );
+ }
+ next();
+ });
+ }
+ };
+});
+
+var widget = $.widget;
+
+
+/*!
+ * jQuery UI Mouse 1.11.4
+ * http://jqueryui.com
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/mouse/
+ */
+
+
+var mouseHandled = false;
+$( document ).mouseup( function() {
+ mouseHandled = false;
+});
+
+var mouse = $.widget("ui.mouse", {
+ version: "1.11.4",
+ options: {
+ cancel: "input,textarea,button,select,option",
+ distance: 1,
+ delay: 0
+ },
+ _mouseInit: function() {
+ var that = this;
+
+ this.element
+ .bind("mousedown." + this.widgetName, function(event) {
+ return that._mouseDown(event);
+ })
+ .bind("click." + this.widgetName, function(event) {
+ if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, that.widgetName + ".preventClickEvent");
+ event.stopImmediatePropagation();
+ return false;
+ }
+ });
+
+ this.started = false;
+ },
+
+ // TODO: make sure destroying one instance of mouse doesn't mess with
+ // other instances of mouse
+ _mouseDestroy: function() {
+ this.element.unbind("." + this.widgetName);
+ if ( this._mouseMoveDelegate ) {
+ this.document
+ .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
+ .unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
+ }
+ },
+
+ _mouseDown: function(event) {
+ // don't let more than one widget handle mouseStart
+ if ( mouseHandled ) {
+ return;
+ }
+
+ this._mouseMoved = false;
+
+ // we may have missed mouseup (out of window)
+ (this._mouseStarted && this._mouseUp(event));
+
+ this._mouseDownEvent = event;
+
+ var that = this,
+ btnIsLeft = (event.which === 1),
+ // event.target.nodeName works around a bug in IE 8 with
+ // disabled inputs (#7620)
+ elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
+ if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
+ return true;
+ }
+
+ this.mouseDelayMet = !this.options.delay;
+ if (!this.mouseDelayMet) {
+ this._mouseDelayTimer = setTimeout(function() {
+ that.mouseDelayMet = true;
+ }, this.options.delay);
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted = (this._mouseStart(event) !== false);
+ if (!this._mouseStarted) {
+ event.preventDefault();
+ return true;
+ }
+ }
+
+ // Click event may never have fired (Gecko & Opera)
+ if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, this.widgetName + ".preventClickEvent");
+ }
+
+ // these delegates are required to keep context
+ this._mouseMoveDelegate = function(event) {
+ return that._mouseMove(event);
+ };
+ this._mouseUpDelegate = function(event) {
+ return that._mouseUp(event);
+ };
+
+ this.document
+ .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
+ .bind( "mouseup." + this.widgetName, this._mouseUpDelegate );
+
+ event.preventDefault();
+
+ mouseHandled = true;
+ return true;
+ },
+
+ _mouseMove: function(event) {
+ // Only check for mouseups outside the document if you've moved inside the document
+ // at least once. This prevents the firing of mouseup in the case of IE<9, which will
+ // fire a mousemove event if content is placed under the cursor. See #7778
+ // Support: IE <9
+ if ( this._mouseMoved ) {
+ // IE mouseup check - mouseup happened when mouse was out of window
+ if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
+ return this._mouseUp(event);
+
+ // Iframe mouseup check - mouseup occurred in another document
+ } else if ( !event.which ) {
+ return this._mouseUp( event );
+ }
+ }
+
+ if ( event.which || event.button ) {
+ this._mouseMoved = true;
+ }
+
+ if (this._mouseStarted) {
+ this._mouseDrag(event);
+ return event.preventDefault();
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted =
+ (this._mouseStart(this._mouseDownEvent, event) !== false);
+ (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
+ }
+
+ return !this._mouseStarted;
+ },
+
+ _mouseUp: function(event) {
+ this.document
+ .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
+ .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate );
+
+ if (this._mouseStarted) {
+ this._mouseStarted = false;
+
+ if (event.target === this._mouseDownEvent.target) {
+ $.data(event.target, this.widgetName + ".preventClickEvent", true);
+ }
+
+ this._mouseStop(event);
+ }
+
+ mouseHandled = false;
+ return false;
+ },
+
+ _mouseDistanceMet: function(event) {
+ return (Math.max(
+ Math.abs(this._mouseDownEvent.pageX - event.pageX),
+ Math.abs(this._mouseDownEvent.pageY - event.pageY)
+ ) >= this.options.distance
+ );
+ },
+
+ _mouseDelayMet: function(/* event */) {
+ return this.mouseDelayMet;
+ },
+
+ // These are placeholder methods, to be overriden by extending plugin
+ _mouseStart: function(/* event */) {},
+ _mouseDrag: function(/* event */) {},
+ _mouseStop: function(/* event */) {},
+ _mouseCapture: function(/* event */) { return true; }
+});
+
+
+/*!
+ * jQuery UI Draggable 1.11.4
+ * http://jqueryui.com
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/draggable/
+ */
+
+
+$.widget("ui.draggable", $.ui.mouse, {
+ version: "1.11.4",
+ widgetEventPrefix: "drag",
+ options: {
+ addClasses: true,
+ appendTo: "parent",
+ axis: false,
+ connectToSortable: false,
+ containment: false,
+ cursor: "auto",
+ cursorAt: false,
+ grid: false,
+ handle: false,
+ helper: "original",
+ iframeFix: false,
+ opacity: false,
+ refreshPositions: false,
+ revert: false,
+ revertDuration: 500,
+ scope: "default",
+ scroll: true,
+ scrollSensitivity: 20,
+ scrollSpeed: 20,
+ snap: false,
+ snapMode: "both",
+ snapTolerance: 20,
+ stack: false,
+ zIndex: false,
+
+ // callbacks
+ drag: null,
+ start: null,
+ stop: null
+ },
+ _create: function() {
+
+ if ( this.options.helper === "original" ) {
+ this._setPositionRelative();
+ }
+ if (this.options.addClasses){
+ this.element.addClass("ui-draggable");
+ }
+ if (this.options.disabled){
+ this.element.addClass("ui-draggable-disabled");
+ }
+ this._setHandleClassName();
+
+ this._mouseInit();
+ },
+
+ _setOption: function( key, value ) {
+ this._super( key, value );
+ if ( key === "handle" ) {
+ this._removeHandleClassName();
+ this._setHandleClassName();
+ }
+ },
+
+ _destroy: function() {
+ if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
+ this.destroyOnClear = true;
+ return;
+ }
+ this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
+ this._removeHandleClassName();
+ this._mouseDestroy();
+ },
+
+ _mouseCapture: function(event) {
+ var o = this.options;
+
+ this._blurActiveElement( event );
+
+ // among others, prevent a drag on a resizable-handle
+ if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
+ return false;
+ }
+
+ //Quit if we're not on a valid handle
+ this.handle = this._getHandle(event);
+ if (!this.handle) {
+ return false;
+ }
+
+ this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );
+
+ return true;
+
+ },
+
+ _blockFrames: function( selector ) {
+ this.iframeBlocks = this.document.find( selector ).map(function() {
+ var iframe = $( this );
+
+ return $( "
" )
+ .css( "position", "absolute" )
+ .appendTo( iframe.parent() )
+ .outerWidth( iframe.outerWidth() )
+ .outerHeight( iframe.outerHeight() )
+ .offset( iframe.offset() )[ 0 ];
+ });
+ },
+
+ _unblockFrames: function() {
+ if ( this.iframeBlocks ) {
+ this.iframeBlocks.remove();
+ delete this.iframeBlocks;
+ }
+ },
+
+ _blurActiveElement: function( event ) {
+ var document = this.document[ 0 ];
+
+ // Only need to blur if the event occurred on the draggable itself, see #10527
+ if ( !this.handleElement.is( event.target ) ) {
+ return;
+ }
+
+ // support: IE9
+ // IE9 throws an "Unspecified error" accessing document.activeElement from an
').appendTo("body");
+ var d = { width: $c.css("width") - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight };
+ $c.remove();
+ window.scrollbarWidth = d.width;
+ window.scrollbarHeight = d.height;
+ return dim.match(/^(width|height)$/) ? d[dim] : d;
+ }
+
+
+ /**
+ * Returns hash container 'display' and 'visibility'
+ *
+ * @see $.swap() - swaps CSS, runs callback, resets CSS
+ * @param {!Object} $E jQuery element
+ * @param {boolean=} [force=false] Run even if display != none
+ * @return {!Object} Returns current style props, if applicable
+ */
+, showInvisibly: function ($E, force) {
+ if ($E && $E.length && (force || $E.css("display") === "none")) { // only if not *already hidden*
+ var s = $E[0].style
+ // save ONLY the 'style' props because that is what we must restore
+ , CSS = { display: s.display || '', visibility: s.visibility || '' };
+ // show element 'invisibly' so can be measured
+ $E.css({ display: "block", visibility: "hidden" });
+ return CSS;
+ }
+ return {};
+ }
+
+ /**
+ * Returns data for setting size of an element (container or a pane).
+ *
+ * @see _create(), onWindowResize() for container, plus others for pane
+ * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc
+ */
+, getElementDimensions: function ($E, inset) {
+ var
+ // dimensions hash - start with current data IF passed
+ d = { css: {}, inset: {} }
+ , x = d.css // CSS hash
+ , i = { bottom: 0 } // TEMP insets (bottom = complier hack)
+ , N = $.layout.cssNum
+ , off = $E.offset()
+ , b, p, ei // TEMP border, padding
+ ;
+ d.offsetLeft = off.left;
+ d.offsetTop = off.top;
+
+ if (!inset) inset = {}; // simplify logic below
+
+ $.each("Left,Right,Top,Bottom".split(","), function (idx, e) { // e = edge
+ b = x["border" + e] = $.layout.borderWidth($E, e);
+ p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e);
+ ei = e.toLowerCase();
+ d.inset[ei] = inset[ei] >= 0 ? inset[ei] : p; // any missing insetX value = paddingX
+ i[ei] = d.inset[ei] + b; // total offset of content from outer side
+ });
+
+ x.width = $E.width();
+ x.height = $E.height();
+ x.top = N($E,"top",true);
+ x.bottom = N($E,"bottom",true);
+ x.left = N($E,"left",true);
+ x.right = N($E,"right",true);
+
+ d.outerWidth = $E.outerWidth();
+ d.outerHeight = $E.outerHeight();
+ // calc the TRUE inner-dimensions, even in quirks-mode!
+ d.innerWidth = max(0, d.outerWidth - i.left - i.right);
+ d.innerHeight = max(0, d.outerHeight - i.top - i.bottom);
+ // layoutWidth/Height is used in calcs for manual resizing
+ // layoutW/H only differs from innerW/H when in quirks-mode - then is like outerW/H
+ d.layoutWidth = $E.innerWidth();
+ d.layoutHeight = $E.innerHeight();
+
+ //if ($E.prop('tagName') === 'BODY') { debugData( d, $E.prop('tagName') ); } // DEBUG
+
+ //d.visible = $E.is(":visible");// && x.width > 0 && x.height > 0;
+
+ return d;
+ }
+
+, getElementStyles: function ($E, list) {
+ var
+ CSS = {}
+ , style = $E[0].style
+ , props = list.split(",")
+ , sides = "Top,Bottom,Left,Right".split(",")
+ , attrs = "Color,Style,Width".split(",")
+ , p, s, a, i, j, k
+ ;
+ for (i=0; i < props.length; i++) {
+ p = props[i];
+ if (p.match(/(border|padding|margin)$/))
+ for (j=0; j < 4; j++) {
+ s = sides[j];
+ if (p === "border")
+ for (k=0; k < 3; k++) {
+ a = attrs[k];
+ CSS[p+s+a] = style[p+s+a];
+ }
+ else
+ CSS[p+s] = style[p+s];
+ }
+ else
+ CSS[p] = style[p];
+ };
+ return CSS
+ }
+
+ /**
+ * Return the innerWidth for the current browser/doctype
+ *
+ * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles()
+ * @param {Array.
} $E Must pass a jQuery object - first element is processed
+ * @param {number=} outerWidth (optional) Can pass a width, allowing calculations BEFORE element is resized
+ * @return {number} Returns the innerWidth of the elem by subtracting padding and borders
+ */
+, cssWidth: function ($E, outerWidth) {
+ // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
+ if (outerWidth <= 0) return 0;
+
+ var bs = !$.layout.browser.boxModel ? "border-box" : $.support.boxSizing ? $E.css("boxSizing") : "content-box"
+ , b = $.layout.borderWidth
+ , n = $.layout.cssNum
+ , W = outerWidth
+ ;
+ // strip border and/or padding from outerWidth to get CSS Width
+ if (bs !== "border-box")
+ W -= (b($E, "Left") + b($E, "Right"));
+ if (bs === "content-box")
+ W -= (n($E, "paddingLeft") + n($E, "paddingRight"));
+ return max(0,W);
+ }
+
+ /**
+ * Return the innerHeight for the current browser/doctype
+ *
+ * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles()
+ * @param {Array.} $E Must pass a jQuery object - first element is processed
+ * @param {number=} outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized
+ * @return {number} Returns the innerHeight of the elem by subtracting padding and borders
+ */
+, cssHeight: function ($E, outerHeight) {
+ // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
+ if (outerHeight <= 0) return 0;
+
+ var bs = !$.layout.browser.boxModel ? "border-box" : $.support.boxSizing ? $E.css("boxSizing") : "content-box"
+ , b = $.layout.borderWidth
+ , n = $.layout.cssNum
+ , H = outerHeight
+ ;
+ // strip border and/or padding from outerHeight to get CSS Height
+ if (bs !== "border-box")
+ H -= (b($E, "Top") + b($E, "Bottom"));
+ if (bs === "content-box")
+ H -= (n($E, "paddingTop") + n($E, "paddingBottom"));
+ return max(0,H);
+ }
+
+ /**
+ * Returns the 'current CSS numeric value' for a CSS property - 0 if property does not exist
+ *
+ * @see Called by many methods
+ * @param {Array.} $E Must pass a jQuery object - first element is processed
+ * @param {string} prop The name of the CSS property, eg: top, width, etc.
+ * @param {boolean=} [allowAuto=false] true = return 'auto' if that is value; false = return 0
+ * @return {(string|number)} Usually used to get an integer value for position (top, left) or size (height, width)
+ */
+, cssNum: function ($E, prop, allowAuto) {
+ if (!$E.jquery) $E = $($E);
+ var CSS = $.layout.showInvisibly($E)
+ , p = $.css($E[0], prop, true)
+ , v = allowAuto && p=="auto" ? p : Math.round(parseFloat(p) || 0);
+ $E.css( CSS ); // RESET
+ return v;
+ }
+
+, borderWidth: function (el, side) {
+ if (el.jquery) el = el[0];
+ var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left
+ return $.css(el, b+"Style", true) === "none" ? 0 : Math.round(parseFloat($.css(el, b+"Width", true)) || 0);
+ }
+
+ /**
+ * Mouse-tracking utility - FUTURE REFERENCE
+ *
+ * init: if (!window.mouse) {
+ * window.mouse = { x: 0, y: 0 };
+ * $(document).mousemove( $.layout.trackMouse );
+ * }
+ *
+ * @param {Object} evt
+ *
+, trackMouse: function (evt) {
+ window.mouse = { x: evt.clientX, y: evt.clientY };
+ }
+ */
+
+ /**
+ * SUBROUTINE for preventPrematureSlideClose option
+ *
+ * @param {Object} evt
+ * @param {Object=} el
+ */
+, isMouseOverElem: function (evt, el) {
+ var
+ $E = $(el || this)
+ , d = $E.offset()
+ , T = d.top
+ , L = d.left
+ , R = L + $E.outerWidth()
+ , B = T + $E.outerHeight()
+ , x = evt.pageX // evt.clientX ?
+ , y = evt.pageY // evt.clientY ?
+ ;
+ // if X & Y are < 0, probably means is over an open SELECT
+ return ($.layout.browser.msie && x < 0 && y < 0) || ((x >= L && x <= R) && (y >= T && y <= B));
+ }
+
+ /**
+ * Message/Logging Utility
+ *
+ * @example $.layout.msg("My message"); // log text
+ * @example $.layout.msg("My message", true); // alert text
+ * @example $.layout.msg({ foo: "bar" }, "Title"); // log hash-data, with custom title
+ * @example $.layout.msg({ foo: "bar" }, true, "Title", { sort: false }); -OR-
+ * @example $.layout.msg({ foo: "bar" }, "Title", { sort: false, display: true }); // alert hash-data
+ *
+ * @param {(Object|string)} info String message OR Hash/Array
+ * @param {(Boolean|string|Object)=} [popup=false] True means alert-box - can be skipped
+ * @param {(Object|string)=} [debugTitle=""] Title for Hash data - can be skipped
+ * @param {Object=} [debugOpts] Extra options for debug output
+ */
+, msg: function (info, popup, debugTitle, debugOpts) {
+ if ($.isPlainObject(info) && window.debugData) {
+ if (typeof popup === "string") {
+ debugOpts = debugTitle;
+ debugTitle = popup;
+ }
+ else if (typeof debugTitle === "object") {
+ debugOpts = debugTitle;
+ debugTitle = null;
+ }
+ var t = debugTitle || "log( )"
+ , o = $.extend({ sort: false, returnHTML: false, display: false }, debugOpts);
+ if (popup === true || o.display)
+ debugData( info, t, o );
+ else if (window.console)
+ console.log(debugData( info, t, o ));
+ }
+ else if (popup)
+ alert(info);
+ else if (window.console)
+ console.log(info);
+ else {
+ var id = "#layoutLogger"
+ , $l = $(id);
+ if (!$l.length)
+ $l = createLog();
+ $l.children("ul").append(''+ info.replace(/\/g,">") +' ');
+ }
+
+ function createLog () {
+ var pos = $.support.fixedPosition ? 'fixed' : 'absolute'
+ , $e = $(''
+ + '
'
+ + 'X Layout console.log
'
+ + '
'
+ + '
'
+ ).appendTo("body");
+ $e.css('left', $(window).width() - $e.outerWidth() - 5)
+ if ($.ui.draggable) $e.draggable({ handle: ':first-child' });
+ return $e;
+ };
+ }
+
+};
+
+
+/*
+ * $.layout.browser REPLACES removed $.browser, with extra data
+ * Parsing code here adapted from jQuery 1.8 $.browse
+ */
+var u = navigator.userAgent.toLowerCase()
+, m = /(chrome)[ \/]([\w.]+)/.exec( u )
+ || /(webkit)[ \/]([\w.]+)/.exec( u )
+ || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( u )
+ || /(msie) ([\w.]+)/.exec( u )
+ || u.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( u )
+ || []
+, b = m[1] || ""
+, v = m[2] || 0
+, ie = b === "msie"
+;
+$.layout.browser = {
+ version: v
+, safari: b === "webkit" // webkit (NOT chrome) = safari
+, webkit: b === "chrome" // chrome = webkit
+, msie: ie
+, isIE6: ie && v == 6
+ // ONLY IE reverts to old box-model - update for older jQ onReady
+, boxModel: !ie || $.support.boxModel !== false
+};
+if (b) $.layout.browser[b] = true; // set CURRENT browser
+/* OLD versions of jQuery only set $.support.boxModel after page is loaded
+ * so if this is IE, use support.boxModel to test for quirks-mode (ONLY IE changes boxModel) */
+if (ie) $(function(){ $.layout.browser.boxModel = $.support.boxModel; });
+
+
+// DEFAULT OPTIONS
+$.layout.defaults = {
+/*
+ * LAYOUT & LAYOUT-CONTAINER OPTIONS
+ * - none of these options are applicable to individual panes
+ */
+ name: "" // Not required, but useful for buttons and used for the state-cookie
+, containerClass: "ui-layout-container" // layout-container element
+, inset: null // custom container-inset values (override padding)
+, scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark)
+, resizeWithWindow: true // bind thisLayout.resizeAll() to the window.resize event
+, resizeWithWindowDelay: 200 // delay calling resizeAll because makes window resizing very jerky
+, resizeWithWindowMaxDelay: 0 // 0 = none - force resize every XX ms while window is being resized
+, maskPanesEarly: false // true = create pane-masks on resizer.mouseDown instead of waiting for resizer.dragstart
+, onresizeall_start: null // CALLBACK when resizeAll() STARTS - NOT pane-specific
+, onresizeall_end: null // CALLBACK when resizeAll() ENDS - NOT pane-specific
+, onload_start: null // CALLBACK when Layout inits - after options initialized, but before elements
+, onload_end: null // CALLBACK when Layout inits - after EVERYTHING has been initialized
+, onunload_start: null // CALLBACK when Layout is destroyed OR onWindowUnload
+, onunload_end: null // CALLBACK when Layout is destroyed OR onWindowUnload
+, initPanes: true // false = DO NOT initialize the panes onLoad - will init later
+, showErrorMessages: true // enables fatal error messages to warn developers of common errors
+, showDebugMessages: false // display console-and-alert debug msgs - IF this Layout version _has_ debugging code!
+// Changing this zIndex value will cause other zIndex values to automatically change
+, zIndex: null // the PANE zIndex - resizers and masks will be +1
+// DO NOT CHANGE the zIndex values below unless you clearly understand their relationships
+, zIndexes: { // set _default_ z-index values here...
+ pane_normal: 0 // normal z-index for panes
+ , content_mask: 1 // applied to overlays used to mask content INSIDE panes during resizing
+ , resizer_normal: 2 // normal z-index for resizer-bars
+ , pane_sliding: 100 // applied to *BOTH* the pane and its resizer when a pane is 'slid open'
+ , pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer
+ , resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged'
+ }
+, errors: {
+ pane: "pane" // description of "layout pane element" - used only in error messages
+ , selector: "selector" // description of "jQuery-selector" - used only in error messages
+ , addButtonError: "Error Adding Button\nInvalid "
+ , containerMissing: "UI Layout Initialization Error\nThe specified layout-container does not exist."
+ , centerPaneMissing: "UI Layout Initialization Error\nThe center-pane element does not exist.\nThe center-pane is a required element."
+ , noContainerHeight: "UI Layout Initialization Warning\nThe layout-container \"CONTAINER\" has no height.\nTherefore the layout is 0-height and hence 'invisible'!"
+ , callbackError: "UI Layout Callback Error\nThe EVENT callback is not a valid function."
+ }
+/*
+ * PANE DEFAULT SETTINGS
+ * - settings under the 'panes' key become the default settings for *all panes*
+ * - ALL pane-options can also be set specifically for each panes, which will override these 'default values'
+ */
+, panes: { // default options for 'all panes' - will be overridden by 'per-pane settings'
+ applyDemoStyles: false // NOTE: renamed from applyDefaultStyles for clarity
+ , closable: true // pane can open & close
+ , resizable: true // when open, pane can be resized
+ , slidable: true // when closed, pane can 'slide open' over other panes - closes on mouse-out
+ , initClosed: false // true = init pane as 'closed'
+ , initHidden: false // true = init pane as 'hidden' - no resizer-bar/spacing
+ // SELECTORS
+ //, paneSelector: "" // MUST be pane-specific - jQuery selector for pane
+ , contentSelector: ".ui-layout-content" // INNER div/element to auto-size so only it scrolls, not the entire pane!
+ , contentIgnoreSelector: ".ui-layout-ignore" // element(s) to 'ignore' when measuring 'content'
+ , findNestedContent: false // true = $P.find(contentSelector), false = $P.children(contentSelector)
+ // GENERIC ROOT-CLASSES - for auto-generated classNames
+ , paneClass: "ui-layout-pane" // Layout Pane
+ , resizerClass: "ui-layout-resizer" // Resizer Bar
+ , togglerClass: "ui-layout-toggler" // Toggler Button
+ , buttonClass: "ui-layout-button" // CUSTOM Buttons - eg: '[ui-layout-button]-toggle/-open/-close/-pin'
+ // ELEMENT SIZE & SPACING
+ //, size: 100 // MUST be pane-specific -initial size of pane
+ , minSize: 0 // when manually resizing a pane
+ , maxSize: 0 // ditto, 0 = no limit
+ , spacing_open: 6 // space between pane and adjacent panes - when pane is 'open'
+ , spacing_closed: 6 // ditto - when pane is 'closed'
+ , togglerLength_open: 50 // Length = WIDTH of toggler button on north/south sides - HEIGHT on east/west sides
+ , togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden'
+ , togglerAlign_open: "center" // top/left, bottom/right, center, OR...
+ , togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right
+ , togglerContent_open: "" // text or HTML to put INSIDE the toggler
+ , togglerContent_closed: "" // ditto
+ // RESIZING OPTIONS
+ , resizerDblClickToggle: true //
+ , autoResize: true // IF size is 'auto' or a percentage, then recalc 'pixel size' whenever the layout resizes
+ , autoReopen: true // IF a pane was auto-closed due to noRoom, reopen it when there is room? False = leave it closed
+ , resizerDragOpacity: 1 // option for ui.draggable
+ //, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar
+ , maskContents: false // true = add DIV-mask over-or-inside this pane so can 'drag' over IFRAMES
+ , maskObjects: false // true = add IFRAME-mask over-or-inside this pane to cover objects/applets - content-mask will overlay this mask
+ , maskZindex: null // will override zIndexes.content_mask if specified - not applicable to iframe-panes
+ , resizingGrid: false // grid size that the resizers will snap-to during resizing, eg: [20,20]
+ , livePaneResizing: false // true = LIVE Resizing as resizer is dragged
+ , liveContentResizing: false // true = re-measure header/footer heights as resizer is dragged
+ , liveResizingTolerance: 1 // how many px change before pane resizes, to control performance
+ // SLIDING OPTIONS
+ , sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding'
+ , slideTrigger_open: "click" // click, dblclick, mouseenter
+ , slideTrigger_close: "mouseleave"// click, mouseleave
+ , slideDelay_open: 300 // applies only for mouseenter event - 0 = instant open
+ , slideDelay_close: 300 // applies only for mouseleave event (300ms is the minimum!)
+ , hideTogglerOnSlide: false // when pane is slid-open, should the toggler show?
+ , preventQuickSlideClose: $.layout.browser.webkit // Chrome triggers slideClosed as it is opening
+ , preventPrematureSlideClose: false // handle incorrect mouseleave trigger, like when over a SELECT-list in IE
+ // PANE-SPECIFIC TIPS & MESSAGES
+ , tips: {
+ Open: "Open" // eg: "Open Pane"
+ , Close: "Close"
+ , Resize: "Resize"
+ , Slide: "Slide Open"
+ , Pin: "Pin"
+ , Unpin: "Un-Pin"
+ , noRoomToOpen: "Not enough room to show this panel." // alert if user tries to open a pane that cannot
+ , minSizeWarning: "Panel has reached its minimum size" // displays in browser statusbar
+ , maxSizeWarning: "Panel has reached its maximum size" // ditto
+ }
+ // HOT-KEYS & MISC
+ , showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver
+ , enableCursorHotkey: true // enabled 'cursor' hotkeys
+ //, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character
+ , customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT'
+ // PANE ANIMATION
+ // NOTE: fxSss_open, fxSss_close & fxSss_size options (eg: fxName_open) are auto-generated if not passed
+ , fxName: "slide" // ('none' or blank), slide, drop, scale -- only relevant to 'open' & 'close', NOT 'size'
+ , fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration
+ , fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 }
+ , fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation
+ , animatePaneSizing: false // true = animate resizing after dragging resizer-bar OR sizePane() is called
+ /* NOTE: Action-specific FX options are auto-generated from the options above if not specifically set:
+ fxName_open: "slide" // 'Open' pane animation
+ fnName_close: "slide" // 'Close' pane animation
+ fxName_size: "slide" // 'Size' pane animation - when animatePaneSizing = true
+ fxSpeed_open: null
+ fxSpeed_close: null
+ fxSpeed_size: null
+ fxSettings_open: {}
+ fxSettings_close: {}
+ fxSettings_size: {}
+ */
+ // CHILD/NESTED LAYOUTS
+ , children: null // Layout-options for nested/child layout - even {} is valid as options
+ , containerSelector: '' // if child is NOT 'directly nested', a selector to find it/them (can have more than one child layout!)
+ , initChildren: true // true = child layout will be created as soon as _this_ layout completes initialization
+ , destroyChildren: true // true = destroy child-layout if this pane is destroyed
+ , resizeChildren: true // true = trigger child-layout.resizeAll() when this pane is resized
+ // EVENT TRIGGERING
+ , triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes
+ , triggerEventsDuringLiveResize: true // true = trigger onresize callback REPEATEDLY if livePaneResizing==true
+ // PANE CALLBACKS
+ , onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start
+ , onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end
+ , onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start
+ , onhide_end: null // CALLBACK when pane ENDS being Closed - AFTER onclose_end
+ , onopen_start: null // CALLBACK when pane STARTS to Open
+ , onopen_end: null // CALLBACK when pane ENDS being Opened
+ , onclose_start: null // CALLBACK when pane STARTS to Close
+ , onclose_end: null // CALLBACK when pane ENDS being Closed
+ , onresize_start: null // CALLBACK when pane STARTS being Resized ***FOR ANY REASON***
+ , onresize_end: null // CALLBACK when pane ENDS being Resized ***FOR ANY REASON***
+ , onsizecontent_start: null // CALLBACK when sizing of content-element STARTS
+ , onsizecontent_end: null // CALLBACK when sizing of content-element ENDS
+ , onswap_start: null // CALLBACK when pane STARTS to Swap
+ , onswap_end: null // CALLBACK when pane ENDS being Swapped
+ , ondrag_start: null // CALLBACK when pane STARTS being ***MANUALLY*** Resized
+ , ondrag_end: null // CALLBACK when pane ENDS being ***MANUALLY*** Resized
+ }
+/*
+ * PANE-SPECIFIC SETTINGS
+ * - options listed below MUST be specified per-pane - they CANNOT be set under 'panes'
+ * - all options under the 'panes' key can also be set specifically for any pane
+ * - most options under the 'panes' key apply only to 'border-panes' - NOT the the center-pane
+ */
+, north: {
+ paneSelector: ".ui-layout-north"
+ , size: "auto" // eg: "auto", "30%", .30, 200
+ , resizerCursor: "n-resize" // custom = url(myCursor.cur)
+ , customHotkey: "" // EITHER a charCode (43) OR a character ("o")
+ }
+, south: {
+ paneSelector: ".ui-layout-south"
+ , size: "auto"
+ , resizerCursor: "s-resize"
+ , customHotkey: ""
+ }
+, east: {
+ paneSelector: ".ui-layout-east"
+ , size: 200
+ , resizerCursor: "e-resize"
+ , customHotkey: ""
+ }
+, west: {
+ paneSelector: ".ui-layout-west"
+ , size: 200
+ , resizerCursor: "w-resize"
+ , customHotkey: ""
+ }
+, center: {
+ paneSelector: ".ui-layout-center"
+ , minWidth: 0
+ , minHeight: 0
+ }
+};
+
+$.layout.optionsMap = {
+ // layout/global options - NOT pane-options
+ layout: ("name,instanceKey,stateManagement,effects,inset,zIndexes,errors,"
+ + "zIndex,scrollToBookmarkOnLoad,showErrorMessages,maskPanesEarly,"
+ + "outset,resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay,"
+ + "onresizeall,onresizeall_start,onresizeall_end,onload,onload_start,onload_end,onunload,onunload_start,onunload_end").split(",")
+// borderPanes: [ ALL options that are NOT specified as 'layout' ]
+ // default.panes options that apply to the center-pane (most options apply _only_ to border-panes)
+, center: ("paneClass,contentSelector,contentIgnoreSelector,findNestedContent,applyDemoStyles,triggerEventsOnLoad,"
+ + "showOverflowOnHover,maskContents,maskObjects,liveContentResizing,"
+ + "containerSelector,children,initChildren,resizeChildren,destroyChildren,"
+ + "onresize,onresize_start,onresize_end,onsizecontent,onsizecontent_start,onsizecontent_end").split(",")
+ // options that MUST be specifically set 'per-pane' - CANNOT set in the panes (defaults) key
+, noDefault: ("paneSelector,resizerCursor,customHotkey").split(",")
+};
+
+/**
+ * Processes options passed in converts flat-format data into subkey (JSON) format
+ * In flat-format, subkeys are _currently_ separated with 2 underscores, like north__optName
+ * Plugins may also call this method so they can transform their own data
+ *
+ * @param {!Object} hash Data/options passed by user - may be a single level or nested levels
+ * @param {boolean=} [addKeys=false] Should the primary layout.options keys be added if they do not exist?
+ * @return {Object} Returns hash of minWidth & minHeight
+ */
+$.layout.transformData = function (hash, addKeys) {
+ var json = addKeys ? { panes: {}, center: {} } : {} // init return object
+ , branch, optKey, keys, key, val, i, c;
+
+ if (typeof hash !== "object") return json; // no options passed
+
+ // convert all 'flat-keys' to 'sub-key' format
+ for (optKey in hash) {
+ branch = json;
+ val = hash[ optKey ];
+ keys = optKey.split("__"); // eg: west__size or north__fxSettings__duration
+ c = keys.length - 1;
+ // convert underscore-delimited to subkeys
+ for (i=0; i <= c; i++) {
+ key = keys[i];
+ if (i === c) { // last key = value
+ if ($.isPlainObject( val ))
+ branch[key] = $.layout.transformData( val ); // RECURSE
+ else
+ branch[key] = val;
+ }
+ else {
+ if (!branch[key])
+ branch[key] = {}; // create the subkey
+ // recurse to sub-key for next loop - if not done
+ branch = branch[key];
+ }
+ }
+ }
+ return json;
+};
+
+// INTERNAL CONFIG DATA - DO NOT CHANGE THIS!
+$.layout.backwardCompatibility = {
+ // data used by renameOldOptions()
+ map: {
+ // OLD Option Name: NEW Option Name
+ applyDefaultStyles: "applyDemoStyles"
+ // CHILD/NESTED LAYOUTS
+ , childOptions: "children"
+ , initChildLayout: "initChildren"
+ , destroyChildLayout: "destroyChildren"
+ , resizeChildLayout: "resizeChildren"
+ , resizeNestedLayout: "resizeChildren"
+ // MISC Options
+ , resizeWhileDragging: "livePaneResizing"
+ , resizeContentWhileDragging: "liveContentResizing"
+ , triggerEventsWhileDragging: "triggerEventsDuringLiveResize"
+ , maskIframesOnResize: "maskContents"
+ // STATE MANAGEMENT
+ , useStateCookie: "stateManagement.enabled"
+ , "cookie.autoLoad": "stateManagement.autoLoad"
+ , "cookie.autoSave": "stateManagement.autoSave"
+ , "cookie.keys": "stateManagement.stateKeys"
+ , "cookie.name": "stateManagement.cookie.name"
+ , "cookie.domain": "stateManagement.cookie.domain"
+ , "cookie.path": "stateManagement.cookie.path"
+ , "cookie.expires": "stateManagement.cookie.expires"
+ , "cookie.secure": "stateManagement.cookie.secure"
+ // OLD Language options
+ , noRoomToOpenTip: "tips.noRoomToOpen"
+ , togglerTip_open: "tips.Close" // open = Close
+ , togglerTip_closed: "tips.Open" // closed = Open
+ , resizerTip: "tips.Resize"
+ , sliderTip: "tips.Slide"
+ }
+
+/**
+* @param {Object} opts
+*/
+, renameOptions: function (opts) {
+ var map = $.layout.backwardCompatibility.map
+ , oldData, newData, value
+ ;
+ for (var itemPath in map) {
+ oldData = getBranch( itemPath );
+ value = oldData.branch[ oldData.key ];
+ if (value !== undefined) {
+ newData = getBranch( map[itemPath], true );
+ newData.branch[ newData.key ] = value;
+ delete oldData.branch[ oldData.key ];
+ }
+ }
+
+ /**
+ * @param {string} path
+ * @param {boolean=} [create=false] Create path if does not exist
+ */
+ function getBranch (path, create) {
+ var a = path.split(".") // split keys into array
+ , c = a.length - 1
+ , D = { branch: opts, key: a[c] } // init branch at top & set key (last item)
+ , i = 0, k, undef;
+ for (; i 0) {
+ if (autoHide && $E.data('autoHidden') && $E.innerHeight() > 0) {
+ $E.show().data('autoHidden', false);
+ if (!browser.mozilla) // FireFox refreshes iframes - IE does not
+ // make hidden, then visible to 'refresh' display after animation
+ $E.css(_c.hidden).css(_c.visible);
+ }
+ }
+ else if (autoHide && !$E.data('autoHidden'))
+ $E.hide().data('autoHidden', true);
+ }
+
+ /**
+ * @param {(string|!Object)} el
+ * @param {number=} outerHeight
+ * @param {boolean=} [autoHide=false]
+ */
+, setOuterHeight = function (el, outerHeight, autoHide) {
+ var $E = el, h;
+ if (isStr(el)) $E = $Ps[el]; // west
+ else if (!el.jquery) $E = $(el);
+ h = cssH($E, outerHeight);
+ $E.css({ height: h, visibility: "visible" }); // may have been 'hidden' by sizeContent
+ if (h > 0 && $E.innerWidth() > 0) {
+ if (autoHide && $E.data('autoHidden')) {
+ $E.show().data('autoHidden', false);
+ if (!browser.mozilla) // FireFox refreshes iframes - IE does not
+ $E.css(_c.hidden).css(_c.visible);
+ }
+ }
+ else if (autoHide && !$E.data('autoHidden'))
+ $E.hide().data('autoHidden', true);
+ }
+
+
+ /**
+ * Converts any 'size' params to a pixel/integer size, if not already
+ * If 'auto' or a decimal/percentage is passed as 'size', a pixel-size is calculated
+ *
+ /**
+ * @param {string} pane
+ * @param {(string|number)=} size
+ * @param {string=} [dir]
+ * @return {number}
+ */
+, _parseSize = function (pane, size, dir) {
+ if (!dir) dir = _c[pane].dir;
+
+ if (isStr(size) && size.match(/%/))
+ size = (size === '100%') ? -1 : parseInt(size, 10) / 100; // convert % to decimal
+
+ if (size === 0)
+ return 0;
+ else if (size >= 1)
+ return parseInt(size, 10);
+
+ var o = options, avail = 0;
+ if (dir=="horz") // north or south or center.minHeight
+ avail = sC.innerHeight - ($Ps.north ? o.north.spacing_open : 0) - ($Ps.south ? o.south.spacing_open : 0);
+ else if (dir=="vert") // east or west or center.minWidth
+ avail = sC.innerWidth - ($Ps.west ? o.west.spacing_open : 0) - ($Ps.east ? o.east.spacing_open : 0);
+
+ if (size === -1) // -1 == 100%
+ return avail;
+ else if (size > 0) // percentage, eg: .25
+ return round(avail * size);
+ else if (pane=="center")
+ return 0;
+ else { // size < 0 || size=='auto' || size==Missing || size==Invalid
+ // auto-size the pane
+ var dim = (dir === "horz" ? "height" : "width")
+ , $P = $Ps[pane]
+ , $C = dim === 'height' ? $Cs[pane] : false
+ , vis = $.layout.showInvisibly($P) // show pane invisibly if hidden
+ , szP = $P.css(dim) // SAVE current pane size
+ , szC = $C ? $C.css(dim) : 0 // SAVE current content size
+ ;
+ $P.css(dim, "auto");
+ if ($C) $C.css(dim, "auto");
+ size = (dim === "height") ? $P.outerHeight() : $P.outerWidth(); // MEASURE
+ $P.css(dim, szP).css(vis); // RESET size & visibility
+ if ($C) $C.css(dim, szC);
+ return size;
+ }
+ }
+
+ /**
+ * Calculates current 'size' (outer-width or outer-height) of a border-pane - optionally with 'pane-spacing' added
+ *
+ * @param {(string|!Object)} pane
+ * @param {boolean=} [inclSpace=false]
+ * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes
+ */
+, getPaneSize = function (pane, inclSpace) {
+ var
+ $P = $Ps[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , oSp = (inclSpace ? o.spacing_open : 0)
+ , cSp = (inclSpace ? o.spacing_closed : 0)
+ ;
+ if (!$P || s.isHidden)
+ return 0;
+ else if (s.isClosed || (s.isSliding && inclSpace))
+ return cSp;
+ else if (_c[pane].dir === "horz")
+ return $P.outerHeight() + oSp;
+ else // dir === "vert"
+ return $P.outerWidth() + oSp;
+ }
+
+ /**
+ * Calculate min/max pane dimensions and limits for resizing
+ *
+ * @param {string} pane
+ * @param {boolean=} [slide=false]
+ */
+, setSizeLimits = function (pane, slide) {
+ if (!isInitialized()) return;
+ var
+ o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , dir = c.dir
+ , type = c.sizeType.toLowerCase()
+ , isSliding = (slide != undefined ? slide : s.isSliding) // only open() passes 'slide' param
+ , $P = $Ps[pane]
+ , paneSpacing = o.spacing_open
+ // measure the pane on the *opposite side* from this pane
+ , altPane = _c.oppositeEdge[pane]
+ , altS = state[altPane]
+ , $altP = $Ps[altPane]
+ , altPaneSize = (!$altP || altS.isVisible===false || altS.isSliding ? 0 : (dir=="horz" ? $altP.outerHeight() : $altP.outerWidth()))
+ , altPaneSpacing = ((!$altP || altS.isHidden ? 0 : options[altPane][ altS.isClosed !== false ? "spacing_closed" : "spacing_open" ]) || 0)
+ // limitSize prevents this pane from 'overlapping' opposite pane
+ , containerSize = (dir=="horz" ? sC.innerHeight : sC.innerWidth)
+ , minCenterDims = cssMinDims("center")
+ , minCenterSize = dir=="horz" ? max(options.center.minHeight, minCenterDims.minHeight) : max(options.center.minWidth, minCenterDims.minWidth)
+ // if pane is 'sliding', then ignore center and alt-pane sizes - because 'overlays' them
+ , limitSize = (containerSize - paneSpacing - (isSliding ? 0 : (_parseSize("center", minCenterSize, dir) + altPaneSize + altPaneSpacing)))
+ , minSize = s.minSize = max( _parseSize(pane, o.minSize), cssMinDims(pane).minSize )
+ , maxSize = s.maxSize = min( (o.maxSize ? _parseSize(pane, o.maxSize) : 100000), limitSize )
+ , r = s.resizerPosition = {} // used to set resizing limits
+ , top = sC.inset.top
+ , left = sC.inset.left
+ , W = sC.innerWidth
+ , H = sC.innerHeight
+ , rW = o.spacing_open // subtract resizer-width to get top/left position for south/east
+ ;
+ switch (pane) {
+ case "north": r.min = top + minSize;
+ r.max = top + maxSize;
+ break;
+ case "west": r.min = left + minSize;
+ r.max = left + maxSize;
+ break;
+ case "south": r.min = top + H - maxSize - rW;
+ r.max = top + H - minSize - rW;
+ break;
+ case "east": r.min = left + W - maxSize - rW;
+ r.max = left + W - minSize - rW;
+ break;
+ };
+ }
+
+ /**
+ * Returns data for setting the size/position of center pane. Also used to set Height for east/west panes
+ *
+ * @return JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height
+ */
+, calcNewCenterPaneDims = function () {
+ var d = {
+ top: getPaneSize("north", true) // true = include 'spacing' value for pane
+ , bottom: getPaneSize("south", true)
+ , left: getPaneSize("west", true)
+ , right: getPaneSize("east", true)
+ , width: 0
+ , height: 0
+ };
+
+ // NOTE: sC = state.container
+ // calc center-pane outer dimensions
+ d.width = sC.innerWidth - d.left - d.right; // outerWidth
+ d.height = sC.innerHeight - d.bottom - d.top; // outerHeight
+ // add the 'container border/padding' to get final positions relative to the container
+ d.top += sC.inset.top;
+ d.bottom += sC.inset.bottom;
+ d.left += sC.inset.left;
+ d.right += sC.inset.right;
+
+ return d;
+ }
+
+
+ /**
+ * @param {!Object} el
+ * @param {boolean=} [allStates=false]
+ */
+, getHoverClasses = function (el, allStates) {
+ var
+ $El = $(el)
+ , type = $El.data("layoutRole")
+ , pane = $El.data("layoutEdge")
+ , o = options[pane]
+ , root = o[type +"Class"]
+ , _pane = "-"+ pane // eg: "-west"
+ , _open = "-open"
+ , _closed = "-closed"
+ , _slide = "-sliding"
+ , _hover = "-hover " // NOTE the trailing space
+ , _state = $El.hasClass(root+_closed) ? _closed : _open
+ , _alt = _state === _closed ? _open : _closed
+ , classes = (root+_hover) + (root+_pane+_hover) + (root+_state+_hover) + (root+_pane+_state+_hover)
+ ;
+ if (allStates) // when 'removing' classes, also remove alternate-state classes
+ classes += (root+_alt+_hover) + (root+_pane+_alt+_hover);
+
+ if (type=="resizer" && $El.hasClass(root+_slide))
+ classes += (root+_slide+_hover) + (root+_pane+_slide+_hover);
+
+ return $.trim(classes);
+ }
+, addHover = function (evt, el) {
+ var $E = $(el || this);
+ if (evt && $E.data("layoutRole") === "toggler")
+ evt.stopPropagation(); // prevent triggering 'slide' on Resizer-bar
+ $E.addClass( getHoverClasses($E) );
+ }
+, removeHover = function (evt, el) {
+ var $E = $(el || this);
+ $E.removeClass( getHoverClasses($E, true) );
+ }
+
+, onResizerEnter = function (evt) { // ALSO called by toggler.mouseenter
+ var pane = $(this).data("layoutEdge")
+ , s = state[pane]
+ ;
+ // ignore closed-panes and mouse moving back & forth over resizer!
+ // also ignore if ANY pane is currently resizing
+ if ( s.isClosed || s.isResizing || state.paneResizing ) return;
+
+ if ($.fn.disableSelection)
+ $("body").disableSelection();
+ if (options.maskPanesEarly)
+ showMasks( pane, { resizing: true });
+ }
+, onResizerLeave = function (evt, el) {
+ var e = el || this // el is only passed when called by the timer
+ , pane = $(e).data("layoutEdge")
+ , name = pane +"ResizerLeave"
+ ;
+ timer.clear(pane+"_openSlider"); // cancel slideOpen timer, if set
+ timer.clear(name); // cancel enableSelection timer - may re/set below
+ // this method calls itself on a timer because it needs to allow
+ // enough time for dragging to kick-in and set the isResizing flag
+ // dragging has a 100ms delay set, so this delay must be >100
+ if (!el) // 1st call - mouseleave event
+ timer.set(name, function(){ onResizerLeave(evt, e); }, 200);
+ // if user is resizing, then dragStop will enableSelection(), so can skip it here
+ else if ( !state.paneResizing ) { // 2nd call - by timer
+ if ($.fn.enableSelection)
+ $("body").enableSelection();
+ if (options.maskPanesEarly)
+ hideMasks();
+ }
+ }
+
+/*
+ * ###########################
+ * INITIALIZATION METHODS
+ * ###########################
+ */
+
+ /**
+ * Initialize the layout - called automatically whenever an instance of layout is created
+ *
+ * @see none - triggered onInit
+ * @return mixed true = fully initialized | false = panes not initialized (yet) | 'cancel' = abort
+ */
+, _create = function () {
+ // initialize config/options
+ initOptions();
+ var o = options
+ , s = state;
+
+ // TEMP state so isInitialized returns true during init process
+ s.creatingLayout = true;
+
+ // init plugins for this layout, if there are any (eg: stateManagement)
+ runPluginCallbacks( Instance, $.layout.onCreate );
+
+ // options & state have been initialized, so now run beforeLoad callback
+ // onload will CANCEL layout creation if it returns false
+ if (false === _runCallbacks("onload_start"))
+ return 'cancel';
+
+ // initialize the container element
+ _initContainer();
+
+ // bind hotkey function - keyDown - if required
+ initHotkeys();
+
+ // bind window.onunload
+ $(window).bind("unload."+ sID, unload);
+
+ // init plugins for this layout, if there are any (eg: customButtons)
+ runPluginCallbacks( Instance, $.layout.onLoad );
+
+ // if layout elements are hidden, then layout WILL NOT complete initialization!
+ // initLayoutElements will set initialized=true and run the onload callback IF successful
+ if (o.initPanes) _initLayoutElements();
+
+ delete s.creatingLayout;
+
+ return state.initialized;
+ }
+
+ /**
+ * Initialize the layout IF not already
+ *
+ * @see All methods in Instance run this test
+ * @return boolean true = layoutElements have been initialized | false = panes are not initialized (yet)
+ */
+, isInitialized = function () {
+ if (state.initialized || state.creatingLayout) return true; // already initialized
+ else return _initLayoutElements(); // try to init panes NOW
+ }
+
+ /**
+ * Initialize the layout - called automatically whenever an instance of layout is created
+ *
+ * @see _create() & isInitialized
+ * @param {boolean=} [retry=false] // indicates this is a 2nd try
+ * @return An object pointer to the instance created
+ */
+, _initLayoutElements = function (retry) {
+ // initialize config/options
+ var o = options;
+ // CANNOT init panes inside a hidden container!
+ if (!$N.is(":visible")) {
+ // handle Chrome bug where popup window 'has no height'
+ // if layout is BODY element, try again in 50ms
+ // SEE: http://layout.jquery-dev.net/samples/test_popup_window.html
+ if ( !retry && browser.webkit && $N[0].tagName === "BODY" )
+ setTimeout(function(){ _initLayoutElements(true); }, 50);
+ return false;
+ }
+
+ // a center pane is required, so make sure it exists
+ if (!getPane("center").length) {
+ return _log( o.errors.centerPaneMissing );
+ }
+
+ // TEMP state so isInitialized returns true during init process
+ state.creatingLayout = true;
+
+ // update Container dims
+ $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values
+
+ // initialize all layout elements
+ initPanes(); // size & position panes - calls initHandles() - which calls initResizable()
+
+ if (o.scrollToBookmarkOnLoad) {
+ var l = self.location;
+ if (l.hash) l.replace( l.hash ); // scrollTo Bookmark
+ }
+
+ // check to see if this layout 'nested' inside a pane
+ if (Instance.hasParentLayout)
+ o.resizeWithWindow = false;
+ // bind resizeAll() for 'this layout instance' to window.resize event
+ else if (o.resizeWithWindow)
+ $(window).bind("resize."+ sID, windowResize);
+
+ delete state.creatingLayout;
+ state.initialized = true;
+
+ // init plugins for this layout, if there are any
+ runPluginCallbacks( Instance, $.layout.onReady );
+
+ // now run the onload callback, if exists
+ _runCallbacks("onload_end");
+
+ return true; // elements initialized successfully
+ }
+
+ /**
+ * Initialize nested layouts for a specific pane - can optionally pass layout-options
+ *
+ * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
+ * @param {Object=} [opts] Layout-options - if passed, will OVERRRIDE options[pane].children
+ * @return An object pointer to the layout instance created - or null
+ */
+, createChildren = function (evt_or_pane, opts) {
+ var pane = evtPane.call(this, evt_or_pane)
+ , $P = $Ps[pane]
+ ;
+ if (!$P) return;
+ var $C = $Cs[pane]
+ , s = state[pane]
+ , o = options[pane]
+ , sm = options.stateManagement || {}
+ , cos = opts ? (o.children = opts) : o.children
+ ;
+ if ( $.isPlainObject( cos ) )
+ cos = [ cos ]; // convert a hash to a 1-elem array
+ else if (!cos || !$.isArray( cos ))
+ return;
+
+ $.each( cos, function (idx, co) {
+ if ( !$.isPlainObject( co ) ) return;
+
+ // determine which element is supposed to be the 'child container'
+ // if pane has a 'containerSelector' OR a 'content-div', use those instead of the pane
+ var $containers = co.containerSelector ? $P.find( co.containerSelector ) : ($C || $P);
+
+ $containers.each(function(){
+ var $cont = $(this)
+ , child = $cont.data("layout") // see if a child-layout ALREADY exists on this element
+ ;
+ // if no layout exists, but children are set, try to create the layout now
+ if (!child) {
+ // TODO: see about moving this to the stateManagement plugin, as a method
+ // set a unique child-instance key for this layout, if not already set
+ setInstanceKey({ container: $cont, options: co }, s );
+ // If THIS layout has a hash in stateManagement.autoLoad,
+ // then see if it also contains state-data for this child-layout
+ // If so, copy the stateData to child.options.stateManagement.autoLoad
+ if ( sm.includeChildren && state.stateData[pane] ) {
+ // THIS layout's state was cached when its state was loaded
+ var paneChildren = state.stateData[pane].children || {}
+ , childState = paneChildren[ co.instanceKey ]
+ , co_sm = co.stateManagement || (co.stateManagement = { autoLoad: true })
+ ;
+ // COPY the stateData into the autoLoad key
+ if ( co_sm.autoLoad === true && childState ) {
+ co_sm.autoSave = false; // disable autoSave because saving handled by parent-layout
+ co_sm.includeChildren = true; // cascade option - FOR NOW
+ co_sm.autoLoad = $.extend(true, {}, childState); // COPY the state-hash
+ }
+ }
+
+ // create the layout
+ child = $cont.layout( co );
+
+ // if successful, update data
+ if (child) {
+ // add the child and update all layout-pointers
+ // MAY have already been done by child-layout calling parent.refreshChildren()
+ refreshChildren( pane, child );
+ }
+ }
+ });
+ });
+ }
+
+, setInstanceKey = function (child, parentPaneState) {
+ // create a named key for use in state and instance branches
+ var $c = child.container
+ , o = child.options
+ , sm = o.stateManagement
+ , key = o.instanceKey || $c.data("layoutInstanceKey")
+ ;
+ if (!key) key = (sm && sm.cookie ? sm.cookie.name : '') || o.name; // look for a name/key
+ if (!key) key = "layout"+ (++parentPaneState.childIdx); // if no name/key found, generate one
+ else key = key.replace(/[^\w-]/gi, '_').replace(/_{2,}/g, '_'); // ensure is valid as a hash key
+ o.instanceKey = key;
+ $c.data("layoutInstanceKey", key); // useful if layout is destroyed and then recreated
+ return key;
+ }
+
+ /**
+ * @param {string} pane The pane being opened, ie: north, south, east, or west
+ * @param {Object=} newChild New child-layout Instance to add to this pane
+ */
+, refreshChildren = function (pane, newChild) {
+ var $P = $Ps[pane]
+ , pC = children[pane]
+ , s = state[pane]
+ , o
+ ;
+ // check for destroy()ed layouts and update the child pointers & arrays
+ if ($.isPlainObject( pC )) {
+ $.each( pC, function (key, child) {
+ if (child.destroyed) delete pC[key]
+ });
+ // if no more children, remove the children hash
+ if ($.isEmptyObject( pC ))
+ pC = children[pane] = null; // clear children hash
+ }
+
+ // see if there is a directly-nested layout inside this pane
+ // if there is, then there can be only ONE child-layout, so check that...
+ if (!newChild && !pC) {
+ newChild = $P.data("layout");
+ }
+
+ // if a newChild instance was passed, add it to children[pane]
+ if (newChild) {
+ // update child.state
+ newChild.hasParentLayout = true; // set parent-flag in child
+ // instanceKey is a key-name used in both state and children
+ o = newChild.options;
+ // set a unique child-instance key for this layout, if not already set
+ setInstanceKey( newChild, s );
+ // add pointer to pane.children hash
+ if (!pC) pC = children[pane] = {}; // create an empty children hash
+ pC[ o.instanceKey ] = newChild.container.data("layout"); // add childLayout instance
+ }
+
+ // ALWAYS refresh the pane.children alias, even if null
+ Instance[pane].children = children[pane];
+
+ // if newChild was NOT passed - see if there is a child layout NOW
+ if (!newChild) {
+ createChildren(pane); // MAY create a child and re-call this method
+ }
+ }
+
+, windowResize = function () {
+ var o = options
+ , delay = Number(o.resizeWithWindowDelay);
+ if (delay < 10) delay = 100; // MUST have a delay!
+ // resizing uses a delay-loop because the resize event fires repeatly - except in FF, but delay anyway
+ timer.clear("winResize"); // if already running
+ timer.set("winResize", function(){
+ timer.clear("winResize");
+ timer.clear("winResizeRepeater");
+ var dims = elDims( $N, o.inset );
+ // only trigger resizeAll() if container has changed size
+ if (dims.innerWidth !== sC.innerWidth || dims.innerHeight !== sC.innerHeight)
+ resizeAll();
+ }, delay);
+ // ALSO set fixed-delay timer, if not already running
+ if (!timer.data["winResizeRepeater"]) setWindowResizeRepeater();
+ }
+
+, setWindowResizeRepeater = function () {
+ var delay = Number(options.resizeWithWindowMaxDelay);
+ if (delay > 0)
+ timer.set("winResizeRepeater", function(){ setWindowResizeRepeater(); resizeAll(); }, delay);
+ }
+
+, unload = function () {
+ var o = options;
+
+ _runCallbacks("onunload_start");
+
+ // trigger plugin callabacks for this layout (eg: stateManagement)
+ runPluginCallbacks( Instance, $.layout.onUnload );
+
+ _runCallbacks("onunload_end");
+ }
+
+ /**
+ * Validate and initialize container CSS and events
+ *
+ * @see _create()
+ */
+, _initContainer = function () {
+ var
+ N = $N[0]
+ , $H = $("html")
+ , tag = sC.tagName = N.tagName
+ , id = sC.id = N.id
+ , cls = sC.className = N.className
+ , o = options
+ , name = o.name
+ , props = "position,margin,padding,border"
+ , css = "layoutCSS"
+ , CSS = {}
+ , hid = "hidden" // used A LOT!
+ // see if this container is a 'pane' inside an outer-layout
+ , parent = $N.data("parentLayout") // parent-layout Instance
+ , pane = $N.data("layoutEdge") // pane-name in parent-layout
+ , isChild = parent && pane
+ , num = $.layout.cssNum
+ , $parent, n
+ ;
+ // sC = state.container
+ sC.selector = $N.selector.split(".slice")[0];
+ sC.ref = (o.name ? o.name +' layout / ' : '') + tag + (id ? "#"+id : cls ? '.['+cls+']' : ''); // used in messages
+ sC.isBody = (tag === "BODY");
+
+ // try to find a parent-layout
+ if (!isChild && !sC.isBody) {
+ $parent = $N.closest("."+ $.layout.defaults.panes.paneClass);
+ parent = $parent.data("parentLayout");
+ pane = $parent.data("layoutEdge");
+ isChild = parent && pane;
+ }
+
+ $N .data({
+ layout: Instance
+ , layoutContainer: sID // FLAG to indicate this is a layout-container - contains unique internal ID
+ })
+ .addClass(o.containerClass)
+ ;
+ var layoutMethods = {
+ destroy: ''
+ , initPanes: ''
+ , resizeAll: 'resizeAll'
+ , resize: 'resizeAll'
+ };
+ // loop hash and bind all methods - include layoutID namespacing
+ for (name in layoutMethods) {
+ $N.bind("layout"+ name.toLowerCase() +"."+ sID, Instance[ layoutMethods[name] || name ]);
+ }
+
+ // if this container is another layout's 'pane', then set child/parent pointers
+ if (isChild) {
+ // update parent flag
+ Instance.hasParentLayout = true;
+ // set pointers to THIS child-layout (Instance) in parent-layout
+ parent.refreshChildren( pane, Instance );
+ }
+
+ // SAVE original container CSS for use in destroy()
+ if (!$N.data(css)) {
+ // handle props like overflow different for BODY & HTML - has 'system default' values
+ if (sC.isBody) {
+ // SAVE CSS
+ $N.data(css, $.extend( styles($N, props), {
+ height: $N.css("height")
+ , overflow: $N.css("overflow")
+ , overflowX: $N.css("overflowX")
+ , overflowY: $N.css("overflowY")
+ }));
+ // ALSO SAVE CSS
+ $H.data(css, $.extend( styles($H, 'padding'), {
+ height: "auto" // FF would return a fixed px-size!
+ , overflow: $H.css("overflow")
+ , overflowX: $H.css("overflowX")
+ , overflowY: $H.css("overflowY")
+ }));
+ }
+ else // handle props normally for non-body elements
+ $N.data(css, styles($N, props+",top,bottom,left,right,width,height,overflow,overflowX,overflowY") );
+ }
+
+ try {
+ // common container CSS
+ CSS = {
+ overflow: hid
+ , overflowX: hid
+ , overflowY: hid
+ };
+ $N.css( CSS );
+
+ if (o.inset && !$.isPlainObject(o.inset)) {
+ // can specify a single number for equal outset all-around
+ n = parseInt(o.inset, 10) || 0
+ o.inset = {
+ top: n
+ , bottom: n
+ , left: n
+ , right: n
+ };
+ }
+
+ // format html & body if this is a full page layout
+ if (sC.isBody) {
+ // if HTML has padding, use this as an outer-spacing around BODY
+ if (!o.outset) {
+ // use padding from parent-elem (HTML) as outset
+ o.outset = {
+ top: num($H, "paddingTop")
+ , bottom: num($H, "paddingBottom")
+ , left: num($H, "paddingLeft")
+ , right: num($H, "paddingRight")
+ };
+ }
+ else if (!$.isPlainObject(o.outset)) {
+ // can specify a single number for equal outset all-around
+ n = parseInt(o.outset, 10) || 0
+ o.outset = {
+ top: n
+ , bottom: n
+ , left: n
+ , right: n
+ };
+ }
+ // HTML
+ $H.css( CSS ).css({
+ height: "100%"
+ , border: "none" // no border or padding allowed when using height = 100%
+ , padding: 0 // ditto
+ , margin: 0
+ });
+ // BODY
+ if (browser.isIE6) {
+ // IE6 CANNOT use the trick of setting absolute positioning on all 4 sides - must have 'height'
+ $N.css({
+ width: "100%"
+ , height: "100%"
+ , border: "none" // no border or padding allowed when using height = 100%
+ , padding: 0 // ditto
+ , margin: 0
+ , position: "relative"
+ });
+ // convert body padding to an inset option - the border cannot be measured in IE6!
+ if (!o.inset) o.inset = elDims( $N ).inset;
+ }
+ else { // use absolute positioning for BODY to allow borders & padding without overflow
+ $N.css({
+ width: "auto"
+ , height: "auto"
+ , margin: 0
+ , position: "absolute" // allows for border and padding on BODY
+ });
+ // apply edge-positioning created above
+ $N.css( o.outset );
+ }
+ // set current layout-container dimensions
+ $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values
+ }
+ else {
+ // container MUST have 'position'
+ var p = $N.css("position");
+ if (!p || !p.match(/(fixed|absolute|relative)/))
+ $N.css("position","relative");
+
+ // set current layout-container dimensions
+ if ( $N.is(":visible") ) {
+ $.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT change insetX (padding) values
+ if (sC.innerHeight < 1) // container has no 'height' - warn developer
+ _log( o.errors.noContainerHeight.replace(/CONTAINER/, sC.ref) );
+ }
+ }
+
+ // if container has min-width/height, then enable scrollbar(s)
+ if ( num($N, "minWidth") ) $N.parent().css("overflowX","auto");
+ if ( num($N, "minHeight") ) $N.parent().css("overflowY","auto");
+
+ } catch (ex) {}
+ }
+
+ /**
+ * Bind layout hotkeys - if options enabled
+ *
+ * @see _create() and addPane()
+ * @param {string=} [panes=""] The edge(s) to process
+ */
+, initHotkeys = function (panes) {
+ panes = panes ? panes.split(",") : _c.borderPanes;
+ // bind keyDown to capture hotkeys, if option enabled for ANY pane
+ $.each(panes, function (i, pane) {
+ var o = options[pane];
+ if (o.enableCursorHotkey || o.customHotkey) {
+ $(document).bind("keydown."+ sID, keyDown); // only need to bind this ONCE
+ return false; // BREAK - binding was done
+ }
+ });
+ }
+
+ /**
+ * Build final OPTIONS data
+ *
+ * @see _create()
+ */
+, initOptions = function () {
+ var data, d, pane, key, val, i, c, o;
+
+ // reprocess user's layout-options to have correct options sub-key structure
+ opts = $.layout.transformData( opts, true ); // panes = default subkey
+
+ // auto-rename old options for backward compatibility
+ opts = $.layout.backwardCompatibility.renameAllOptions( opts );
+
+ // if user-options has 'panes' key (pane-defaults), clean it...
+ if (!$.isEmptyObject(opts.panes)) {
+ // REMOVE any pane-defaults that MUST be set per-pane
+ data = $.layout.optionsMap.noDefault;
+ for (i=0, c=data.length; i 0) {
+ z.pane_normal = zo;
+ z.content_mask = max(zo+1, z.content_mask); // MIN = +1
+ z.resizer_normal = max(zo+2, z.resizer_normal); // MIN = +2
+ }
+
+ // DELETE 'panes' key now that we are done - values were copied to EACH pane
+ delete options.panes;
+
+
+ function createFxOptions ( pane ) {
+ var o = options[pane]
+ , d = options.panes;
+ // ensure fxSettings key to avoid errors
+ if (!o.fxSettings) o.fxSettings = {};
+ if (!d.fxSettings) d.fxSettings = {};
+
+ $.each(["_open","_close","_size"], function (i,n) {
+ var
+ sName = "fxName"+ n
+ , sSpeed = "fxSpeed"+ n
+ , sSettings = "fxSettings"+ n
+ // recalculate fxName according to specificity rules
+ , fxName = o[sName] =
+ o[sName] // options.west.fxName_open
+ || d[sName] // options.panes.fxName_open
+ || o.fxName // options.west.fxName
+ || d.fxName // options.panes.fxName
+ || "none" // MEANS $.layout.defaults.panes.fxName == "" || false || null || 0
+ , fxExists = $.effects && ($.effects[fxName] || ($.effects.effect && $.effects.effect[fxName]))
+ ;
+ // validate fxName to ensure is valid effect - MUST have effect-config data in options.effects
+ if (fxName === "none" || !options.effects[fxName] || !fxExists)
+ fxName = o[sName] = "none"; // effect not loaded OR unrecognized fxName
+
+ // set vars for effects subkeys to simplify logic
+ var fx = options.effects[fxName] || {} // effects.slide
+ , fx_all = fx.all || null // effects.slide.all
+ , fx_pane = fx[pane] || null // effects.slide.west
+ ;
+ // create fxSpeed[_open|_close|_size]
+ o[sSpeed] =
+ o[sSpeed] // options.west.fxSpeed_open
+ || d[sSpeed] // options.west.fxSpeed_open
+ || o.fxSpeed // options.west.fxSpeed
+ || d.fxSpeed // options.panes.fxSpeed
+ || null // DEFAULT - let fxSetting.duration control speed
+ ;
+ // create fxSettings[_open|_close|_size]
+ o[sSettings] = $.extend(
+ true
+ , {}
+ , fx_all // effects.slide.all
+ , fx_pane // effects.slide.west
+ , d.fxSettings // options.panes.fxSettings
+ , o.fxSettings // options.west.fxSettings
+ , d[sSettings] // options.panes.fxSettings_open
+ , o[sSettings] // options.west.fxSettings_open
+ );
+ });
+
+ // DONE creating action-specific-settings for this pane,
+ // so DELETE generic options - are no longer meaningful
+ delete o.fxName;
+ delete o.fxSpeed;
+ delete o.fxSettings;
+ }
+ }
+
+ /**
+ * Initialize module objects, styling, size and position for all panes
+ *
+ * @see _initElements()
+ * @param {string} pane The pane to process
+ */
+, getPane = function (pane) {
+ var sel = options[pane].paneSelector
+ if (sel.substr(0,1)==="#") // ID selector
+ // NOTE: elements selected 'by ID' DO NOT have to be 'children'
+ return $N.find(sel).eq(0);
+ else { // class or other selector
+ var $P = $N.children(sel).eq(0);
+ // look for the pane nested inside a 'form' element
+ return $P.length ? $P : $N.children("form:first").children(sel).eq(0);
+ }
+ }
+
+ /**
+ * @param {Object=} evt
+ */
+, initPanes = function (evt) {
+ // stopPropagation if called by trigger("layoutinitpanes") - use evtPane utility
+ evtPane(evt);
+
+ // NOTE: do north & south FIRST so we can measure their height - do center LAST
+ $.each(_c.allPanes, function (idx, pane) {
+ addPane( pane, true );
+ });
+
+ // init the pane-handles NOW in case we have to hide or close the pane below
+ initHandles();
+
+ // now that all panes have been initialized and initially-sized,
+ // make sure there is really enough space available for each pane
+ $.each(_c.borderPanes, function (i, pane) {
+ if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN
+ setSizeLimits(pane);
+ makePaneFit(pane); // pane may be Closed, Hidden or Resized by makePaneFit()
+ }
+ });
+ // size center-pane AGAIN in case we 'closed' a border-pane in loop above
+ sizeMidPanes("center");
+
+ // Chrome/Webkit sometimes fires callbacks BEFORE it completes resizing!
+ // Before RC30.3, there was a 10ms delay here, but that caused layout
+ // to load asynchrously, which is BAD, so try skipping delay for now
+
+ // process pane contents and callbacks, and init/resize child-layout if exists
+ $.each(_c.allPanes, function (idx, pane) {
+ afterInitPane(pane);
+ });
+ }
+
+ /**
+ * Add a pane to the layout - subroutine of initPanes()
+ *
+ * @see initPanes()
+ * @param {string} pane The pane to process
+ * @param {boolean=} [force=false] Size content after init
+ */
+, addPane = function (pane, force) {
+ if (!force && !isInitialized()) return;
+ var
+ o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , dir = c.dir
+ , fx = s.fx
+ , spacing = o.spacing_open || 0
+ , isCenter = (pane === "center")
+ , CSS = {}
+ , $P = $Ps[pane]
+ , size, minSize, maxSize, child
+ ;
+ // if pane-pointer already exists, remove the old one first
+ if ($P)
+ removePane( pane, false, true, false );
+ else
+ $Cs[pane] = false; // init
+
+ $P = $Ps[pane] = getPane(pane);
+ if (!$P.length) {
+ $Ps[pane] = false; // logic
+ return;
+ }
+
+ // SAVE original Pane CSS
+ if (!$P.data("layoutCSS")) {
+ var props = "position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border";
+ $P.data("layoutCSS", styles($P, props));
+ }
+
+ // create alias for pane data in Instance - initHandles will add more
+ Instance[pane] = {
+ name: pane
+ , pane: $Ps[pane]
+ , content: $Cs[pane]
+ , options: options[pane]
+ , state: state[pane]
+ , children: children[pane]
+ };
+
+ // add classes, attributes & events
+ $P .data({
+ parentLayout: Instance // pointer to Layout Instance
+ , layoutPane: Instance[pane] // NEW pointer to pane-alias-object
+ , layoutEdge: pane
+ , layoutRole: "pane"
+ })
+ .css(c.cssReq).css("zIndex", options.zIndexes.pane_normal)
+ .css(o.applyDemoStyles ? c.cssDemo : {}) // demo styles
+ .addClass( o.paneClass +" "+ o.paneClass+"-"+pane ) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector'
+ .bind("mouseenter."+ sID, addHover )
+ .bind("mouseleave."+ sID, removeHover )
+ ;
+ var paneMethods = {
+ hide: ''
+ , show: ''
+ , toggle: ''
+ , close: ''
+ , open: ''
+ , slideOpen: ''
+ , slideClose: ''
+ , slideToggle: ''
+ , size: 'sizePane'
+ , sizePane: 'sizePane'
+ , sizeContent: ''
+ , sizeHandles: ''
+ , enableClosable: ''
+ , disableClosable: ''
+ , enableSlideable: ''
+ , disableSlideable: ''
+ , enableResizable: ''
+ , disableResizable: ''
+ , swapPanes: 'swapPanes'
+ , swap: 'swapPanes'
+ , move: 'swapPanes'
+ , removePane: 'removePane'
+ , remove: 'removePane'
+ , createChildren: ''
+ , resizeChildren: ''
+ , resizeAll: 'resizeAll'
+ , resizeLayout: 'resizeAll'
+ }
+ , name;
+ // loop hash and bind all methods - include layoutID namespacing
+ for (name in paneMethods) {
+ $P.bind("layoutpane"+ name.toLowerCase() +"."+ sID, Instance[ paneMethods[name] || name ]);
+ }
+
+ // see if this pane has a 'scrolling-content element'
+ initContent(pane, false); // false = do NOT sizeContent() - called later
+
+ if (!isCenter) {
+ // call _parseSize AFTER applying pane classes & styles - but before making visible (if hidden)
+ // if o.size is auto or not valid, then MEASURE the pane and use that as its 'size'
+ size = s.size = _parseSize(pane, o.size);
+ minSize = _parseSize(pane,o.minSize) || 1;
+ maxSize = _parseSize(pane,o.maxSize) || 100000;
+ if (size > 0) size = max(min(size, maxSize), minSize);
+ s.autoResize = o.autoResize; // used with percentage sizes
+
+ // state for border-panes
+ s.isClosed = false; // true = pane is closed
+ s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes
+ s.isResizing= false; // true = pane is in process of being resized
+ s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible!
+
+ // array for 'pin buttons' whose classNames are auto-updated on pane-open/-close
+ if (!s.pins) s.pins = [];
+ }
+ // states common to ALL panes
+ s.tagName = $P[0].tagName;
+ s.edge = pane; // useful if pane is (or about to be) 'swapped' - easy find out where it is (or is going)
+ s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically
+ s.isVisible = true; // false = pane is invisible - closed OR hidden - simplify logic
+
+ // init pane positioning
+ setPanePosition( pane );
+
+ // if pane is not visible,
+ if (dir === "horz") // north or south pane
+ CSS.height = cssH($P, size);
+ else if (dir === "vert") // east or west pane
+ CSS.width = cssW($P, size);
+ //else if (isCenter) {}
+
+ $P.css(CSS); // apply size -- top, bottom & height will be set by sizeMidPanes
+ if (dir != "horz") sizeMidPanes(pane, true); // true = skipCallback
+
+ // if manually adding a pane AFTER layout initialization, then...
+ if (state.initialized) {
+ initHandles( pane );
+ initHotkeys( pane );
+ }
+
+ // close or hide the pane if specified in settings
+ if (o.initClosed && o.closable && !o.initHidden)
+ close(pane, true, true); // true, true = force, noAnimation
+ else if (o.initHidden || o.initClosed)
+ hide(pane); // will be completely invisible - no resizer or spacing
+ else if (!s.noRoom)
+ // make the pane visible - in case was initially hidden
+ $P.css("display","block");
+ // ELSE setAsOpen() - called later by initHandles()
+
+ // RESET visibility now - pane will appear IF display:block
+ $P.css("visibility","visible");
+
+ // check option for auto-handling of pop-ups & drop-downs
+ if (o.showOverflowOnHover)
+ $P.hover( allowOverflow, resetOverflow );
+
+ // if manually adding a pane AFTER layout initialization, then...
+ if (state.initialized) {
+ afterInitPane( pane );
+ }
+ }
+
+, afterInitPane = function (pane) {
+ var $P = $Ps[pane]
+ , s = state[pane]
+ , o = options[pane]
+ ;
+ if (!$P) return;
+
+ // see if there is a directly-nested layout inside this pane
+ if ($P.data("layout"))
+ refreshChildren( pane, $P.data("layout") );
+
+ // process pane contents and callbacks, and init/resize child-layout if exists
+ if (s.isVisible) { // pane is OPEN
+ if (state.initialized) // this pane was added AFTER layout was created
+ resizeAll(); // will also sizeContent
+ else
+ sizeContent(pane);
+
+ if (o.triggerEventsOnLoad)
+ _runCallbacks("onresize_end", pane);
+ else // automatic if onresize called, otherwise call it specifically
+ // resize child - IF inner-layout already exists (created before this layout)
+ resizeChildren(pane, true); // a previously existing childLayout
+ }
+
+ // init childLayouts - even if pane is not visible
+ if (o.initChildren && o.children)
+ createChildren(pane);
+ }
+
+ /**
+ * @param {string=} panes The pane(s) to process
+ */
+, setPanePosition = function (panes) {
+ panes = panes ? panes.split(",") : _c.borderPanes;
+
+ // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV
+ $.each(panes, function (i, pane) {
+ var $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , side = _c[pane].side
+ , CSS = {}
+ ;
+ if (!$P) return; // pane does not exist - skip
+
+ // set css-position to account for container borders & padding
+ switch (pane) {
+ case "north": CSS.top = sC.inset.top;
+ CSS.left = sC.inset.left;
+ CSS.right = sC.inset.right;
+ break;
+ case "south": CSS.bottom = sC.inset.bottom;
+ CSS.left = sC.inset.left;
+ CSS.right = sC.inset.right;
+ break;
+ case "west": CSS.left = sC.inset.left; // top, bottom & height set by sizeMidPanes()
+ break;
+ case "east": CSS.right = sC.inset.right; // ditto
+ break;
+ case "center": // top, left, width & height set by sizeMidPanes()
+ }
+ // apply position
+ $P.css(CSS);
+
+ // update resizer position
+ if ($R && s.isClosed)
+ $R.css(side, sC.inset[side]);
+ else if ($R && !s.isHidden)
+ $R.css(side, sC.inset[side] + getPaneSize(pane));
+ });
+ }
+
+ /**
+ * Initialize module objects, styling, size and position for all resize bars and toggler buttons
+ *
+ * @see _create()
+ * @param {string=} [panes=""] The edge(s) to process
+ */
+, initHandles = function (panes) {
+ panes = panes ? panes.split(",") : _c.borderPanes;
+
+ // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV
+ $.each(panes, function (i, pane) {
+ var $P = $Ps[pane];
+ $Rs[pane] = false; // INIT
+ $Ts[pane] = false;
+ if (!$P) return; // pane does not exist - skip
+
+ var o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , paneId = o.paneSelector.substr(0,1) === "#" ? o.paneSelector.substr(1) : ""
+ , rClass = o.resizerClass
+ , tClass = o.togglerClass
+ , spacing = (s.isVisible ? o.spacing_open : o.spacing_closed)
+ , _pane = "-"+ pane // used for classNames
+ , _state = (s.isVisible ? "-open" : "-closed") // used for classNames
+ , I = Instance[pane]
+ // INIT RESIZER BAR
+ , $R = I.resizer = $Rs[pane] = $("
")
+ // INIT TOGGLER BUTTON
+ , $T = I.toggler = (o.closable ? $Ts[pane] = $("
") : false)
+ ;
+
+ //if (s.isVisible && o.resizable) ... handled by initResizable
+ if (!s.isVisible && o.slidable)
+ $R.attr("title", o.tips.Slide).css("cursor", o.sliderCursor);
+
+ $R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer"
+ .attr("id", paneId ? paneId +"-resizer" : "" )
+ .data({
+ parentLayout: Instance
+ , layoutPane: Instance[pane] // NEW pointer to pane-alias-object
+ , layoutEdge: pane
+ , layoutRole: "resizer"
+ })
+ .css(_c.resizers.cssReq).css("zIndex", options.zIndexes.resizer_normal)
+ .css(o.applyDemoStyles ? _c.resizers.cssDemo : {}) // add demo styles
+ .addClass(rClass +" "+ rClass+_pane)
+ .hover(addHover, removeHover) // ALWAYS add hover-classes, even if resizing is not enabled - handle with CSS instead
+ .hover(onResizerEnter, onResizerLeave) // ALWAYS NEED resizer.mouseleave to balance toggler.mouseenter
+ .appendTo($N) // append DIV to container
+ ;
+ if (o.resizerDblClickToggle)
+ $R.bind("dblclick."+ sID, toggle );
+
+ if ($T) {
+ $T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler"
+ .attr("id", paneId ? paneId +"-toggler" : "" )
+ .data({
+ parentLayout: Instance
+ , layoutPane: Instance[pane] // NEW pointer to pane-alias-object
+ , layoutEdge: pane
+ , layoutRole: "toggler"
+ })
+ .css(_c.togglers.cssReq) // add base/required styles
+ .css(o.applyDemoStyles ? _c.togglers.cssDemo : {}) // add demo styles
+ .addClass(tClass +" "+ tClass+_pane)
+ .hover(addHover, removeHover) // ALWAYS add hover-classes, even if toggling is not enabled - handle with CSS instead
+ .bind("mouseenter", onResizerEnter) // NEED toggler.mouseenter because mouseenter MAY NOT fire on resizer
+ .appendTo($R) // append SPAN to resizer DIV
+ ;
+ // ADD INNER-SPANS TO TOGGLER
+ if (o.togglerContent_open) // ui-layout-open
+ $(""+ o.togglerContent_open +" ")
+ .data({
+ layoutEdge: pane
+ , layoutRole: "togglerContent"
+ })
+ .data("layoutRole", "togglerContent")
+ .data("layoutEdge", pane)
+ .addClass("content content-open")
+ .css("display","none")
+ .appendTo( $T )
+ //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-open instead!
+ ;
+ if (o.togglerContent_closed) // ui-layout-closed
+ $(""+ o.togglerContent_closed +" ")
+ .data({
+ layoutEdge: pane
+ , layoutRole: "togglerContent"
+ })
+ .addClass("content content-closed")
+ .css("display","none")
+ .appendTo( $T )
+ //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-closed instead!
+ ;
+ // ADD TOGGLER.click/.hover
+ enableClosable(pane);
+ }
+
+ // add Draggable events
+ initResizable(pane);
+
+ // ADD CLASSNAMES & SLIDE-BINDINGS - eg: class="resizer resizer-west resizer-open"
+ if (s.isVisible)
+ setAsOpen(pane); // onOpen will be called, but NOT onResize
+ else {
+ setAsClosed(pane); // onClose will be called
+ bindStartSlidingEvents(pane, true); // will enable events IF option is set
+ }
+
+ });
+
+ // SET ALL HANDLE DIMENSIONS
+ sizeHandles();
+ }
+
+
+ /**
+ * Initialize scrolling ui-layout-content div - if exists
+ *
+ * @see initPane() - or externally after an Ajax injection
+ * @param {string} pane The pane to process
+ * @param {boolean=} [resize=true] Size content after init
+ */
+, initContent = function (pane, resize) {
+ if (!isInitialized()) return;
+ var
+ o = options[pane]
+ , sel = o.contentSelector
+ , I = Instance[pane]
+ , $P = $Ps[pane]
+ , $C
+ ;
+ if (sel) $C = I.content = $Cs[pane] = (o.findNestedContent)
+ ? $P.find(sel).eq(0) // match 1-element only
+ : $P.children(sel).eq(0)
+ ;
+ if ($C && $C.length) {
+ $C.data("layoutRole", "content");
+ // SAVE original Content CSS
+ if (!$C.data("layoutCSS"))
+ $C.data("layoutCSS", styles($C, "height"));
+ $C.css( _c.content.cssReq );
+ if (o.applyDemoStyles) {
+ $C.css( _c.content.cssDemo ); // add padding & overflow: auto to content-div
+ $P.css( _c.content.cssDemoPane ); // REMOVE padding/scrolling from pane
+ }
+ // ensure no vertical scrollbar on pane - will mess up measurements
+ if ($P.css("overflowX").match(/(scroll|auto)/)) {
+ $P.css("overflow", "hidden");
+ }
+ state[pane].content = {}; // init content state
+ if (resize !== false) sizeContent(pane);
+ // sizeContent() is called AFTER init of all elements
+ }
+ else
+ I.content = $Cs[pane] = false;
+ }
+
+
+ /**
+ * Add resize-bars to all panes that specify it in options
+ * -dependancy: $.fn.resizable - will skip if not found
+ *
+ * @see _create()
+ * @param {string=} [panes=""] The edge(s) to process
+ */
+, initResizable = function (panes) {
+ var draggingAvailable = $.layout.plugins.draggable
+ , side // set in start()
+ ;
+ panes = panes ? panes.split(",") : _c.borderPanes;
+
+ $.each(panes, function (idx, pane) {
+ var o = options[pane];
+ if (!draggingAvailable || !$Ps[pane] || !o.resizable) {
+ o.resizable = false;
+ return true; // skip to next
+ }
+
+ var s = state[pane]
+ , z = options.zIndexes
+ , c = _c[pane]
+ , side = c.dir=="horz" ? "top" : "left"
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , base = o.resizerClass
+ , lastPos = 0 // used when live-resizing
+ , r, live // set in start because may change
+ // 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process
+ , resizerClass = base+"-drag" // resizer-drag
+ , resizerPaneClass = base+"-"+pane+"-drag" // resizer-north-drag
+ // 'helper' class is applied to the CLONED resizer-bar while it is being dragged
+ , helperClass = base+"-dragging" // resizer-dragging
+ , helperPaneClass = base+"-"+pane+"-dragging" // resizer-north-dragging
+ , helperLimitClass = base+"-dragging-limit" // resizer-drag
+ , helperPaneLimitClass = base+"-"+pane+"-dragging-limit" // resizer-north-drag
+ , helperClassesSet = false // logic var
+ ;
+
+ if (!s.isClosed)
+ $R.attr("title", o.tips.Resize)
+ .css("cursor", o.resizerCursor); // n-resize, s-resize, etc
+
+ $R.draggable({
+ containment: $N[0] // limit resizing to layout container
+ , axis: (c.dir=="horz" ? "y" : "x") // limit resizing to horz or vert axis
+ , delay: 0
+ , distance: 1
+ , grid: o.resizingGrid
+ // basic format for helper - style it using class: .ui-draggable-dragging
+ , helper: "clone"
+ , opacity: o.resizerDragOpacity
+ , addClasses: false // avoid ui-state-disabled class when disabled
+ //, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed
+ , zIndex: z.resizer_drag
+
+ , start: function (e, ui) {
+ // REFRESH options & state pointers in case we used swapPanes
+ o = options[pane];
+ s = state[pane];
+ // re-read options
+ live = o.livePaneResizing;
+
+ // ondrag_start callback - will CANCEL hide if returns false
+ // TODO: dragging CANNOT be cancelled like this, so see if there is a way?
+ if (false === _runCallbacks("ondrag_start", pane)) return false;
+
+ s.isResizing = true; // prevent pane from closing while resizing
+ state.paneResizing = pane; // easy to see if ANY pane is resizing
+ timer.clear(pane+"_closeSlider"); // just in case already triggered
+
+ // SET RESIZER LIMITS - used in drag()
+ setSizeLimits(pane); // update pane/resizer state
+ r = s.resizerPosition;
+ lastPos = ui.position[ side ]
+
+ $R.addClass( resizerClass +" "+ resizerPaneClass ); // add drag classes
+ helperClassesSet = false; // reset logic var - see drag()
+
+ // DISABLE TEXT SELECTION (probably already done by resizer.mouseOver)
+ $('body').disableSelection();
+
+ // MASK PANES CONTAINING IFRAMES, APPLETS OR OTHER TROUBLESOME ELEMENTS
+ showMasks( pane, { resizing: true });
+ }
+
+ , drag: function (e, ui) {
+ if (!helperClassesSet) { // can only add classes after clone has been added to the DOM
+ //$(".ui-draggable-dragging")
+ ui.helper
+ .addClass( helperClass +" "+ helperPaneClass ) // add helper classes
+ .css({ right: "auto", bottom: "auto" }) // fix dir="rtl" issue
+ .children().css("visibility","hidden") // hide toggler inside dragged resizer-bar
+ ;
+ helperClassesSet = true;
+ // draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane!
+ if (s.isSliding) $Ps[pane].css("zIndex", z.pane_sliding);
+ }
+ // CONTAIN RESIZER-BAR TO RESIZING LIMITS
+ var limit = 0;
+ if (ui.position[side] < r.min) {
+ ui.position[side] = r.min;
+ limit = -1;
+ }
+ else if (ui.position[side] > r.max) {
+ ui.position[side] = r.max;
+ limit = 1;
+ }
+ // ADD/REMOVE dragging-limit CLASS
+ if (limit) {
+ ui.helper.addClass( helperLimitClass +" "+ helperPaneLimitClass ); // at dragging-limit
+ window.defaultStatus = (limit>0 && pane.match(/(north|west)/)) || (limit<0 && pane.match(/(south|east)/)) ? o.tips.maxSizeWarning : o.tips.minSizeWarning;
+ }
+ else {
+ ui.helper.removeClass( helperLimitClass +" "+ helperPaneLimitClass ); // not at dragging-limit
+ window.defaultStatus = "";
+ }
+ // DYNAMICALLY RESIZE PANES IF OPTION ENABLED
+ // won't trigger unless resizer has actually moved!
+ if (live && Math.abs(ui.position[side] - lastPos) >= o.liveResizingTolerance) {
+ lastPos = ui.position[side];
+ resizePanes(e, ui, pane)
+ }
+ }
+
+ , stop: function (e, ui) {
+ $('body').enableSelection(); // RE-ENABLE TEXT SELECTION
+ window.defaultStatus = ""; // clear 'resizing limit' message from statusbar
+ $R.removeClass( resizerClass +" "+ resizerPaneClass ); // remove drag classes from Resizer
+ s.isResizing = false;
+ state.paneResizing = false; // easy to see if ANY pane is resizing
+ resizePanes(e, ui, pane, true); // true = resizingDone
+ }
+
+ });
+ });
+
+ /**
+ * resizePanes
+ *
+ * Sub-routine called from stop() - and drag() if livePaneResizing
+ *
+ * @param {!Object} evt
+ * @param {!Object} ui
+ * @param {string} pane
+ * @param {boolean=} [resizingDone=false]
+ */
+ var resizePanes = function (evt, ui, pane, resizingDone) {
+ var dragPos = ui.position
+ , c = _c[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , resizerPos
+ ;
+ switch (pane) {
+ case "north": resizerPos = dragPos.top; break;
+ case "west": resizerPos = dragPos.left; break;
+ case "south": resizerPos = sC.layoutHeight - dragPos.top - o.spacing_open; break;
+ case "east": resizerPos = sC.layoutWidth - dragPos.left - o.spacing_open; break;
+ };
+ // remove container margin from resizer position to get the pane size
+ var newSize = resizerPos - sC.inset[c.side];
+
+ // Disable OR Resize Mask(s) created in drag.start
+ if (!resizingDone) {
+ // ensure we meet liveResizingTolerance criteria
+ if (Math.abs(newSize - s.size) < o.liveResizingTolerance)
+ return; // SKIP resize this time
+ // resize the pane
+ manualSizePane(pane, newSize, false, true); // true = noAnimation
+ sizeMasks(); // resize all visible masks
+ }
+ else { // resizingDone
+ // ondrag_end callback
+ if (false !== _runCallbacks("ondrag_end", pane))
+ manualSizePane(pane, newSize, false, true); // true = noAnimation
+ hideMasks(true); // true = force hiding all masks even if one is 'sliding'
+ if (s.isSliding) // RE-SHOW 'object-masks' so objects won't show through sliding pane
+ showMasks( pane, { resizing: true });
+ }
+ };
+ }
+
+ /**
+ * sizeMask
+ *
+ * Needed to overlay a DIV over an IFRAME-pane because mask CANNOT be *inside* the pane
+ * Called when mask created, and during livePaneResizing
+ */
+, sizeMask = function () {
+ var $M = $(this)
+ , pane = $M.data("layoutMask") // eg: "west"
+ , s = state[pane]
+ ;
+ // only masks over an IFRAME-pane need manual resizing
+ if (s.tagName == "IFRAME" && s.isVisible) // no need to mask closed/hidden panes
+ $M.css({
+ top: s.offsetTop
+ , left: s.offsetLeft
+ , width: s.outerWidth
+ , height: s.outerHeight
+ });
+ /* ALT Method...
+ var $P = $Ps[pane];
+ $M.css( $P.position() ).css({ width: $P[0].offsetWidth, height: $P[0].offsetHeight });
+ */
+ }
+, sizeMasks = function () {
+ $Ms.each( sizeMask ); // resize all 'visible' masks
+ }
+
+ /**
+ * @param {string} pane The pane being resized, animated or isSliding
+ * @param {Object=} [args] (optional) Options: which masks to apply, and to which panes
+ */
+, showMasks = function (pane, args) {
+ var c = _c[pane]
+ , panes = ["center"]
+ , z = options.zIndexes
+ , a = $.extend({
+ objectsOnly: false
+ , animation: false
+ , resizing: true
+ , sliding: state[pane].isSliding
+ }, args )
+ , o, s
+ ;
+ if (a.resizing)
+ panes.push( pane );
+ if (a.sliding)
+ panes.push( _c.oppositeEdge[pane] ); // ADD the oppositeEdge-pane
+
+ if (c.dir === "horz") {
+ panes.push("west");
+ panes.push("east");
+ }
+
+ $.each(panes, function(i,p){
+ s = state[p];
+ o = options[p];
+ if (s.isVisible && ( o.maskObjects || (!a.objectsOnly && o.maskContents) )) {
+ getMasks(p).each(function(){
+ sizeMask.call(this);
+ this.style.zIndex = s.isSliding ? z.pane_sliding+1 : z.pane_normal+1
+ this.style.display = "block";
+ });
+ }
+ });
+ }
+
+ /**
+ * @param {boolean=} force Hide masks even if a pane is sliding
+ */
+, hideMasks = function (force) {
+ // ensure no pane is resizing - could be a timing issue
+ if (force || !state.paneResizing) {
+ $Ms.hide(); // hide ALL masks
+ }
+ // if ANY pane is sliding, then DO NOT remove masks from panes with maskObjects enabled
+ else if (!force && !$.isEmptyObject( state.panesSliding )) {
+ var i = $Ms.length - 1
+ , p, $M;
+ for (; i >= 0; i--) {
+ $M = $Ms.eq(i);
+ p = $M.data("layoutMask");
+ if (!options[p].maskObjects) {
+ $M.hide();
+ }
+ }
+ }
+ }
+
+ /**
+ * @param {string} pane
+ */
+, getMasks = function (pane) {
+ var $Masks = $([])
+ , $M, i = 0, c = $Ms.length
+ ;
+ for (; i CSS
+ if (sC.tagName === "BODY" && ($N = $("html")).data(css)) // RESET CSS
+ $N.css( $N.data(css) ).removeData(css);
+
+ // trigger plugins for this layout, if there are any
+ runPluginCallbacks( Instance, $.layout.onDestroy );
+
+ // trigger state-management and onunload callback
+ unload();
+
+ // clear the Instance of everything except for container & options (so could recreate)
+ // RE-CREATE: myLayout = myLayout.container.layout( myLayout.options );
+ for (var n in Instance)
+ if (!n.match(/^(container|options)$/)) delete Instance[ n ];
+ // add a 'destroyed' flag to make it easy to check
+ Instance.destroyed = true;
+
+ // if this is a child layout, CLEAR the child-pointer in the parent
+ /* for now the pointer REMAINS, but with only container, options and destroyed keys
+ if (parentPane) {
+ var layout = parentPane.pane.data("parentLayout")
+ , key = layout.options.instanceKey || 'error';
+ // THIS SYNTAX MAY BE WRONG!
+ parentPane.children[key] = layout.children[ parentPane.name ].children[key] = null;
+ }
+ */
+
+ return Instance; // for coding convenience
+ }
+
+ /**
+ * Remove a pane from the layout - subroutine of destroy()
+ *
+ * @see destroy()
+ * @param {(string|Object)} evt_or_pane The pane to process
+ * @param {boolean=} [remove=false] Remove the DOM element?
+ * @param {boolean=} [skipResize=false] Skip calling resizeAll()?
+ * @param {boolean=} [destroyChild=true] Destroy Child-layouts? If not passed, obeys options setting
+ */
+, removePane = function (evt_or_pane, remove, skipResize, destroyChild) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $P = $Ps[pane]
+ , $C = $Cs[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ ;
+ // NOTE: elements can still exist even after remove()
+ // so check for missing data(), which is cleared by removed()
+ if ($P && $.isEmptyObject( $P.data() )) $P = false;
+ if ($C && $.isEmptyObject( $C.data() )) $C = false;
+ if ($R && $.isEmptyObject( $R.data() )) $R = false;
+ if ($T && $.isEmptyObject( $T.data() )) $T = false;
+
+ if ($P) $P.stop(true, true);
+
+ var o = options[pane]
+ , s = state[pane]
+ , d = "layout"
+ , css = "layoutCSS"
+ , pC = children[pane]
+ , hasChildren = $.isPlainObject( pC ) && !$.isEmptyObject( pC )
+ , destroy = destroyChild !== undefined ? destroyChild : o.destroyChildren
+ ;
+ // FIRST destroy the child-layout(s)
+ if (hasChildren && destroy) {
+ $.each( pC, function (key, child) {
+ if (!child.destroyed)
+ child.destroy(true);// tell child-layout to destroy ALL its child-layouts too
+ if (child.destroyed) // destroy was successful
+ delete pC[key];
+ });
+ // if no more children, remove the children hash
+ if ($.isEmptyObject( pC )) {
+ pC = children[pane] = null; // clear children hash
+ hasChildren = false;
+ }
+ }
+
+ // Note: can't 'remove' a pane element with non-destroyed children
+ if ($P && remove && !hasChildren)
+ $P.remove(); // remove the pane-element and everything inside it
+ else if ($P && $P[0]) {
+ // create list of ALL pane-classes that need to be removed
+ var root = o.paneClass // default="ui-layout-pane"
+ , pRoot = root +"-"+ pane // eg: "ui-layout-pane-west"
+ , _open = "-open"
+ , _sliding= "-sliding"
+ , _closed = "-closed"
+ , classes = [ root, root+_open, root+_closed, root+_sliding, // generic classes
+ pRoot, pRoot+_open, pRoot+_closed, pRoot+_sliding ] // pane-specific classes
+ ;
+ $.merge(classes, getHoverClasses($P, true)); // ADD hover-classes
+ // remove all Layout classes from pane-element
+ $P .removeClass( classes.join(" ") ) // remove ALL pane-classes
+ .removeData("parentLayout")
+ .removeData("layoutPane")
+ .removeData("layoutRole")
+ .removeData("layoutEdge")
+ .removeData("autoHidden") // in case set
+ .unbind("."+ sID) // remove ALL Layout events
+ // TODO: remove these extra unbind commands when jQuery is fixed
+ //.unbind("mouseenter"+ sID)
+ //.unbind("mouseleave"+ sID)
+ ;
+ // do NOT reset CSS if this pane/content is STILL the container of a nested layout!
+ // the nested layout will reset its 'container' CSS when/if it is destroyed
+ if (hasChildren && $C) {
+ // a content-div may not have a specific width, so give it one to contain the Layout
+ $C.width( $C.width() );
+ $.each( pC, function (key, child) {
+ child.resizeAll(); // resize the Layout
+ });
+ }
+ else if ($C)
+ $C.css( $C.data(css) ).removeData(css).removeData("layoutRole");
+ // remove pane AFTER content in case there was a nested layout
+ if (!$P.data(d))
+ $P.css( $P.data(css) ).removeData(css);
+ }
+
+ // REMOVE pane resizer and toggler elements
+ if ($T) $T.remove();
+ if ($R) $R.remove();
+
+ // CLEAR all pointers and state data
+ Instance[pane] = $Ps[pane] = $Cs[pane] = $Rs[pane] = $Ts[pane] = false;
+ s = { removed: true };
+
+ if (!skipResize)
+ resizeAll();
+ }
+
+
+/*
+ * ###########################
+ * ACTION METHODS
+ * ###########################
+ */
+
+ /**
+ * @param {string} pane
+ */
+, _hidePane = function (pane) {
+ var $P = $Ps[pane]
+ , o = options[pane]
+ , s = $P[0].style
+ ;
+ if (o.useOffscreenClose) {
+ if (!$P.data(_c.offscreenReset))
+ $P.data(_c.offscreenReset, { left: s.left, right: s.right });
+ $P.css( _c.offscreenCSS );
+ }
+ else
+ $P.hide().removeData(_c.offscreenReset);
+ }
+
+ /**
+ * @param {string} pane
+ */
+, _showPane = function (pane) {
+ var $P = $Ps[pane]
+ , o = options[pane]
+ , off = _c.offscreenCSS
+ , old = $P.data(_c.offscreenReset)
+ , s = $P[0].style
+ ;
+ $P .show() // ALWAYS show, just in case
+ .removeData(_c.offscreenReset);
+ if (o.useOffscreenClose && old) {
+ if (s.left == off.left)
+ s.left = old.left;
+ if (s.right == off.right)
+ s.right = old.right;
+ }
+ }
+
+
+ /**
+ * Completely 'hides' a pane, including its spacing - as if it does not exist
+ * The pane is not actually 'removed' from the source, so can use 'show' to un-hide it
+ *
+ * @param {(string|Object)} evt_or_pane The pane being hidden, ie: north, south, east, or west
+ * @param {boolean=} [noAnimation=false]
+ */
+, hide = function (evt_or_pane, noAnimation) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , o = options[pane]
+ , s = state[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ ;
+ if (!$P || s.isHidden) return; // pane does not exist OR is already hidden
+
+ // onhide_start callback - will CANCEL hide if returns false
+ if (state.initialized && false === _runCallbacks("onhide_start", pane)) return;
+
+ s.isSliding = false; // just in case
+ delete state.panesSliding[pane];
+
+ // now hide the elements
+ if ($R) $R.hide(); // hide resizer-bar
+ if (!state.initialized || s.isClosed) {
+ s.isClosed = true; // to trigger open-animation on show()
+ s.isHidden = true;
+ s.isVisible = false;
+ if (!state.initialized)
+ _hidePane(pane); // no animation when loading page
+ sizeMidPanes(_c[pane].dir === "horz" ? "" : "center");
+ if (state.initialized || o.triggerEventsOnLoad)
+ _runCallbacks("onhide_end", pane);
+ }
+ else {
+ s.isHiding = true; // used by onclose
+ close(pane, false, noAnimation); // adjust all panes to fit
+ }
+ }
+
+ /**
+ * Show a hidden pane - show as 'closed' by default unless openPane = true
+ *
+ * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
+ * @param {boolean=} [openPane=false]
+ * @param {boolean=} [noAnimation=false]
+ * @param {boolean=} [noAlert=false]
+ */
+, show = function (evt_or_pane, openPane, noAnimation, noAlert) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , o = options[pane]
+ , s = state[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ ;
+ if (!$P || !s.isHidden) return; // pane does not exist OR is not hidden
+
+ // onshow_start callback - will CANCEL show if returns false
+ if (false === _runCallbacks("onshow_start", pane)) return;
+
+ s.isShowing = true; // used by onopen/onclose
+ //s.isHidden = false; - will be set by open/close - if not cancelled
+ s.isSliding = false; // just in case
+ delete state.panesSliding[pane];
+
+ // now show the elements
+ //if ($R) $R.show(); - will be shown by open/close
+ if (openPane === false)
+ close(pane, true); // true = force
+ else
+ open(pane, false, noAnimation, noAlert); // adjust all panes to fit
+ }
+
+
+ /**
+ * Toggles a pane open/closed by calling either open or close
+ *
+ * @param {(string|Object)} evt_or_pane The pane being toggled, ie: north, south, east, or west
+ * @param {boolean=} [slide=false]
+ */
+, toggle = function (evt_or_pane, slide) {
+ if (!isInitialized()) return;
+ var evt = evtObj(evt_or_pane)
+ , pane = evtPane.call(this, evt_or_pane)
+ , s = state[pane]
+ ;
+ if (evt) // called from to $R.dblclick OR triggerPaneEvent
+ evt.stopImmediatePropagation();
+ if (s.isHidden)
+ show(pane); // will call 'open' after unhiding it
+ else if (s.isClosed)
+ open(pane, !!slide);
+ else
+ close(pane);
+ }
+
+
+ /**
+ * Utility method used during init or other auto-processes
+ *
+ * @param {string} pane The pane being closed
+ * @param {boolean=} [setHandles=false]
+ */
+, _closePane = function (pane, setHandles) {
+ var
+ $P = $Ps[pane]
+ , s = state[pane]
+ ;
+ _hidePane(pane);
+ s.isClosed = true;
+ s.isVisible = false;
+ if (setHandles) setAsClosed(pane);
+ }
+
+ /**
+ * Close the specified pane (animation optional), and resize all other panes as needed
+ *
+ * @param {(string|Object)} evt_or_pane The pane being closed, ie: north, south, east, or west
+ * @param {boolean=} [force=false]
+ * @param {boolean=} [noAnimation=false]
+ * @param {boolean=} [skipCallback=false]
+ */
+, close = function (evt_or_pane, force, noAnimation, skipCallback) {
+ var pane = evtPane.call(this, evt_or_pane);
+ // if pane has been initialized, but NOT the complete layout, close pane instantly
+ if (!state.initialized && $Ps[pane]) {
+ _closePane(pane, true); // INIT pane as closed
+ return;
+ }
+ if (!isInitialized()) return;
+
+ var
+ $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , doFX, isShowing, isHiding, wasSliding;
+
+ // QUEUE in case another action/animation is in progress
+ $N.queue(function( queueNext ){
+
+ if ( !$P
+ || (!o.closable && !s.isShowing && !s.isHiding) // invalid request // (!o.resizable && !o.closable) ???
+ || (!force && s.isClosed && !s.isShowing) // already closed
+ ) return queueNext();
+
+ // onclose_start callback - will CANCEL hide if returns false
+ // SKIP if just 'showing' a hidden pane as 'closed'
+ var abort = !s.isShowing && false === _runCallbacks("onclose_start", pane);
+
+ // transfer logic vars to temp vars
+ isShowing = s.isShowing;
+ isHiding = s.isHiding;
+ wasSliding = s.isSliding;
+ // now clear the logic vars (REQUIRED before aborting)
+ delete s.isShowing;
+ delete s.isHiding;
+
+ if (abort) return queueNext();
+
+ doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none");
+ s.isMoving = true;
+ s.isClosed = true;
+ s.isVisible = false;
+ // update isHidden BEFORE sizing panes
+ if (isHiding) s.isHidden = true;
+ else if (isShowing) s.isHidden = false;
+
+ if (s.isSliding) // pane is being closed, so UNBIND trigger events
+ bindStopSlidingEvents(pane, false); // will set isSliding=false
+ else // resize panes adjacent to this one
+ sizeMidPanes(_c[pane].dir === "horz" ? "" : "center", false); // false = NOT skipCallback
+
+ // if this pane has a resizer bar, move it NOW - before animation
+ setAsClosed(pane);
+
+ // CLOSE THE PANE
+ if (doFX) { // animate the close
+ lockPaneForFX(pane, true); // need to set left/top so animation will work
+ $P.hide( o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () {
+ lockPaneForFX(pane, false); // undo
+ if (s.isClosed) close_2();
+ queueNext();
+ });
+ }
+ else { // hide the pane without animation
+ _hidePane(pane);
+ close_2();
+ queueNext();
+ };
+ });
+
+ // SUBROUTINE
+ function close_2 () {
+ s.isMoving = false;
+ bindStartSlidingEvents(pane, true); // will enable if o.slidable = true
+
+ // if opposite-pane was autoClosed, see if it can be autoOpened now
+ var altPane = _c.oppositeEdge[pane];
+ if (state[ altPane ].noRoom) {
+ setSizeLimits( altPane );
+ makePaneFit( altPane );
+ }
+
+ if (!skipCallback && (state.initialized || o.triggerEventsOnLoad)) {
+ // onclose callback - UNLESS just 'showing' a hidden pane as 'closed'
+ if (!isShowing) _runCallbacks("onclose_end", pane);
+ // onhide OR onshow callback
+ if (isShowing) _runCallbacks("onshow_end", pane);
+ if (isHiding) _runCallbacks("onhide_end", pane);
+ }
+ }
+ }
+
+ /**
+ * @param {string} pane The pane just closed, ie: north, south, east, or west
+ */
+, setAsClosed = function (pane) {
+ if (!$Rs[pane]) return; // handles not initialized yet!
+ var
+ $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , side = _c[pane].side
+ , rClass = o.resizerClass
+ , tClass = o.togglerClass
+ , _pane = "-"+ pane // used for classNames
+ , _open = "-open"
+ , _sliding= "-sliding"
+ , _closed = "-closed"
+ ;
+ $R
+ .css(side, sC.inset[side]) // move the resizer
+ .removeClass( rClass+_open +" "+ rClass+_pane+_open )
+ .removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding )
+ .addClass( rClass+_closed +" "+ rClass+_pane+_closed )
+ ;
+ // DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvents?
+ if (o.resizable && $.layout.plugins.draggable)
+ $R
+ .draggable("disable")
+ .removeClass("ui-state-disabled") // do NOT apply disabled styling - not suitable here
+ .css("cursor", "default")
+ .attr("title","")
+ ;
+
+ // if pane has a toggler button, adjust that too
+ if ($T) {
+ $T
+ .removeClass( tClass+_open +" "+ tClass+_pane+_open )
+ .addClass( tClass+_closed +" "+ tClass+_pane+_closed )
+ .attr("title", o.tips.Open) // may be blank
+ ;
+ // toggler-content - if exists
+ $T.children(".content-open").hide();
+ $T.children(".content-closed").css("display","block");
+ }
+
+ // sync any 'pin buttons'
+ syncPinBtns(pane, false);
+
+ if (state.initialized) {
+ // resize 'length' and position togglers for adjacent panes
+ sizeHandles();
+ }
+ }
+
+ /**
+ * Open the specified pane (animation optional), and resize all other panes as needed
+ *
+ * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
+ * @param {boolean=} [slide=false]
+ * @param {boolean=} [noAnimation=false]
+ * @param {boolean=} [noAlert=false]
+ */
+, open = function (evt_or_pane, slide, noAnimation, noAlert) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , doFX, isShowing
+ ;
+ // QUEUE in case another action/animation is in progress
+ $N.queue(function( queueNext ){
+
+ if ( !$P
+ || (!o.resizable && !o.closable && !s.isShowing) // invalid request
+ || (s.isVisible && !s.isSliding) // already open
+ ) return queueNext();
+
+ // pane can ALSO be unhidden by just calling show(), so handle this scenario
+ if (s.isHidden && !s.isShowing) {
+ queueNext(); // call before show() because it needs the queue free
+ show(pane, true);
+ return;
+ }
+
+ if (s.autoResize && s.size != o.size) // resize pane to original size set in options
+ sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize
+ else
+ // make sure there is enough space available to open the pane
+ setSizeLimits(pane, slide);
+
+ // onopen_start callback - will CANCEL open if returns false
+ var cbReturn = _runCallbacks("onopen_start", pane);
+
+ if (cbReturn === "abort")
+ return queueNext();
+
+ // update pane-state again in case options were changed in onopen_start
+ if (cbReturn !== "NC") // NC = "No Callback"
+ setSizeLimits(pane, slide);
+
+ if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN!
+ syncPinBtns(pane, false); // make sure pin-buttons are reset
+ if (!noAlert && o.tips.noRoomToOpen)
+ alert(o.tips.noRoomToOpen);
+ return queueNext(); // ABORT
+ }
+
+ if (slide) // START Sliding - will set isSliding=true
+ bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane
+ else if (s.isSliding) // PIN PANE (stop sliding) - open pane 'normally' instead
+ bindStopSlidingEvents(pane, false); // UNBIND trigger events - will set isSliding=false
+ else if (o.slidable)
+ bindStartSlidingEvents(pane, false); // UNBIND trigger events
+
+ s.noRoom = false; // will be reset by makePaneFit if 'noRoom'
+ makePaneFit(pane);
+
+ // transfer logic var to temp var
+ isShowing = s.isShowing;
+ // now clear the logic var
+ delete s.isShowing;
+
+ doFX = !noAnimation && s.isClosed && (o.fxName_open != "none");
+ s.isMoving = true;
+ s.isVisible = true;
+ s.isClosed = false;
+ // update isHidden BEFORE sizing panes - WHY??? Old?
+ if (isShowing) s.isHidden = false;
+
+ if (doFX) { // ANIMATE
+ // mask adjacent panes with objects
+ lockPaneForFX(pane, true); // need to set left/top so animation will work
+ $P.show( o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() {
+ lockPaneForFX(pane, false); // undo
+ if (s.isVisible) open_2(); // continue
+ queueNext();
+ });
+ }
+ else { // no animation
+ _showPane(pane);// just show pane and...
+ open_2(); // continue
+ queueNext();
+ };
+ });
+
+ // SUBROUTINE
+ function open_2 () {
+ s.isMoving = false;
+
+ // cure iframe display issues
+ _fixIframe(pane);
+
+ // NOTE: if isSliding, then other panes are NOT 'resized'
+ if (!s.isSliding) { // resize all panes adjacent to this one
+ sizeMidPanes(_c[pane].dir=="vert" ? "center" : "", false); // false = NOT skipCallback
+ }
+
+ // set classes, position handles and execute callbacks...
+ setAsOpen(pane);
+ };
+
+ }
+
+ /**
+ * @param {string} pane The pane just opened, ie: north, south, east, or west
+ * @param {boolean=} [skipCallback=false]
+ */
+, setAsOpen = function (pane, skipCallback) {
+ var
+ $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , side = _c[pane].side
+ , rClass = o.resizerClass
+ , tClass = o.togglerClass
+ , _pane = "-"+ pane // used for classNames
+ , _open = "-open"
+ , _closed = "-closed"
+ , _sliding= "-sliding"
+ ;
+ $R
+ .css(side, sC.inset[side] + getPaneSize(pane)) // move the resizer
+ .removeClass( rClass+_closed +" "+ rClass+_pane+_closed )
+ .addClass( rClass+_open +" "+ rClass+_pane+_open )
+ ;
+ if (s.isSliding)
+ $R.addClass( rClass+_sliding +" "+ rClass+_pane+_sliding )
+ else // in case 'was sliding'
+ $R.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding )
+
+ removeHover( 0, $R ); // remove hover classes
+ if (o.resizable && $.layout.plugins.draggable)
+ $R .draggable("enable")
+ .css("cursor", o.resizerCursor)
+ .attr("title", o.tips.Resize);
+ else if (!s.isSliding)
+ $R.css("cursor", "default"); // n-resize, s-resize, etc
+
+ // if pane also has a toggler button, adjust that too
+ if ($T) {
+ $T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed )
+ .addClass( tClass+_open +" "+ tClass+_pane+_open )
+ .attr("title", o.tips.Close); // may be blank
+ removeHover( 0, $T ); // remove hover classes
+ // toggler-content - if exists
+ $T.children(".content-closed").hide();
+ $T.children(".content-open").css("display","block");
+ }
+
+ // sync any 'pin buttons'
+ syncPinBtns(pane, !s.isSliding);
+
+ // update pane-state dimensions - BEFORE resizing content
+ $.extend(s, elDims($P));
+
+ if (state.initialized) {
+ // resize resizer & toggler sizes for all panes
+ sizeHandles();
+ // resize content every time pane opens - to be sure
+ sizeContent(pane, true); // true = remeasure headers/footers, even if 'pane.isMoving'
+ }
+
+ if (!skipCallback && (state.initialized || o.triggerEventsOnLoad) && $P.is(":visible")) {
+ // onopen callback
+ _runCallbacks("onopen_end", pane);
+ // onshow callback - TODO: should this be here?
+ if (s.isShowing) _runCallbacks("onshow_end", pane);
+
+ // ALSO call onresize because layout-size *may* have changed while pane was closed
+ if (state.initialized)
+ _runCallbacks("onresize_end", pane);
+ }
+
+ // TODO: Somehow sizePane("north") is being called after this point???
+ }
+
+
+ /**
+ * slideOpen / slideClose / slideToggle
+ *
+ * Pass-though methods for sliding
+ */
+, slideOpen = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var evt = evtObj(evt_or_pane)
+ , pane = evtPane.call(this, evt_or_pane)
+ , s = state[pane]
+ , delay = options[pane].slideDelay_open
+ ;
+ // prevent event from triggering on NEW resizer binding created below
+ if (evt) evt.stopImmediatePropagation();
+
+ if (s.isClosed && evt && evt.type === "mouseenter" && delay > 0)
+ // trigger = mouseenter - use a delay
+ timer.set(pane+"_openSlider", open_NOW, delay);
+ else
+ open_NOW(); // will unbind events if is already open
+
+ /**
+ * SUBROUTINE for timed open
+ */
+ function open_NOW () {
+ if (!s.isClosed) // skip if no longer closed!
+ bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane
+ else if (!s.isMoving)
+ open(pane, true); // true = slide - open() will handle binding
+ };
+ }
+
+, slideClose = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var evt = evtObj(evt_or_pane)
+ , pane = evtPane.call(this, evt_or_pane)
+ , o = options[pane]
+ , s = state[pane]
+ , delay = s.isMoving ? 1000 : 300 // MINIMUM delay - option may override
+ ;
+ if (s.isClosed || s.isResizing)
+ return; // skip if already closed OR in process of resizing
+ else if (o.slideTrigger_close === "click")
+ close_NOW(); // close immediately onClick
+ else if (o.preventQuickSlideClose && s.isMoving)
+ return; // handle Chrome quick-close on slide-open
+ else if (o.preventPrematureSlideClose && evt && $.layout.isMouseOverElem(evt, $Ps[pane]))
+ return; // handle incorrect mouseleave trigger, like when over a SELECT-list in IE
+ else if (evt) // trigger = mouseleave - use a delay
+ // 1 sec delay if 'opening', else .3 sec
+ timer.set(pane+"_closeSlider", close_NOW, max(o.slideDelay_close, delay));
+ else // called programically
+ close_NOW();
+
+ /**
+ * SUBROUTINE for timed close
+ */
+ function close_NOW () {
+ if (s.isClosed) // skip 'close' if already closed!
+ bindStopSlidingEvents(pane, false); // UNBIND trigger events - TODO: is this needed here?
+ else if (!s.isMoving)
+ close(pane); // close will handle unbinding
+ };
+ }
+
+ /**
+ * @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
+ */
+, slideToggle = function (evt_or_pane) {
+ var pane = evtPane.call(this, evt_or_pane);
+ toggle(pane, true);
+ }
+
+
+ /**
+ * Must set left/top on East/South panes so animation will work properly
+ *
+ * @param {string} pane The pane to lock, 'east' or 'south' - any other is ignored!
+ * @param {boolean} doLock true = set left/top, false = remove
+ */
+, lockPaneForFX = function (pane, doLock) {
+ var $P = $Ps[pane]
+ , s = state[pane]
+ , o = options[pane]
+ , z = options.zIndexes
+ ;
+ if (doLock) {
+ showMasks( pane, { animation: true, objectsOnly: true });
+ $P.css({ zIndex: z.pane_animate }); // overlay all elements during animation
+ if (pane=="south")
+ $P.css({ top: sC.inset.top + sC.innerHeight - $P.outerHeight() });
+ else if (pane=="east")
+ $P.css({ left: sC.inset.left + sC.innerWidth - $P.outerWidth() });
+ }
+ else { // animation DONE - RESET CSS
+ hideMasks();
+ $P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) });
+ if (pane=="south")
+ $P.css({ top: "auto" });
+ // if pane is positioned 'off-screen', then DO NOT screw with it!
+ else if (pane=="east" && !$P.css("left").match(/\-99999/))
+ $P.css({ left: "auto" });
+ // fix anti-aliasing in IE - only needed for animations that change opacity
+ if (browser.msie && o.fxOpacityFix && o.fxName_open != "slide" && $P.css("filter") && $P.css("opacity") == 1)
+ $P[0].style.removeAttribute('filter');
+ }
+ }
+
+
+ /**
+ * Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger
+ *
+ * @see open(), close()
+ * @param {string} pane The pane to enable/disable, 'north', 'south', etc.
+ * @param {boolean} enable Enable or Disable sliding?
+ */
+, bindStartSlidingEvents = function (pane, enable) {
+ var o = options[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , evtName = o.slideTrigger_open.toLowerCase()
+ ;
+ if (!$R || (enable && !o.slidable)) return;
+
+ // make sure we have a valid event
+ if (evtName.match(/mouseover/))
+ evtName = o.slideTrigger_open = "mouseenter";
+ else if (!evtName.match(/(click|dblclick|mouseenter)/))
+ evtName = o.slideTrigger_open = "click";
+
+ // must remove double-click-toggle when using dblclick-slide
+ if (o.resizerDblClickToggle && evtName.match(/click/)) {
+ $R[enable ? "unbind" : "bind"]('dblclick.'+ sID, toggle)
+ }
+
+ $R
+ // add or remove event
+ [enable ? "bind" : "unbind"](evtName +'.'+ sID, slideOpen)
+ // set the appropriate cursor & title/tip
+ .css("cursor", enable ? o.sliderCursor : "default")
+ .attr("title", enable ? o.tips.Slide : "")
+ ;
+ }
+
+ /**
+ * Add or remove 'mouseleave' events to 'slide close' when pane is 'sliding' open or closed
+ * Also increases zIndex when pane is sliding open
+ * See bindStartSlidingEvents for code to control 'slide open'
+ *
+ * @see slideOpen(), slideClose()
+ * @param {string} pane The pane to process, 'north', 'south', etc.
+ * @param {boolean} enable Enable or Disable events?
+ */
+, bindStopSlidingEvents = function (pane, enable) {
+ var o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , z = options.zIndexes
+ , evtName = o.slideTrigger_close.toLowerCase()
+ , action = (enable ? "bind" : "unbind")
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ ;
+ timer.clear(pane+"_closeSlider"); // just in case
+
+ if (enable) {
+ s.isSliding = true;
+ state.panesSliding[pane] = true;
+ // remove 'slideOpen' event from resizer
+ // ALSO will raise the zIndex of the pane & resizer
+ bindStartSlidingEvents(pane, false);
+ }
+ else {
+ s.isSliding = false;
+ delete state.panesSliding[pane];
+ }
+
+ // RE/SET zIndex - increases when pane is sliding-open, resets to normal when not
+ $P.css("zIndex", enable ? z.pane_sliding : z.pane_normal);
+ $R.css("zIndex", enable ? z.pane_sliding+2 : z.resizer_normal); // NOTE: mask = pane_sliding+1
+
+ // make sure we have a valid event
+ if (!evtName.match(/(click|mouseleave)/))
+ evtName = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout'
+
+ // add/remove slide triggers
+ $R[action](evtName, slideClose); // base event on resize
+ // need extra events for mouseleave
+ if (evtName === "mouseleave") {
+ // also close on pane.mouseleave
+ $P[action]("mouseleave."+ sID, slideClose);
+ // cancel timer when mouse moves between 'pane' and 'resizer'
+ $R[action]("mouseenter."+ sID, cancelMouseOut);
+ $P[action]("mouseenter."+ sID, cancelMouseOut);
+ }
+
+ if (!enable)
+ timer.clear(pane+"_closeSlider");
+ else if (evtName === "click" && !o.resizable) {
+ // IF pane is not resizable (which already has a cursor and tip)
+ // then set the a cursor & title/tip on resizer when sliding
+ $R.css("cursor", enable ? o.sliderCursor : "default");
+ $R.attr("title", enable ? o.tips.Close : ""); // use Toggler-tip, eg: "Close Pane"
+ }
+
+ // SUBROUTINE for mouseleave timer clearing
+ function cancelMouseOut (evt) {
+ timer.clear(pane+"_closeSlider");
+ evt.stopPropagation();
+ }
+ }
+
+
+ /**
+ * Hides/closes a pane if there is insufficient room - reverses this when there is room again
+ * MUST have already called setSizeLimits() before calling this method
+ *
+ * @param {string} pane The pane being resized
+ * @param {boolean=} [isOpening=false] Called from onOpen?
+ * @param {boolean=} [skipCallback=false] Should the onresize callback be run?
+ * @param {boolean=} [force=false]
+ */
+, makePaneFit = function (pane, isOpening, skipCallback, force) {
+ var o = options[pane]
+ , s = state[pane]
+ , c = _c[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , isSidePane = c.dir==="vert"
+ , hasRoom = false
+ ;
+ // special handling for center & east/west panes
+ if (pane === "center" || (isSidePane && s.noVerticalRoom)) {
+ // see if there is enough room to display the pane
+ // ERROR: hasRoom = s.minHeight <= s.maxHeight && (isSidePane || s.minWidth <= s.maxWidth);
+ hasRoom = (s.maxHeight >= 0);
+ if (hasRoom && s.noRoom) { // previously hidden due to noRoom, so show now
+ _showPane(pane);
+ if ($R) $R.show();
+ s.isVisible = true;
+ s.noRoom = false;
+ if (isSidePane) s.noVerticalRoom = false;
+ _fixIframe(pane);
+ }
+ else if (!hasRoom && !s.noRoom) { // not currently hidden, so hide now
+ _hidePane(pane);
+ if ($R) $R.hide();
+ s.isVisible = false;
+ s.noRoom = true;
+ }
+ }
+
+ // see if there is enough room to fit the border-pane
+ if (pane === "center") {
+ // ignore center in this block
+ }
+ else if (s.minSize <= s.maxSize) { // pane CAN fit
+ hasRoom = true;
+ if (s.size > s.maxSize) // pane is too big - shrink it
+ sizePane(pane, s.maxSize, skipCallback, true, force); // true = noAnimation
+ else if (s.size < s.minSize) // pane is too small - enlarge it
+ sizePane(pane, s.minSize, skipCallback, true, force); // true = noAnimation
+ // need s.isVisible because new pseudoClose method keeps pane visible, but off-screen
+ else if ($R && s.isVisible && $P.is(":visible")) {
+ // make sure resizer-bar is positioned correctly
+ // handles situation where nested layout was 'hidden' when initialized
+ var pos = s.size + sC.inset[c.side];
+ if ($.layout.cssNum( $R, c.side ) != pos) $R.css( c.side, pos );
+ }
+
+ // if was previously hidden due to noRoom, then RESET because NOW there is room
+ if (s.noRoom) {
+ // s.noRoom state will be set by open or show
+ if (s.wasOpen && o.closable) {
+ if (o.autoReopen)
+ open(pane, false, true, true); // true = noAnimation, true = noAlert
+ else // leave the pane closed, so just update state
+ s.noRoom = false;
+ }
+ else
+ show(pane, s.wasOpen, true, true); // true = noAnimation, true = noAlert
+ }
+ }
+ else { // !hasRoom - pane CANNOT fit
+ if (!s.noRoom) { // pane not set as noRoom yet, so hide or close it now...
+ s.noRoom = true; // update state
+ s.wasOpen = !s.isClosed && !s.isSliding;
+ if (s.isClosed){} // SKIP
+ else if (o.closable) // 'close' if possible
+ close(pane, true, true); // true = force, true = noAnimation
+ else // 'hide' pane if cannot just be closed
+ hide(pane, true); // true = noAnimation
+ }
+ }
+ }
+
+
+ /**
+ * manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized'
+ *
+ * @param {(string|Object)} evt_or_pane The pane being resized
+ * @param {number} size The *desired* new size for this pane - will be validated
+ * @param {boolean=} [skipCallback=false] Should the onresize callback be run?
+ * @param {boolean=} [noAnimation=false]
+ * @param {boolean=} [force=false] Force resizing even if does not seem necessary
+ */
+, manualSizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , o = options[pane]
+ , s = state[pane]
+ // if resizing callbacks have been delayed and resizing is now DONE, force resizing to complete...
+ , forceResize = force || (o.livePaneResizing && !s.isResizing)
+ ;
+ // ANY call to manualSizePane disables autoResize - ie, percentage sizing
+ s.autoResize = false;
+ // flow-through...
+ sizePane(pane, size, skipCallback, noAnimation, forceResize); // will animate resize if option enabled
+ }
+
+ /**
+ * sizePane is called only by internal methods whenever a pane needs to be resized
+ *
+ * @param {(string|Object)} evt_or_pane The pane being resized
+ * @param {number} size The *desired* new size for this pane - will be validated
+ * @param {boolean=} [skipCallback=false] Should the onresize callback be run?
+ * @param {boolean=} [noAnimation=false]
+ * @param {boolean=} [force=false] Force resizing even if does not seem necessary
+ */
+, sizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane) // probably NEVER called from event?
+ , o = options[pane]
+ , s = state[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , side = _c[pane].side
+ , dimName = _c[pane].sizeType.toLowerCase()
+ , skipResizeWhileDragging = s.isResizing && !o.triggerEventsDuringLiveResize
+ , doFX = noAnimation !== true && o.animatePaneSizing
+ , oldSize, newSize
+ ;
+ // QUEUE in case another action/animation is in progress
+ $N.queue(function( queueNext ){
+ // calculate 'current' min/max sizes
+ setSizeLimits(pane); // update pane-state
+ oldSize = s.size;
+ size = _parseSize(pane, size); // handle percentages & auto
+ size = max(size, _parseSize(pane, o.minSize));
+ size = min(size, s.maxSize);
+ if (size < s.minSize) { // not enough room for pane!
+ queueNext(); // call before makePaneFit() because it needs the queue free
+ makePaneFit(pane, false, skipCallback); // will hide or close pane
+ return;
+ }
+
+ // IF newSize is same as oldSize, then nothing to do - abort
+ if (!force && size === oldSize)
+ return queueNext();
+
+ s.newSize = size;
+
+ // onresize_start callback CANNOT cancel resizing because this would break the layout!
+ if (!skipCallback && state.initialized && s.isVisible)
+ _runCallbacks("onresize_start", pane);
+
+ // resize the pane, and make sure its visible
+ newSize = cssSize(pane, size);
+
+ if (doFX && $P.is(":visible")) { // ANIMATE
+ var fx = $.layout.effects.size[pane] || $.layout.effects.size.all
+ , easing = o.fxSettings_size.easing || fx.easing
+ , z = options.zIndexes
+ , props = {};
+ props[ dimName ] = newSize +'px';
+ s.isMoving = true;
+ // overlay all elements during animation
+ $P.css({ zIndex: z.pane_animate })
+ .show().animate( props, o.fxSpeed_size, easing, function(){
+ // reset zIndex after animation
+ $P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) });
+ s.isMoving = false;
+ delete s.newSize;
+ sizePane_2(); // continue
+ queueNext();
+ });
+ }
+ else { // no animation
+ $P.css( dimName, newSize ); // resize pane
+ delete s.newSize;
+ // if pane is visible, then
+ if ($P.is(":visible"))
+ sizePane_2(); // continue
+ else {
+ // pane is NOT VISIBLE, so just update state data...
+ // when pane is *next opened*, it will have the new size
+ s.size = size; // update state.size
+ $.extend(s, elDims($P)); // update state dimensions
+ }
+ queueNext();
+ };
+
+ });
+
+ // SUBROUTINE
+ function sizePane_2 () {
+ /* Panes are sometimes not sized precisely in some browsers!?
+ * This code will resize the pane up to 3 times to nudge the pane to the correct size
+ */
+ var actual = dimName==='width' ? $P.outerWidth() : $P.outerHeight()
+ , tries = [{
+ pane: pane
+ , count: 1
+ , target: size
+ , actual: actual
+ , correct: (size === actual)
+ , attempt: size
+ , cssSize: newSize
+ }]
+ , lastTry = tries[0]
+ , thisTry = {}
+ , msg = 'Inaccurate size after resizing the '+ pane +'-pane.'
+ ;
+ while ( !lastTry.correct ) {
+ thisTry = { pane: pane, count: lastTry.count+1, target: size };
+
+ if (lastTry.actual > size)
+ thisTry.attempt = max(0, lastTry.attempt - (lastTry.actual - size));
+ else // lastTry.actual < size
+ thisTry.attempt = max(0, lastTry.attempt + (size - lastTry.actual));
+
+ thisTry.cssSize = cssSize(pane, thisTry.attempt);
+ $P.css( dimName, thisTry.cssSize );
+
+ thisTry.actual = dimName=='width' ? $P.outerWidth() : $P.outerHeight();
+ thisTry.correct = (size === thisTry.actual);
+
+ // log attempts and alert the user of this *non-fatal error* (if showDebugMessages)
+ if ( tries.length === 1) {
+ _log(msg, false, true);
+ _log(lastTry, false, true);
+ }
+ _log(thisTry, false, true);
+ // after 4 tries, is as close as its gonna get!
+ if (tries.length > 3) break;
+
+ tries.push( thisTry );
+ lastTry = tries[ tries.length - 1 ];
+ }
+ // END TESTING CODE
+
+ // update pane-state dimensions
+ s.size = size;
+ $.extend(s, elDims($P));
+
+ if (s.isVisible && $P.is(":visible")) {
+ // reposition the resizer-bar
+ if ($R) $R.css( side, size + sC.inset[side] );
+ // resize the content-div
+ sizeContent(pane);
+ }
+
+ if (!skipCallback && !skipResizeWhileDragging && state.initialized && s.isVisible)
+ _runCallbacks("onresize_end", pane);
+
+ // resize all the adjacent panes, and adjust their toggler buttons
+ // when skipCallback passed, it means the controlling method will handle 'other panes'
+ if (!skipCallback) {
+ // also no callback if live-resize is in progress and NOT triggerEventsDuringLiveResize
+ if (!s.isSliding) sizeMidPanes(_c[pane].dir=="horz" ? "" : "center", skipResizeWhileDragging, force);
+ sizeHandles();
+ }
+
+ // if opposite-pane was autoClosed, see if it can be autoOpened now
+ var altPane = _c.oppositeEdge[pane];
+ if (size < oldSize && state[ altPane ].noRoom) {
+ setSizeLimits( altPane );
+ makePaneFit( altPane, false, skipCallback );
+ }
+
+ // DEBUG - ALERT user/developer so they know there was a sizing problem
+ if (tries.length > 1)
+ _log(msg +'\nSee the Error Console for details.', true, true);
+ }
+ }
+
+ /**
+ * @see initPanes(), sizePane(), resizeAll(), open(), close(), hide()
+ * @param {(Array.|string)} panes The pane(s) being resized, comma-delmited string
+ * @param {boolean=} [skipCallback=false] Should the onresize callback be run?
+ * @param {boolean=} [force=false]
+ */
+, sizeMidPanes = function (panes, skipCallback, force) {
+ panes = (panes ? panes : "east,west,center").split(",");
+
+ $.each(panes, function (i, pane) {
+ if (!$Ps[pane]) return; // NO PANE - skip
+ var
+ o = options[pane]
+ , s = state[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , isCenter= (pane=="center")
+ , hasRoom = true
+ , CSS = {}
+ // if pane is not visible, show it invisibly NOW rather than for *each call* in this script
+ , visCSS = $.layout.showInvisibly($P)
+
+ , newCenter = calcNewCenterPaneDims()
+ ;
+
+ // update pane-state dimensions
+ $.extend(s, elDims($P));
+
+ if (pane === "center") {
+ if (!force && s.isVisible && newCenter.width === s.outerWidth && newCenter.height === s.outerHeight) {
+ $P.css(visCSS);
+ return true; // SKIP - pane already the correct size
+ }
+ // set state for makePaneFit() logic
+ $.extend(s, cssMinDims(pane), {
+ maxWidth: newCenter.width
+ , maxHeight: newCenter.height
+ });
+ CSS = newCenter;
+ s.newWidth = CSS.width;
+ s.newHeight = CSS.height;
+ // convert OUTER width/height to CSS width/height
+ CSS.width = cssW($P, CSS.width);
+ // NEW - allow pane to extend 'below' visible area rather than hide it
+ CSS.height = cssH($P, CSS.height);
+ hasRoom = CSS.width >= 0 && CSS.height >= 0; // height >= 0 = ALWAYS TRUE NOW
+
+ // during layout init, try to shrink east/west panes to make room for center
+ if (!state.initialized && o.minWidth > newCenter.width) {
+ var
+ reqPx = o.minWidth - s.outerWidth
+ , minE = options.east.minSize || 0
+ , minW = options.west.minSize || 0
+ , sizeE = state.east.size
+ , sizeW = state.west.size
+ , newE = sizeE
+ , newW = sizeW
+ ;
+ if (reqPx > 0 && state.east.isVisible && sizeE > minE) {
+ newE = max( sizeE-minE, sizeE-reqPx );
+ reqPx -= sizeE-newE;
+ }
+ if (reqPx > 0 && state.west.isVisible && sizeW > minW) {
+ newW = max( sizeW-minW, sizeW-reqPx );
+ reqPx -= sizeW-newW;
+ }
+ // IF we found enough extra space, then resize the border panes as calculated
+ if (reqPx === 0) {
+ if (sizeE && sizeE != minE)
+ sizePane('east', newE, true, true, force); // true = skipCallback/noAnimation - initPanes will handle when done
+ if (sizeW && sizeW != minW)
+ sizePane('west', newW, true, true, force); // true = skipCallback/noAnimation
+ // now start over!
+ sizeMidPanes('center', skipCallback, force);
+ $P.css(visCSS);
+ return; // abort this loop
+ }
+ }
+ }
+ else { // for east and west, set only the height, which is same as center height
+ // set state.min/maxWidth/Height for makePaneFit() logic
+ if (s.isVisible && !s.noVerticalRoom)
+ $.extend(s, elDims($P), cssMinDims(pane))
+ if (!force && !s.noVerticalRoom && newCenter.height === s.outerHeight) {
+ $P.css(visCSS);
+ return true; // SKIP - pane already the correct size
+ }
+ // east/west have same top, bottom & height as center
+ CSS.top = newCenter.top;
+ CSS.bottom = newCenter.bottom;
+ s.newSize = newCenter.height
+ // NEW - allow pane to extend 'below' visible area rather than hide it
+ CSS.height = cssH($P, newCenter.height);
+ s.maxHeight = CSS.height;
+ hasRoom = (s.maxHeight >= 0); // ALWAYS TRUE NOW
+ if (!hasRoom) s.noVerticalRoom = true; // makePaneFit() logic
+ }
+
+ if (hasRoom) {
+ // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized
+ if (!skipCallback && state.initialized)
+ _runCallbacks("onresize_start", pane);
+
+ $P.css(CSS); // apply the CSS to pane
+ if (pane !== "center")
+ sizeHandles(pane); // also update resizer length
+ if (s.noRoom && !s.isClosed && !s.isHidden)
+ makePaneFit(pane); // will re-open/show auto-closed/hidden pane
+ if (s.isVisible) {
+ $.extend(s, elDims($P)); // update pane dimensions
+ if (state.initialized) sizeContent(pane); // also resize the contents, if exists
+ }
+ }
+ else if (!s.noRoom && s.isVisible) // no room for pane
+ makePaneFit(pane); // will hide or close pane
+
+ // reset visibility, if necessary
+ $P.css(visCSS);
+
+ delete s.newSize;
+ delete s.newWidth;
+ delete s.newHeight;
+
+ if (!s.isVisible)
+ return true; // DONE - next pane
+
+ /*
+ * Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes
+ * Normally these panes have only 'left' & 'right' positions so pane auto-sizes
+ * ALSO required when pane is an IFRAME because will NOT default to 'full width'
+ * TODO: Can I use width:100% for a north/south iframe?
+ * TODO: Sounds like a job for $P.outerWidth( sC.innerWidth ) SETTER METHOD
+ */
+ if (pane === "center") { // finished processing midPanes
+ var fix = browser.isIE6 || !browser.boxModel;
+ if ($Ps.north && (fix || state.north.tagName=="IFRAME"))
+ $Ps.north.css("width", cssW($Ps.north, sC.innerWidth));
+ if ($Ps.south && (fix || state.south.tagName=="IFRAME"))
+ $Ps.south.css("width", cssW($Ps.south, sC.innerWidth));
+ }
+
+ // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized
+ if (!skipCallback && state.initialized)
+ _runCallbacks("onresize_end", pane);
+ });
+ }
+
+
+ /**
+ * @see window.onresize(), callbacks or custom code
+ * @param {(Object|boolean)=} evt_or_refresh If 'true', then also reset pane-positioning
+ */
+, resizeAll = function (evt_or_refresh) {
+ var oldW = sC.innerWidth
+ , oldH = sC.innerHeight
+ ;
+ // stopPropagation if called by trigger("layoutdestroy") - use evtPane utility
+ evtPane(evt_or_refresh);
+
+ // cannot size layout when 'container' is hidden or collapsed
+ if (!$N.is(":visible")) return;
+
+ if (!state.initialized) {
+ _initLayoutElements();
+ return; // no need to resize since we just initialized!
+ }
+
+ if (evt_or_refresh === true && $.isPlainObject(options.outset)) {
+ // update container CSS in case outset option has changed
+ $N.css( options.outset );
+ }
+ // UPDATE container dimensions
+ $.extend(sC, elDims( $N, options.inset ));
+ if (!sC.outerHeight) return;
+
+ // if 'true' passed, refresh pane & handle positioning too
+ if (evt_or_refresh === true) {
+ setPanePosition();
+ }
+
+ // onresizeall_start will CANCEL resizing if returns false
+ // state.container has already been set, so user can access this info for calcuations
+ if (false === _runCallbacks("onresizeall_start")) return false;
+
+ var // see if container is now 'smaller' than before
+ shrunkH = (sC.innerHeight < oldH)
+ , shrunkW = (sC.innerWidth < oldW)
+ , $P, o, s
+ ;
+ // NOTE special order for sizing: S-N-E-W
+ $.each(["south","north","east","west"], function (i, pane) {
+ if (!$Ps[pane]) return; // no pane - SKIP
+ o = options[pane];
+ s = state[pane];
+ if (s.autoResize && s.size != o.size) // resize pane to original size set in options
+ sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize
+ else {
+ setSizeLimits(pane);
+ makePaneFit(pane, false, true, true); // true=skipCallback/forceResize
+ }
+ });
+
+ sizeMidPanes("", true, true); // true=skipCallback/forceResize
+ sizeHandles(); // reposition the toggler elements
+
+ // trigger all individual pane callbacks AFTER layout has finished resizing
+ $.each(_c.allPanes, function (i, pane) {
+ $P = $Ps[pane];
+ if (!$P) return; // SKIP
+ if (state[pane].isVisible) // undefined for non-existent panes
+ _runCallbacks("onresize_end", pane); // callback - if exists
+ });
+
+ _runCallbacks("onresizeall_end");
+ //_triggerLayoutEvent(pane, 'resizeall');
+ }
+
+ /**
+ * Whenever a pane resizes or opens that has a nested layout, trigger resizeAll
+ *
+ * @param {(string|Object)} evt_or_pane The pane just resized or opened
+ */
+, resizeChildren = function (evt_or_pane, skipRefresh) {
+ var pane = evtPane.call(this, evt_or_pane);
+
+ if (!options[pane].resizeChildren) return;
+
+ // ensure the pane-children are up-to-date
+ if (!skipRefresh) refreshChildren( pane );
+ var pC = children[pane];
+ if ($.isPlainObject( pC )) {
+ // resize one or more children
+ $.each( pC, function (key, child) {
+ if (!child.destroyed) child.resizeAll();
+ });
+ }
+ }
+
+ /**
+ * IF pane has a content-div, then resize all elements inside pane to fit pane-height
+ *
+ * @param {(string|Object)} evt_or_panes The pane(s) being resized
+ * @param {boolean=} [remeasure=false] Should the content (header/footer) be remeasured?
+ */
+, sizeContent = function (evt_or_panes, remeasure) {
+ if (!isInitialized()) return;
+
+ var panes = evtPane.call(this, evt_or_panes);
+ panes = panes ? panes.split(",") : _c.allPanes;
+
+ $.each(panes, function (idx, pane) {
+ var
+ $P = $Ps[pane]
+ , $C = $Cs[pane]
+ , o = options[pane]
+ , s = state[pane]
+ , m = s.content // m = measurements
+ ;
+ if (!$P || !$C || !$P.is(":visible")) return true; // NOT VISIBLE - skip
+
+ // if content-element was REMOVED, update OR remove the pointer
+ if (!$C.length) {
+ initContent(pane, false); // false = do NOT sizeContent() - already there!
+ if (!$C) return; // no replacement element found - pointer have been removed
+ }
+
+ // onsizecontent_start will CANCEL resizing if returns false
+ if (false === _runCallbacks("onsizecontent_start", pane)) return;
+
+ // skip re-measuring offsets if live-resizing
+ if ((!s.isMoving && !s.isResizing) || o.liveContentResizing || remeasure || m.top == undefined) {
+ _measure();
+ // if any footers are below pane-bottom, they may not measure correctly,
+ // so allow pane overflow and re-measure
+ if (m.hiddenFooters > 0 && $P.css("overflow") === "hidden") {
+ $P.css("overflow", "visible");
+ _measure(); // remeasure while overflowing
+ $P.css("overflow", "hidden");
+ }
+ }
+ // NOTE: spaceAbove/Below *includes* the pane paddingTop/Bottom, but not pane.borders
+ var newH = s.innerHeight - (m.spaceAbove - s.css.paddingTop) - (m.spaceBelow - s.css.paddingBottom);
+
+ if (!$C.is(":visible") || m.height != newH) {
+ // size the Content element to fit new pane-size - will autoHide if not enough room
+ setOuterHeight($C, newH, true); // true=autoHide
+ m.height = newH; // save new height
+ };
+
+ if (state.initialized)
+ _runCallbacks("onsizecontent_end", pane);
+
+ function _below ($E) {
+ return max(s.css.paddingBottom, (parseInt($E.css("marginBottom"), 10) || 0));
+ };
+
+ function _measure () {
+ var
+ ignore = options[pane].contentIgnoreSelector
+ , $Fs = $C.nextAll().not(".ui-layout-mask").not(ignore || ":lt(0)") // not :lt(0) = ALL
+ , $Fs_vis = $Fs.filter(':visible')
+ , $F = $Fs_vis.filter(':last')
+ ;
+ m = {
+ top: $C[0].offsetTop
+ , height: $C.outerHeight()
+ , numFooters: $Fs.length
+ , hiddenFooters: $Fs.length - $Fs_vis.length
+ , spaceBelow: 0 // correct if no content footer ($E)
+ }
+ m.spaceAbove = m.top; // just for state - not used in calc
+ m.bottom = m.top + m.height;
+ if ($F.length)
+ //spaceBelow = (LastFooter.top + LastFooter.height) [footerBottom] - Content.bottom + max(LastFooter.marginBottom, pane.paddingBotom)
+ m.spaceBelow = ($F[0].offsetTop + $F.outerHeight()) - m.bottom + _below($F);
+ else // no footer - check marginBottom on Content element itself
+ m.spaceBelow = _below($C);
+ };
+ });
+ }
+
+
+ /**
+ * Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary
+ *
+ * @see initHandles(), open(), close(), resizeAll()
+ * @param {(string|Object)=} evt_or_panes The pane(s) being resized
+ */
+, sizeHandles = function (evt_or_panes) {
+ var panes = evtPane.call(this, evt_or_panes)
+ panes = panes ? panes.split(",") : _c.borderPanes;
+
+ $.each(panes, function (i, pane) {
+ var
+ o = options[pane]
+ , s = state[pane]
+ , $P = $Ps[pane]
+ , $R = $Rs[pane]
+ , $T = $Ts[pane]
+ , $TC
+ ;
+ if (!$P || !$R) return;
+
+ var
+ dir = _c[pane].dir
+ , _state = (s.isClosed ? "_closed" : "_open")
+ , spacing = o["spacing"+ _state]
+ , togAlign = o["togglerAlign"+ _state]
+ , togLen = o["togglerLength"+ _state]
+ , paneLen
+ , left
+ , offset
+ , CSS = {}
+ ;
+
+ if (spacing === 0) {
+ $R.hide();
+ return;
+ }
+ else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason
+ $R.show(); // in case was previously hidden
+
+ // Resizer Bar is ALWAYS same width/height of pane it is attached to
+ if (dir === "horz") { // north/south
+ //paneLen = $P.outerWidth(); // s.outerWidth ||
+ paneLen = sC.innerWidth; // handle offscreen-panes
+ s.resizerLength = paneLen;
+ left = $.layout.cssNum($P, "left")
+ $R.css({
+ width: cssW($R, paneLen) // account for borders & padding
+ , height: cssH($R, spacing) // ditto
+ , left: left > -9999 ? left : sC.inset.left // handle offscreen-panes
+ });
+ }
+ else { // east/west
+ paneLen = $P.outerHeight(); // s.outerHeight ||
+ s.resizerLength = paneLen;
+ $R.css({
+ height: cssH($R, paneLen) // account for borders & padding
+ , width: cssW($R, spacing) // ditto
+ , top: sC.inset.top + getPaneSize("north", true) // TODO: what if no North pane?
+ //, top: $.layout.cssNum($Ps["center"], "top")
+ });
+ }
+
+ // remove hover classes
+ removeHover( o, $R );
+
+ if ($T) {
+ if (togLen === 0 || (s.isSliding && o.hideTogglerOnSlide)) {
+ $T.hide(); // always HIDE the toggler when 'sliding'
+ return;
+ }
+ else
+ $T.show(); // in case was previously hidden
+
+ if (!(togLen > 0) || togLen === "100%" || togLen > paneLen) {
+ togLen = paneLen;
+ offset = 0;
+ }
+ else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed
+ if (isStr(togAlign)) {
+ switch (togAlign) {
+ case "top":
+ case "left": offset = 0;
+ break;
+ case "bottom":
+ case "right": offset = paneLen - togLen;
+ break;
+ case "middle":
+ case "center":
+ default: offset = round((paneLen - togLen) / 2); // 'default' catches typos
+ }
+ }
+ else { // togAlign = number
+ var x = parseInt(togAlign, 10); //
+ if (togAlign >= 0) offset = x;
+ else offset = paneLen - togLen + x; // NOTE: x is negative!
+ }
+ }
+
+ if (dir === "horz") { // north/south
+ var width = cssW($T, togLen);
+ $T.css({
+ width: width // account for borders & padding
+ , height: cssH($T, spacing) // ditto
+ , left: offset // TODO: VERIFY that toggler positions correctly for ALL values
+ , top: 0
+ });
+ // CENTER the toggler content SPAN
+ $T.children(".content").each(function(){
+ $TC = $(this);
+ $TC.css("marginLeft", round((width-$TC.outerWidth())/2)); // could be negative
+ });
+ }
+ else { // east/west
+ var height = cssH($T, togLen);
+ $T.css({
+ height: height // account for borders & padding
+ , width: cssW($T, spacing) // ditto
+ , top: offset // POSITION the toggler
+ , left: 0
+ });
+ // CENTER the toggler content SPAN
+ $T.children(".content").each(function(){
+ $TC = $(this);
+ $TC.css("marginTop", round((height-$TC.outerHeight())/2)); // could be negative
+ });
+ }
+
+ // remove ALL hover classes
+ removeHover( 0, $T );
+ }
+
+ // DONE measuring and sizing this resizer/toggler, so can be 'hidden' now
+ if (!state.initialized && (o.initHidden || s.isHidden)) {
+ $R.hide();
+ if ($T) $T.hide();
+ }
+ });
+ }
+
+
+ /**
+ * @param {(string|Object)} evt_or_pane
+ */
+, enableClosable = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $T = $Ts[pane]
+ , o = options[pane]
+ ;
+ if (!$T) return;
+ o.closable = true;
+ $T .bind("click."+ sID, function(evt){ evt.stopPropagation(); toggle(pane); })
+ .css("visibility", "visible")
+ .css("cursor", "pointer")
+ .attr("title", state[pane].isClosed ? o.tips.Open : o.tips.Close) // may be blank
+ .show();
+ }
+ /**
+ * @param {(string|Object)} evt_or_pane
+ * @param {boolean=} [hide=false]
+ */
+, disableClosable = function (evt_or_pane, hide) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $T = $Ts[pane]
+ ;
+ if (!$T) return;
+ options[pane].closable = false;
+ // is closable is disable, then pane MUST be open!
+ if (state[pane].isClosed) open(pane, false, true);
+ $T .unbind("."+ sID)
+ .css("visibility", hide ? "hidden" : "visible") // instead of hide(), which creates logic issues
+ .css("cursor", "default")
+ .attr("title", "");
+ }
+
+
+ /**
+ * @param {(string|Object)} evt_or_pane
+ */
+, enableSlidable = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $R = $Rs[pane]
+ ;
+ if (!$R || !$R.data('draggable')) return;
+ options[pane].slidable = true;
+ if (state[pane].isClosed)
+ bindStartSlidingEvents(pane, true);
+ }
+ /**
+ * @param {(string|Object)} evt_or_pane
+ */
+, disableSlidable = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $R = $Rs[pane]
+ ;
+ if (!$R) return;
+ options[pane].slidable = false;
+ if (state[pane].isSliding)
+ close(pane, false, true);
+ else {
+ bindStartSlidingEvents(pane, false);
+ $R .css("cursor", "default")
+ .attr("title", "");
+ removeHover(null, $R[0]); // in case currently hovered
+ }
+ }
+
+
+ /**
+ * @param {(string|Object)} evt_or_pane
+ */
+, enableResizable = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $R = $Rs[pane]
+ , o = options[pane]
+ ;
+ if (!$R || !$R.data('draggable')) return;
+ o.resizable = true;
+ $R.draggable("enable");
+ if (!state[pane].isClosed)
+ $R .css("cursor", o.resizerCursor)
+ .attr("title", o.tips.Resize);
+ }
+ /**
+ * @param {(string|Object)} evt_or_pane
+ */
+, disableResizable = function (evt_or_pane) {
+ if (!isInitialized()) return;
+ var pane = evtPane.call(this, evt_or_pane)
+ , $R = $Rs[pane]
+ ;
+ if (!$R || !$R.data('draggable')) return;
+ options[pane].resizable = false;
+ $R .draggable("disable")
+ .css("cursor", "default")
+ .attr("title", "");
+ removeHover(null, $R[0]); // in case currently hovered
+ }
+
+
+ /**
+ * Move a pane from source-side (eg, west) to target-side (eg, east)
+ * If pane exists on target-side, move that to source-side, ie, 'swap' the panes
+ *
+ * @param {(string|Object)} evt_or_pane1 The pane/edge being swapped
+ * @param {string} pane2 ditto
+ */
+, swapPanes = function (evt_or_pane1, pane2) {
+ if (!isInitialized()) return;
+ var pane1 = evtPane.call(this, evt_or_pane1);
+ // change state.edge NOW so callbacks can know where pane is headed...
+ state[pane1].edge = pane2;
+ state[pane2].edge = pane1;
+ // run these even if NOT state.initialized
+ if (false === _runCallbacks("onswap_start", pane1)
+ || false === _runCallbacks("onswap_start", pane2)
+ ) {
+ state[pane1].edge = pane1; // reset
+ state[pane2].edge = pane2;
+ return;
+ }
+
+ var
+ oPane1 = copy( pane1 )
+ , oPane2 = copy( pane2 )
+ , sizes = {}
+ ;
+ sizes[pane1] = oPane1 ? oPane1.state.size : 0;
+ sizes[pane2] = oPane2 ? oPane2.state.size : 0;
+
+ // clear pointers & state
+ $Ps[pane1] = false;
+ $Ps[pane2] = false;
+ state[pane1] = {};
+ state[pane2] = {};
+
+ // ALWAYS remove the resizer & toggler elements
+ if ($Ts[pane1]) $Ts[pane1].remove();
+ if ($Ts[pane2]) $Ts[pane2].remove();
+ if ($Rs[pane1]) $Rs[pane1].remove();
+ if ($Rs[pane2]) $Rs[pane2].remove();
+ $Rs[pane1] = $Rs[pane2] = $Ts[pane1] = $Ts[pane2] = false;
+
+ // transfer element pointers and data to NEW Layout keys
+ move( oPane1, pane2 );
+ move( oPane2, pane1 );
+
+ // cleanup objects
+ oPane1 = oPane2 = sizes = null;
+
+ // make panes 'visible' again
+ if ($Ps[pane1]) $Ps[pane1].css(_c.visible);
+ if ($Ps[pane2]) $Ps[pane2].css(_c.visible);
+
+ // fix any size discrepancies caused by swap
+ resizeAll();
+
+ // run these even if NOT state.initialized
+ _runCallbacks("onswap_end", pane1);
+ _runCallbacks("onswap_end", pane2);
+
+ return;
+
+ function copy (n) { // n = pane
+ var
+ $P = $Ps[n]
+ , $C = $Cs[n]
+ ;
+ return !$P ? false : {
+ pane: n
+ , P: $P ? $P[0] : false
+ , C: $C ? $C[0] : false
+ , state: $.extend(true, {}, state[n])
+ , options: $.extend(true, {}, options[n])
+ }
+ };
+
+ function move (oPane, pane) {
+ if (!oPane) return;
+ var
+ P = oPane.P
+ , C = oPane.C
+ , oldPane = oPane.pane
+ , c = _c[pane]
+ // save pane-options that should be retained
+ , s = $.extend(true, {}, state[pane])
+ , o = options[pane]
+ // RETAIN side-specific FX Settings - more below
+ , fx = { resizerCursor: o.resizerCursor }
+ , re, size, pos
+ ;
+ $.each("fxName,fxSpeed,fxSettings".split(","), function (i, k) {
+ fx[k +"_open"] = o[k +"_open"];
+ fx[k +"_close"] = o[k +"_close"];
+ fx[k +"_size"] = o[k +"_size"];
+ });
+
+ // update object pointers and attributes
+ $Ps[pane] = $(P)
+ .data({
+ layoutPane: Instance[pane] // NEW pointer to pane-alias-object
+ , layoutEdge: pane
+ })
+ .css(_c.hidden)
+ .css(c.cssReq)
+ ;
+ $Cs[pane] = C ? $(C) : false;
+
+ // set options and state
+ options[pane] = $.extend(true, {}, oPane.options, fx);
+ state[pane] = $.extend(true, {}, oPane.state);
+
+ // change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west
+ re = new RegExp(o.paneClass +"-"+ oldPane, "g");
+ P.className = P.className.replace(re, o.paneClass +"-"+ pane);
+
+ // ALWAYS regenerate the resizer & toggler elements
+ initHandles(pane); // create the required resizer & toggler
+
+ // if moving to different orientation, then keep 'target' pane size
+ if (c.dir != _c[oldPane].dir) {
+ size = sizes[pane] || 0;
+ setSizeLimits(pane); // update pane-state
+ size = max(size, state[pane].minSize);
+ // use manualSizePane to disable autoResize - not useful after panes are swapped
+ manualSizePane(pane, size, true, true); // true/true = skipCallback/noAnimation
+ }
+ else // move the resizer here
+ $Rs[pane].css(c.side, sC.inset[c.side] + (state[pane].isVisible ? getPaneSize(pane) : 0));
+
+
+ // ADD CLASSNAMES & SLIDE-BINDINGS
+ if (oPane.state.isVisible && !s.isVisible)
+ setAsOpen(pane, true); // true = skipCallback
+ else {
+ setAsClosed(pane);
+ bindStartSlidingEvents(pane, true); // will enable events IF option is set
+ }
+
+ // DESTROY the object
+ oPane = null;
+ };
+ }
+
+
+ /**
+ * INTERNAL method to sync pin-buttons when pane is opened or closed
+ * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes
+ *
+ * @see open(), setAsOpen(), setAsClosed()
+ * @param {string} pane These are the params returned to callbacks by layout()
+ * @param {boolean} doPin True means set the pin 'down', False means 'up'
+ */
+, syncPinBtns = function (pane, doPin) {
+ if ($.layout.plugins.buttons)
+ $.each(state[pane].pins, function (i, selector) {
+ $.layout.buttons.setPinState(Instance, $(selector), pane, doPin);
+ });
+ }
+
+; // END var DECLARATIONS
+
+ /**
+ * Capture keys when enableCursorHotkey - toggle pane if hotkey pressed
+ *
+ * @see document.keydown()
+ */
+ function keyDown (evt) {
+ if (!evt) return true;
+ var code = evt.keyCode;
+ if (code < 33) return true; // ignore special keys: ENTER, TAB, etc
+
+ var
+ PANE = {
+ 38: "north" // Up Cursor - $.ui.keyCode.UP
+ , 40: "south" // Down Cursor - $.ui.keyCode.DOWN
+ , 37: "west" // Left Cursor - $.ui.keyCode.LEFT
+ , 39: "east" // Right Cursor - $.ui.keyCode.RIGHT
+ }
+ , ALT = evt.altKey // no worky!
+ , SHIFT = evt.shiftKey
+ , CTRL = evt.ctrlKey
+ , CURSOR = (CTRL && code >= 37 && code <= 40)
+ , o, k, m, pane
+ ;
+
+ if (CURSOR && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey
+ pane = PANE[code];
+ else if (CTRL || SHIFT) // check to see if this matches a custom-hotkey
+ $.each(_c.borderPanes, function (i, p) { // loop each pane to check its hotkey
+ o = options[p];
+ k = o.customHotkey;
+ m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT"
+ if ((SHIFT && m=="SHIFT") || (CTRL && m=="CTRL") || (CTRL && SHIFT)) { // Modifier matches
+ if (k && code === (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches
+ pane = p;
+ return false; // BREAK
+ }
+ }
+ });
+
+ // validate pane
+ if (!pane || !$Ps[pane] || !options[pane].closable || state[pane].isHidden)
+ return true;
+
+ toggle(pane);
+
+ evt.stopPropagation();
+ evt.returnValue = false; // CANCEL key
+ return false;
+ };
+
+
+/*
+ * ######################################
+ * UTILITY METHODS
+ * called externally or by initButtons
+ * ######################################
+ */
+
+ /**
+ * Change/reset a pane overflow setting & zIndex to allow popups/drop-downs to work
+ *
+ * @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event
+ */
+ function allowOverflow (el) {
+ if (!isInitialized()) return;
+ if (this && this.tagName) el = this; // BOUND to element
+ var $P;
+ if (isStr(el))
+ $P = $Ps[el];
+ else if ($(el).data("layoutRole"))
+ $P = $(el);
+ else
+ $(el).parents().each(function(){
+ if ($(this).data("layoutRole")) {
+ $P = $(this);
+ return false; // BREAK
+ }
+ });
+ if (!$P || !$P.length) return; // INVALID
+
+ var
+ pane = $P.data("layoutEdge")
+ , s = state[pane]
+ ;
+
+ // if pane is already raised, then reset it before doing it again!
+ // this would happen if allowOverflow is attached to BOTH the pane and an element
+ if (s.cssSaved)
+ resetOverflow(pane); // reset previous CSS before continuing
+
+ // if pane is raised by sliding or resizing, or its closed, then abort
+ if (s.isSliding || s.isResizing || s.isClosed) {
+ s.cssSaved = false;
+ return;
+ }
+
+ var
+ newCSS = { zIndex: (options.zIndexes.resizer_normal + 1) }
+ , curCSS = {}
+ , of = $P.css("overflow")
+ , ofX = $P.css("overflowX")
+ , ofY = $P.css("overflowY")
+ ;
+ // determine which, if any, overflow settings need to be changed
+ if (of != "visible") {
+ curCSS.overflow = of;
+ newCSS.overflow = "visible";
+ }
+ if (ofX && !ofX.match(/(visible|auto)/)) {
+ curCSS.overflowX = ofX;
+ newCSS.overflowX = "visible";
+ }
+ if (ofY && !ofY.match(/(visible|auto)/)) {
+ curCSS.overflowY = ofX;
+ newCSS.overflowY = "visible";
+ }
+
+ // save the current overflow settings - even if blank!
+ s.cssSaved = curCSS;
+
+ // apply new CSS to raise zIndex and, if necessary, make overflow 'visible'
+ $P.css( newCSS );
+
+ // make sure the zIndex of all other panes is normal
+ $.each(_c.allPanes, function(i, p) {
+ if (p != pane) resetOverflow(p);
+ });
+
+ };
+ /**
+ * @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event
+ */
+ function resetOverflow (el) {
+ if (!isInitialized()) return;
+ if (this && this.tagName) el = this; // BOUND to element
+ var $P;
+ if (isStr(el))
+ $P = $Ps[el];
+ else if ($(el).data("layoutRole"))
+ $P = $(el);
+ else
+ $(el).parents().each(function(){
+ if ($(this).data("layoutRole")) {
+ $P = $(this);
+ return false; // BREAK
+ }
+ });
+ if (!$P || !$P.length) return; // INVALID
+
+ var
+ pane = $P.data("layoutEdge")
+ , s = state[pane]
+ , CSS = s.cssSaved || {}
+ ;
+ // reset the zIndex
+ if (!s.isSliding && !s.isResizing)
+ $P.css("zIndex", options.zIndexes.pane_normal);
+
+ // reset Overflow - if necessary
+ $P.css( CSS );
+
+ // clear var
+ s.cssSaved = false;
+ };
+
+/*
+ * #####################
+ * CREATE/RETURN LAYOUT
+ * #####################
+ */
+ try {
+
+ // validate that container exists
+ var $N = $(this).eq(0); // FIRST matching Container element
+ if (!$N.length) {
+ return _log( options.errors.containerMissing );
+ };
+
+ // Users retrieve Instance of a layout with: $N.layout() OR $N.data("layout")
+ // return the Instance-pointer if layout has already been initialized
+ if ($N.data("layoutContainer") && $N.data("layout"))
+ return $N.data("layout"); // cached pointer
+ } catch(e){
+ console.log("eeeee",e)
+ }
+
+ // init global vars
+ var
+ $Ps = {} // Panes x5 - set in initPanes()
+ , $Cs = {} // Content x5 - set in initPanes()
+ , $Rs = {} // Resizers x4 - set in initHandles()
+ , $Ts = {} // Togglers x4 - set in initHandles()
+ , $Ms = $([]) // Masks - up to 2 masks per pane (IFRAME + DIV)
+ // aliases for code brevity
+ , sC = state.container // alias for easy access to 'container dimensions'
+ , sID = state.id // alias for unique layout ID/namespace - eg: "layout435"
+ ;
+
+ // create Instance object to expose data & option Properties, and primary action Methods
+ var Instance = {
+ // layout data
+ options: options // property - options hash
+ , state: state // property - dimensions hash
+ // object pointers
+ , container: $N // property - object pointers for layout container
+ , panes: $Ps // property - object pointers for ALL Panes: panes.north, panes.center
+ , contents: $Cs // property - object pointers for ALL Content: contents.north, contents.center
+ , resizers: $Rs // property - object pointers for ALL Resizers, eg: resizers.north
+ , togglers: $Ts // property - object pointers for ALL Togglers, eg: togglers.north
+ // border-pane open/close
+ , hide: hide // method - ditto
+ , show: show // method - ditto
+ , toggle: toggle // method - pass a 'pane' ("north", "west", etc)
+ , open: open // method - ditto
+ , close: close // method - ditto
+ , slideOpen: slideOpen // method - ditto
+ , slideClose: slideClose // method - ditto
+ , slideToggle: slideToggle // method - ditto
+ // pane actions
+ , setSizeLimits: setSizeLimits // method - pass a 'pane' - update state min/max data
+ , _sizePane: sizePane // method -intended for user by plugins only!
+ , sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto'
+ , sizeContent: sizeContent // method - pass a 'pane'
+ , swapPanes: swapPanes // method - pass TWO 'panes' - will swap them
+ , showMasks: showMasks // method - pass a 'pane' OR list of panes - default = all panes with mask option set
+ , hideMasks: hideMasks // method - ditto'
+ // pane element methods
+ , initContent: initContent // method - ditto
+ , addPane: addPane // method - pass a 'pane'
+ , removePane: removePane // method - pass a 'pane' to remove from layout, add 'true' to delete the pane-elem
+ , createChildren: createChildren // method - pass a 'pane' and (optional) layout-options (OVERRIDES options[pane].children
+ , refreshChildren: refreshChildren // method - pass a 'pane' and a layout-instance
+ // special pane option setting
+ , enableClosable: enableClosable // method - pass a 'pane'
+ , disableClosable: disableClosable // method - ditto
+ , enableSlidable: enableSlidable // method - ditto
+ , disableSlidable: disableSlidable // method - ditto
+ , enableResizable: enableResizable // method - ditto
+ , disableResizable: disableResizable// method - ditto
+ // utility methods for panes
+ , allowOverflow: allowOverflow // utility - pass calling element (this)
+ , resetOverflow: resetOverflow // utility - ditto
+ // layout control
+ , destroy: destroy // method - no parameters
+ , initPanes: isInitialized // method - no parameters
+ , resizeAll: resizeAll // method - no parameters
+ // callback triggering
+ , runCallbacks: _runCallbacks // method - pass evtName & pane (if a pane-event), eg: trigger("onopen", "west")
+ // alias collections of options, state and children - created in addPane and extended elsewhere
+ , hasParentLayout: false // set by initContainer()
+ , children: children // pointers to child-layouts, eg: Instance.children.west.layoutName
+ , north: false // alias group: { name: pane, pane: $Ps[pane], options: options[pane], state: state[pane], children: children[pane] }
+ , south: false // ditto
+ , west: false // ditto
+ , east: false // ditto
+ , center: false // ditto
+ };
+
+ // create the border layout NOW
+ if (_create() === 'cancel') // onload_start callback returned false to CANCEL layout creation
+ return null;
+ else // true OR false -- if layout-elements did NOT init (hidden or do not exist), can auto-init later
+ return Instance; // return the Instance object
+
+}
+
+
+})( jQuery );
+// END Layout - keep internal vars internal!
+
+
+
+// START Plugins - shared wrapper, no global vars
+(function ($) {
+
+
+/**
+ * jquery.layout.state 1.0
+ * $Date: 2011-07-16 08:00:00 (Sat, 16 July 2011) $
+ *
+ * Copyright (c) 2012
+ * Kevin Dalman (http://allpro.net)
+ *
+ * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
+ * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
+ *
+ * @requires: UI Layout 1.3.0.rc30.1 or higher
+ * @requires: $.ui.cookie (above)
+ *
+ * @see: http://groups.google.com/group/jquery-ui-layout
+ */
+/*
+ * State-management options stored in options.stateManagement, which includes a .cookie hash
+ * Default options saves ALL KEYS for ALL PANES, ie: pane.size, pane.isClosed, pane.isHidden
+ *
+ * // STATE/COOKIE OPTIONS
+ * @example $(el).layout({
+ stateManagement: {
+ enabled: true
+ , stateKeys: "east.size,west.size,east.isClosed,west.isClosed"
+ , cookie: { name: "appLayout", path: "/" }
+ }
+ })
+ * @example $(el).layout({ stateManagement__enabled: true }) // enable auto-state-management using cookies
+ * @example $(el).layout({ stateManagement__cookie: { name: "appLayout", path: "/" } })
+ * @example $(el).layout({ stateManagement__cookie__name: "appLayout", stateManagement__cookie__path: "/" })
+ *
+ * // STATE/COOKIE METHODS
+ * @example myLayout.saveCookie( "west.isClosed,north.size,south.isHidden", {expires: 7} );
+ * @example myLayout.loadCookie();
+ * @example myLayout.deleteCookie();
+ * @example var JSON = myLayout.readState(); // CURRENT Layout State
+ * @example var JSON = myLayout.readCookie(); // SAVED Layout State (from cookie)
+ * @example var JSON = myLayout.state.stateData; // LAST LOADED Layout State (cookie saved in layout.state hash)
+ *
+ * CUSTOM STATE-MANAGEMENT (eg, saved in a database)
+ * @example var JSON = myLayout.readState( "west.isClosed,north.size,south.isHidden" );
+ * @example myLayout.loadState( JSON );
+ */
+
+/**
+ * UI COOKIE UTILITY
+ *
+ * A $.cookie OR $.ui.cookie namespace *should be standard*, but until then...
+ * This creates $.ui.cookie so Layout does not need the cookie.jquery.js plugin
+ * NOTE: This utility is REQUIRED by the layout.state plugin
+ *
+ * Cookie methods in Layout are created as part of State Management
+ */
+if (!$.ui) $.ui = {};
+$.ui.cookie = {
+
+ // cookieEnabled is not in DOM specs, but DOES works in all browsers,including IE6
+ acceptsCookies: !!navigator.cookieEnabled
+
+, read: function (name) {
+ var c = document.cookie
+ , cs = c ? c.split(';') : []
+ , pair // loop var
+ ;
+ for (var i=0, n=cs.length; i < n; i++) {
+ pair = $.trim(cs[i]).split('='); // name=value pair
+ if (pair[0] == name) // found the layout cookie
+ return decodeURIComponent(pair[1]);
+ }
+ return null;
+ }
+
+, write: function (name, val, cookieOpts) {
+ var params = ""
+ , date = ""
+ , clear = false
+ , o = cookieOpts || {}
+ , x = o.expires || null
+ , t = $.type(x)
+ ;
+ if (t === "date")
+ date = x;
+ else if (t === "string" && x > 0) {
+ x = parseInt(x,10);
+ t = "number";
+ }
+ if (t === "number") {
+ date = new Date();
+ if (x > 0)
+ date.setDate(date.getDate() + x);
+ else {
+ date.setFullYear(1970);
+ clear = true;
+ }
+ }
+ if (date) params += ";expires="+ date.toUTCString();
+ if (o.path) params += ";path="+ o.path;
+ if (o.domain) params += ";domain="+ o.domain;
+ if (o.secure) params += ";secure";
+ document.cookie = name +"="+ (clear ? "" : encodeURIComponent( val )) + params; // write or clear cookie
+ }
+
+, clear: function (name) {
+ $.ui.cookie.write(name, "", {expires: -1});
+ }
+
+};
+// if cookie.jquery.js is not loaded, create an alias to replicate it
+// this may be useful to other plugins or code dependent on that plugin
+if (!$.cookie) $.cookie = function (k, v, o) {
+ var C = $.ui.cookie;
+ if (v === null)
+ C.clear(k);
+ else if (v === undefined)
+ return C.read(k);
+ else
+ C.write(k, v, o);
+};
+
+
+// tell Layout that the state plugin is available
+$.layout.plugins.stateManagement = true;
+
+// Add State-Management options to layout.defaults
+$.layout.config.optionRootKeys.push("stateManagement");
+$.layout.defaults.stateManagement = {
+ enabled: false // true = enable state-management, even if not using cookies
+, autoSave: true // Save a state-cookie when page exits?
+, autoLoad: true // Load the state-cookie when Layout inits?
+, animateLoad: true // animate panes when loading state into an active layout
+, includeChildren: true // recurse into child layouts to include their state as well
+ // List state-data to save - must be pane-specific
+, stateKeys: "north.size,south.size,east.size,west.size,"+
+ "north.isClosed,south.isClosed,east.isClosed,west.isClosed,"+
+ "north.isHidden,south.isHidden,east.isHidden,west.isHidden"
+, cookie: {
+ name: "" // If not specified, will use Layout.name, else just "Layout"
+ , domain: "" // blank = current domain
+ , path: "" // blank = current page, "/" = entire website
+ , expires: "" // 'days' to keep cookie - leave blank for 'session cookie'
+ , secure: false
+ }
+};
+// Set stateManagement as a layout-option, NOT a pane-option
+$.layout.optionsMap.layout.push("stateManagement");
+
+/*
+ * State Management methods
+ */
+$.layout.state = {
+
+ /**
+ * Get the current layout state and save it to a cookie
+ *
+ * myLayout.saveCookie( keys, cookieOpts )
+ *
+ * @param {Object} inst
+ * @param {(string|Array)=} keys
+ * @param {Object=} cookieOpts
+ */
+ saveCookie: function (inst, keys, cookieOpts) {
+ var o = inst.options
+ , sm = o.stateManagement
+ , oC = $.extend(true, {}, sm.cookie, cookieOpts || null)
+ , data = inst.state.stateData = inst.readState( keys || sm.stateKeys ) // read current panes-state
+ ;
+ $.ui.cookie.write( oC.name || o.name || "Layout", $.layout.state.encodeJSON(data), oC );
+ return $.extend(true, {}, data); // return COPY of state.stateData data
+ }
+
+ /**
+ * Remove the state cookie
+ *
+ * @param {Object} inst
+ */
+, deleteCookie: function (inst) {
+ var o = inst.options;
+ $.ui.cookie.clear( o.stateManagement.cookie.name || o.name || "Layout" );
+ }
+
+ /**
+ * Read & return data from the cookie - as JSON
+ *
+ * @param {Object} inst
+ */
+, readCookie: function (inst) {
+ var o = inst.options;
+ var c = $.ui.cookie.read( o.stateManagement.cookie.name || o.name || "Layout" );
+ // convert cookie string back to a hash and return it
+ return c ? $.layout.state.decodeJSON(c) : {};
+ }
+
+ /**
+ * Get data from the cookie and USE IT to loadState
+ *
+ * @param {Object} inst
+ */
+, loadCookie: function (inst) {
+ var c = $.layout.state.readCookie(inst); // READ the cookie
+ if (c) {
+ inst.state.stateData = $.extend(true, {}, c); // SET state.stateData
+ inst.loadState(c); // LOAD the retrieved state
+ }
+ return c;
+ }
+
+ /**
+ * Update layout options from the cookie, if one exists
+ *
+ * @param {Object} inst
+ * @param {Object=} stateData
+ * @param {boolean=} animate
+ */
+, loadState: function (inst, data, opts) {
+ if (!$.isPlainObject( data ) || $.isEmptyObject( data )) return;
+
+ // normalize data & cache in the state object
+ data = inst.state.stateData = $.layout.transformData( data ); // panes = default subkey
+
+ // add missing/default state-restore options
+ var smo = inst.options.stateManagement;
+ opts = $.extend({
+ animateLoad: false //smo.animateLoad
+ , includeChildren: smo.includeChildren
+ }, opts );
+
+ if (!inst.state.initialized) {
+ /*
+ * layout NOT initialized, so just update its options
+ */
+ // MUST remove pane.children keys before applying to options
+ // use a copy so we don't remove keys from original data
+ var o = $.extend(true, {}, data);
+ //delete o.center; // center has no state-data - only children
+ $.each($.layout.config.allPanes, function (idx, pane) {
+ if (o[pane]) delete o[pane].children;
+ });
+ // update CURRENT layout-options with saved state data
+ $.extend(true, inst.options, o);
+ }
+ else {
+ /*
+ * layout already initialized, so modify layout's configuration
+ */
+ var noAnimate = !opts.animateLoad
+ , o, c, h, state, open
+ ;
+ $.each($.layout.config.borderPanes, function (idx, pane) {
+ o = data[ pane ];
+ if (!$.isPlainObject( o )) return; // no key, skip pane
+
+ s = o.size;
+ c = o.initClosed;
+ h = o.initHidden;
+ ar = o.autoResize
+ state = inst.state[pane];
+ open = state.isVisible;
+
+ // reset autoResize
+ if (ar)
+ state.autoResize = ar;
+ // resize BEFORE opening
+ if (!open)
+ inst._sizePane(pane, s, false, false, false); // false=skipCallback/noAnimation/forceResize
+ // open/close as necessary - DO NOT CHANGE THIS ORDER!
+ if (h === true) inst.hide(pane, noAnimate);
+ else if (c === true) inst.close(pane, false, noAnimate);
+ else if (c === false) inst.open (pane, false, noAnimate);
+ else if (h === false) inst.show (pane, false, noAnimate);
+ // resize AFTER any other actions
+ if (open)
+ inst._sizePane(pane, s, false, false, noAnimate); // animate resize if option passed
+ });
+
+ /*
+ * RECURSE INTO CHILD-LAYOUTS
+ */
+ if (opts.includeChildren) {
+ var paneStateChildren, childState;
+ $.each(inst.children, function (pane, paneChildren) {
+ paneStateChildren = data[pane] ? data[pane].children : 0;
+ if (paneStateChildren && paneChildren) {
+ $.each(paneChildren, function (stateKey, child) {
+ childState = paneStateChildren[stateKey];
+ if (child && childState)
+ child.loadState( childState );
+ });
+ }
+ });
+ }
+ }
+ }
+
+ /**
+ * Get the *current layout state* and return it as a hash
+ *
+ * @param {Object=} inst // Layout instance to get state for
+ * @param {object=} [opts] // State-Managements override options
+ */
+, readState: function (inst, opts) {
+ // backward compatility
+ if ($.type(opts) === 'string') opts = { keys: opts };
+ if (!opts) opts = {};
+ var sm = inst.options.stateManagement
+ , ic = opts.includeChildren
+ , recurse = ic !== undefined ? ic : sm.includeChildren
+ , keys = opts.stateKeys || sm.stateKeys
+ , alt = { isClosed: 'initClosed', isHidden: 'initHidden' }
+ , state = inst.state
+ , panes = $.layout.config.allPanes
+ , data = {}
+ , pair, pane, key, val
+ , ps, pC, child, array, count, branch
+ ;
+ if ($.isArray(keys)) keys = keys.join(",");
+ // convert keys to an array and change delimiters from '__' to '.'
+ keys = keys.replace(/__/g, ".").split(',');
+ // loop keys and create a data hash
+ for (var i=0, n=keys.length; i < n; i++) {
+ pair = keys[i].split(".");
+ pane = pair[0];
+ key = pair[1];
+ if ($.inArray(pane, panes) < 0) continue; // bad pane!
+ val = state[ pane ][ key ];
+ if (val == undefined) continue;
+ if (key=="isClosed" && state[pane]["isSliding"])
+ val = true; // if sliding, then *really* isClosed
+ ( data[pane] || (data[pane]={}) )[ alt[key] ? alt[key] : key ] = val;
+ }
+
+ // recurse into the child-layouts for each pane
+ if (recurse) {
+ $.each(panes, function (idx, pane) {
+ pC = inst.children[pane];
+ ps = state.stateData[pane];
+ if ($.isPlainObject( pC ) && !$.isEmptyObject( pC )) {
+ // ensure a key exists for this 'pane', eg: branch = data.center
+ branch = data[pane] || (data[pane] = {});
+ if (!branch.children) branch.children = {};
+ $.each( pC, function (key, child) {
+ // ONLY read state from an initialize layout
+ if ( child.state.initialized )
+ branch.children[ key ] = $.layout.state.readState( child );
+ // if we have PREVIOUS (onLoad) state for this child-layout, KEEP IT!
+ else if ( ps && ps.children && ps.children[ key ] ) {
+ branch.children[ key ] = $.extend(true, {}, ps.children[ key ] );
+ }
+ });
+ }
+ });
+ }
+
+ return data;
+ }
+
+ /**
+ * Stringify a JSON hash so can save in a cookie or db-field
+ */
+, encodeJSON: function (JSON) {
+ return parse(JSON);
+ function parse (h) {
+ var D=[], i=0, k, v, t // k = key, v = value
+ , a = $.isArray(h)
+ ;
+ for (k in h) {
+ v = h[k];
+ t = typeof v;
+ if (t == 'string') // STRING - add quotes
+ v = '"'+ v +'"';
+ else if (t == 'object') // SUB-KEY - recurse into it
+ v = parse(v);
+ D[i++] = (!a ? '"'+ k +'":' : '') + v;
+ }
+ return (a ? '[' : '{') + D.join(',') + (a ? ']' : '}');
+ };
+ }
+
+ /**
+ * Convert stringified JSON back to a hash object
+ * @see $.parseJSON(), adding in jQuery 1.4.1
+ */
+, decodeJSON: function (str) {
+ try { return $.parseJSON ? $.parseJSON(str) : window["eval"]("("+ str +")") || {}; }
+ catch (e) { return {}; }
+ }
+
+
+, _create: function (inst) {
+ var _ = $.layout.state
+ , o = inst.options
+ , sm = o.stateManagement
+ ;
+ // ADD State-Management plugin methods to inst
+ $.extend( inst, {
+ // readCookie - update options from cookie - returns hash of cookie data
+ readCookie: function () { return _.readCookie(inst); }
+ // deleteCookie
+ , deleteCookie: function () { _.deleteCookie(inst); }
+ // saveCookie - optionally pass keys-list and cookie-options (hash)
+ , saveCookie: function (keys, cookieOpts) { return _.saveCookie(inst, keys, cookieOpts); }
+ // loadCookie - readCookie and use to loadState() - returns hash of cookie data
+ , loadCookie: function () { return _.loadCookie(inst); }
+ // loadState - pass a hash of state to use to update options
+ , loadState: function (stateData, opts) { _.loadState(inst, stateData, opts); }
+ // readState - returns hash of current layout-state
+ , readState: function (keys) { return _.readState(inst, keys); }
+ // add JSON utility methods too...
+ , encodeJSON: _.encodeJSON
+ , decodeJSON: _.decodeJSON
+ });
+
+ // init state.stateData key, even if plugin is initially disabled
+ inst.state.stateData = {};
+
+ // autoLoad MUST BE one of: data-array, data-hash, callback-function, or TRUE
+ if ( !sm.autoLoad ) return;
+
+ // When state-data exists in the autoLoad key USE IT,
+ // even if stateManagement.enabled == false
+ if ($.isPlainObject( sm.autoLoad )) {
+ if (!$.isEmptyObject( sm.autoLoad )) {
+ inst.loadState( sm.autoLoad );
+ }
+ }
+ else if ( sm.enabled ) {
+ // update the options from cookie or callback
+ // if options is a function, call it to get stateData
+ if ($.isFunction( sm.autoLoad )) {
+ var d = {};
+ try {
+ d = sm.autoLoad( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn
+ } catch (e) {}
+ if (d && $.isPlainObject( d ) && !$.isEmptyObject( d ))
+ inst.loadState(d);
+ }
+ else // any other truthy value will trigger loadCookie
+ inst.loadCookie();
+ }
+ }
+
+, _unload: function (inst) {
+ var sm = inst.options.stateManagement;
+ if (sm.enabled && sm.autoSave) {
+ // if options is a function, call it to save the stateData
+ if ($.isFunction( sm.autoSave )) {
+ try {
+ sm.autoSave( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn
+ } catch (e) {}
+ }
+ else // any truthy value will trigger saveCookie
+ inst.saveCookie();
+ }
+ }
+
+};
+
+// add state initialization method to Layout's onCreate array of functions
+$.layout.onCreate.push( $.layout.state._create );
+$.layout.onUnload.push( $.layout.state._unload );
+
+
+
+
+/**
+ * jquery.layout.buttons 1.0
+ * $Date: 2011-07-16 08:00:00 (Sat, 16 July 2011) $
+ *
+ * Copyright (c) 2012
+ * Kevin Dalman (http://allpro.net)
+ *
+ * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
+ * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
+ *
+ * @requires: UI Layout 1.3.0.rc30.1 or higher
+ *
+ * @see: http://groups.google.com/group/jquery-ui-layout
+ *
+ * Docs: [ to come ]
+ * Tips: [ to come ]
+ */
+
+// tell Layout that the state plugin is available
+$.layout.plugins.buttons = true;
+
+// Add buttons options to layout.defaults
+$.layout.defaults.autoBindCustomButtons = false;
+// Specify autoBindCustomButtons as a layout-option, NOT a pane-option
+$.layout.optionsMap.layout.push("autoBindCustomButtons");
+
+/*
+ * Button methods
+ */
+$.layout.buttons = {
+
+ /**
+ * Searches for .ui-layout-button-xxx elements and auto-binds them as layout-buttons
+ *
+ * @see _create()
+ *
+ * @param {Object} inst Layout Instance object
+ */
+ init: function (inst) {
+ var pre = "ui-layout-button-"
+ , layout = inst.options.name || ""
+ , name;
+ $.each("toggle,open,close,pin,toggle-slide,open-slide".split(","), function (i, action) {
+ $.each($.layout.config.borderPanes, function (ii, pane) {
+ $("."+pre+action+"-"+pane).each(function(){
+ // if button was previously 'bound', data.layoutName was set, but is blank if layout has no 'name'
+ name = $(this).data("layoutName") || $(this).attr("layoutName");
+ if (name == undefined || name === layout)
+ inst.bindButton(this, action, pane);
+ });
+ });
+ });
+ }
+
+ /**
+ * Helper function to validate params received by addButton utilities
+ *
+ * Two classes are added to the element, based on the buttonClass...
+ * The type of button is appended to create the 2nd className:
+ * - ui-layout-button-pin // action btnClass
+ * - ui-layout-button-pin-west // action btnClass + pane
+ * - ui-layout-button-toggle
+ * - ui-layout-button-open
+ * - ui-layout-button-close
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
+ *
+ * @return {Array.} If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise returns null
+ */
+, get: function (inst, selector, pane, action) {
+ var $E = $(selector)
+ , o = inst.options
+ , err = o.errors.addButtonError
+ ;
+ if (!$E.length) { // element not found
+ $.layout.msg(err +" "+ o.errors.selector +": "+ selector, true);
+ }
+ else if ($.inArray(pane, $.layout.config.borderPanes) < 0) { // invalid 'pane' sepecified
+ $.layout.msg(err +" "+ o.errors.pane +": "+ pane, true);
+ $E = $(""); // NO BUTTON
+ }
+ else { // VALID
+ var btn = o[pane].buttonClass +"-"+ action;
+ $E .addClass( btn +" "+ btn +"-"+ pane )
+ .data("layoutName", o.name); // add layout identifier - even if blank!
+ }
+ return $E;
+ }
+
+
+ /**
+ * NEW syntax for binding layout-buttons - will eventually replace addToggle, addOpen, etc.
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} action
+ * @param {string} pane
+ */
+, bind: function (inst, selector, action, pane) {
+ var _ = $.layout.buttons;
+ switch (action.toLowerCase()) {
+ case "toggle": _.addToggle (inst, selector, pane); break;
+ case "open": _.addOpen (inst, selector, pane); break;
+ case "close": _.addClose (inst, selector, pane); break;
+ case "pin": _.addPin (inst, selector, pane); break;
+ case "toggle-slide": _.addToggle (inst, selector, pane, true); break;
+ case "open-slide": _.addOpen (inst, selector, pane, true); break;
+ }
+ return inst;
+ }
+
+ /**
+ * Add a custom Toggler button for a pane
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
+ * @param {boolean=} slide true = slide-open, false = pin-open
+ */
+, addToggle: function (inst, selector, pane, slide) {
+ $.layout.buttons.get(inst, selector, pane, "toggle")
+ .click(function(evt){
+ inst.toggle(pane, !!slide);
+ evt.stopPropagation();
+ });
+ return inst;
+ }
+
+ /**
+ * Add a custom Open button for a pane
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
+ * @param {boolean=} slide true = slide-open, false = pin-open
+ */
+, addOpen: function (inst, selector, pane, slide) {
+ $.layout.buttons.get(inst, selector, pane, "open")
+ .attr("title", inst.options[pane].tips.Open)
+ .click(function (evt) {
+ inst.open(pane, !!slide);
+ evt.stopPropagation();
+ });
+ return inst;
+ }
+
+ /**
+ * Add a custom Close button for a pane
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
+ */
+, addClose: function (inst, selector, pane) {
+ $.layout.buttons.get(inst, selector, pane, "close")
+ .attr("title", inst.options[pane].tips.Close)
+ .click(function (evt) {
+ inst.close(pane);
+ evt.stopPropagation();
+ });
+ return inst;
+ }
+
+ /**
+ * Add a custom Pin button for a pane
+ *
+ * Four classes are added to the element, based on the paneClass for the associated pane...
+ * Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin:
+ * - ui-layout-pane-pin
+ * - ui-layout-pane-west-pin
+ * - ui-layout-pane-pin-up
+ * - ui-layout-pane-west-pin-up
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
+ * @param {string} pane Name of the pane the pin is for: 'north', 'south', etc.
+ */
+, addPin: function (inst, selector, pane) {
+ var _ = $.layout.buttons
+ , $E = _.get(inst, selector, pane, "pin");
+ if ($E.length) {
+ var s = inst.state[pane];
+ $E.click(function (evt) {
+ _.setPinState(inst, $(this), pane, (s.isSliding || s.isClosed));
+ if (s.isSliding || s.isClosed) inst.open( pane ); // change from sliding to open
+ else inst.close( pane ); // slide-closed
+ evt.stopPropagation();
+ });
+ // add up/down pin attributes and classes
+ _.setPinState(inst, $E, pane, (!s.isClosed && !s.isSliding));
+ // add this pin to the pane data so we can 'sync it' automatically
+ // PANE.pins key is an array so we can store multiple pins for each pane
+ s.pins.push( selector ); // just save the selector string
+ }
+ return inst;
+ }
+
+ /**
+ * Change the class of the pin button to make it look 'up' or 'down'
+ *
+ * @see addPin(), syncPins()
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {Array.} $Pin The pin-span element in a jQuery wrapper
+ * @param {string} pane These are the params returned to callbacks by layout()
+ * @param {boolean} doPin true = set the pin 'down', false = set it 'up'
+ */
+, setPinState: function (inst, $Pin, pane, doPin) {
+ var updown = $Pin.attr("pin");
+ if (updown && doPin === (updown=="down")) return; // already in correct state
+ var
+ o = inst.options[pane]
+ , pin = o.buttonClass +"-pin"
+ , side = pin +"-"+ pane
+ , UP = pin +"-up "+ side +"-up"
+ , DN = pin +"-down "+side +"-down"
+ ;
+ $Pin
+ .attr("pin", doPin ? "down" : "up") // logic
+ .attr("title", doPin ? o.tips.Unpin : o.tips.Pin)
+ .removeClass( doPin ? UP : DN )
+ .addClass( doPin ? DN : UP )
+ ;
+ }
+
+ /**
+ * INTERNAL function to sync 'pin buttons' when pane is opened or closed
+ * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes
+ *
+ * @see open(), close()
+ *
+ * @param {Object} inst Layout Instance object
+ * @param {string} pane These are the params returned to callbacks by layout()
+ * @param {boolean} doPin True means set the pin 'down', False means 'up'
+ */
+, syncPinBtns: function (inst, pane, doPin) {
+ // REAL METHOD IS _INSIDE_ LAYOUT - THIS IS HERE JUST FOR REFERENCE
+ $.each(inst.state[pane].pins, function (i, selector) {
+ $.layout.buttons.setPinState(inst, $(selector), pane, doPin);
+ });
+ }
+
+
+, _load: function (inst) {
+ var _ = $.layout.buttons;
+ // ADD Button methods to Layout Instance
+ // Note: sel = jQuery Selector string
+ $.extend( inst, {
+ bindButton: function (sel, action, pane) { return _.bind(inst, sel, action, pane); }
+ // DEPRECATED METHODS
+ , addToggleBtn: function (sel, pane, slide) { return _.addToggle(inst, sel, pane, slide); }
+ , addOpenBtn: function (sel, pane, slide) { return _.addOpen(inst, sel, pane, slide); }
+ , addCloseBtn: function (sel, pane) { return _.addClose(inst, sel, pane); }
+ , addPinBtn: function (sel, pane) { return _.addPin(inst, sel, pane); }
+ });
+
+ // init state array to hold pin-buttons
+ for (var i=0; i<4; i++) {
+ var pane = $.layout.config.borderPanes[i];
+ inst.state[pane].pins = [];
+ }
+
+ // auto-init buttons onLoad if option is enabled
+ if ( inst.options.autoBindCustomButtons )
+ _.init(inst);
+ }
+
+, _unload: function (inst) {
+ // TODO: unbind all buttons???
+ }
+
+};
+
+// add initialization method to Layout's onLoad array of functions
+$.layout.onLoad.push( $.layout.buttons._load );
+//$.layout.onUnload.push( $.layout.buttons._unload );
+
+
+
+/**
+ * jquery.layout.browserZoom 1.0
+ * $Date: 2011-12-29 08:00:00 (Thu, 29 Dec 2011) $
+ *
+ * Copyright (c) 2012
+ * Kevin Dalman (http://allpro.net)
+ *
+ * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
+ * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
+ *
+ * @requires: UI Layout 1.3.0.rc30.1 or higher
+ *
+ * @see: http://groups.google.com/group/jquery-ui-layout
+ *
+ * TODO: Extend logic to handle other problematic zooming in browsers
+ * TODO: Add hotkey/mousewheel bindings to _instantly_ respond to these zoom event
+ */
+
+// tell Layout that the plugin is available
+$.layout.plugins.browserZoom = true;
+
+$.layout.defaults.browserZoomCheckInterval = 1000;
+$.layout.optionsMap.layout.push("browserZoomCheckInterval");
+
+/*
+ * browserZoom methods
+ */
+$.layout.browserZoom = {
+
+ _init: function (inst) {
+ // abort if browser does not need this check
+ if ($.layout.browserZoom.ratio() !== false)
+ $.layout.browserZoom._setTimer(inst);
+ }
+
+, _setTimer: function (inst) {
+ // abort if layout destroyed or browser does not need this check
+ if (inst.destroyed) return;
+ var o = inst.options
+ , s = inst.state
+ // don't need check if inst has parentLayout, but check occassionally in case parent destroyed!
+ // MINIMUM 100ms interval, for performance
+ , ms = inst.hasParentLayout ? 5000 : Math.max( o.browserZoomCheckInterval, 100 )
+ ;
+ // set the timer
+ setTimeout(function(){
+ if (inst.destroyed || !o.resizeWithWindow) return;
+ var d = $.layout.browserZoom.ratio();
+ if (d !== s.browserZoom) {
+ s.browserZoom = d;
+ inst.resizeAll();
+ }
+ // set a NEW timeout
+ $.layout.browserZoom._setTimer(inst);
+ }
+ , ms );
+ }
+
+, ratio: function () {
+ var w = window
+ , s = screen
+ , d = document
+ , dE = d.documentElement || d.body
+ , b = $.layout.browser
+ , v = b.version
+ , r, sW, cW
+ ;
+ // we can ignore all browsers that fire window.resize event onZoom
+ if ((b.msie && v > 8)
+ || !b.msie
+ ) return false; // don't need to track zoom
+
+ if (s.deviceXDPI && s.systemXDPI) // syntax compiler hack
+ return calc(s.deviceXDPI, s.systemXDPI);
+ // everything below is just for future reference!
+ if (b.webkit && (r = d.body.getBoundingClientRect))
+ return calc((r.left - r.right), d.body.offsetWidth);
+ if (b.webkit && (sW = w.outerWidth))
+ return calc(sW, w.innerWidth);
+ if ((sW = s.width) && (cW = dE.clientWidth))
+ return calc(sW, cW);
+ return false; // no match, so cannot - or don't need to - track zoom
+
+ function calc (x,y) { return (parseInt(x,10) / parseInt(y,10) * 100).toFixed(); }
+ }
+
+};
+// add initialization method to Layout's onLoad array of functions
+$.layout.onReady.push( $.layout.browserZoom._init );
+
+
+})( jQuery );
diff --git a/services/web/frontend/js/vendor/libs/jquery.storage.js b/services/web/frontend/js/vendor/libs/jquery.storage.js
new file mode 100644
index 0000000000..2af069d6fc
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/jquery.storage.js
@@ -0,0 +1,82 @@
+/*!
+ * jquery.storage.js 0.0.3 - https://github.com/yckart/jquery.storage.js
+ * The client-side storage for every browser, on any device.
+ *
+ * Copyright (c) 2012 Yannick Albert (http://yckart.com)
+ * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
+ * 2013/02/10
+ **/
+;(function($, window, document) {
+ 'use strict';
+
+ $.map(['localStorage', 'sessionStorage'], function( method ) {
+ var defaults = {
+ cookiePrefix : 'fallback:' + method + ':',
+ cookieOptions : {
+ path : '/',
+ domain : document.domain,
+ expires : ('localStorage' === method) ? { expires: 365 } : undefined
+ }
+ };
+
+ try {
+ $.support[method] = method in window && window[method] !== null;
+ } catch (e) {
+ $.support[method] = false;
+ }
+
+ $[method] = function(key, value) {
+ var options = $.extend({}, defaults, $[method].options);
+
+ this.getItem = function( key ) {
+ var returns = function(key){
+ return JSON.parse($.support[method] ? window[method].getItem(key) : $.cookie(options.cookiePrefix + key));
+ };
+ if(typeof key === 'string') return returns(key);
+
+ var arr = [],
+ i = key.length;
+ while(i--) arr[i] = returns(key[i]);
+ return arr;
+ };
+
+ this.setItem = function( key, value ) {
+ value = JSON.stringify(value);
+ return $.support[method] ? window[method].setItem(key, value) : $.cookie(options.cookiePrefix + key, value, options.cookieOptions);
+ };
+
+ this.removeItem = function( key ) {
+ return $.support[method] ? window[method].removeItem(key) : $.cookie(options.cookiePrefix + key, null, $.extend(options.cookieOptions, {
+ expires: -1
+ }));
+ };
+
+ this.clear = function() {
+ if($.support[method]) {
+ return window[method].clear();
+ } else {
+ var reg = new RegExp('^' + options.cookiePrefix, ''),
+ opts = $.extend(options.cookieOptions, {
+ expires: -1
+ });
+
+ if(document.cookie && document.cookie !== ''){
+ $.map(document.cookie.split(';'), function( cookie ){
+ if(reg.test(cookie = $.trim(cookie))) {
+ $.cookie( cookie.substr(0,cookie.indexOf('=')), null, opts);
+ }
+ });
+ }
+ }
+ };
+
+ if (typeof key !== "undefined") {
+ return typeof value !== "undefined" ? ( value === null ? this.removeItem(key) : this.setItem(key, value) ) : this.getItem(key);
+ }
+
+ return this;
+ };
+
+ $[method].options = defaults;
+ });
+}(jQuery, window, document));
diff --git a/services/web/frontend/js/vendor/libs/jquery.ui.touch-punch.js b/services/web/frontend/js/vendor/libs/jquery.ui.touch-punch.js
new file mode 100644
index 0000000000..f66237934a
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/jquery.ui.touch-punch.js
@@ -0,0 +1,180 @@
+/*!
+ * jQuery UI Touch Punch 0.2.3
+ *
+ * Copyright 2011–2014, Dave Furfero
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ *
+ * Depends:
+ * jquery.ui.widget.js
+ * jquery.ui.mouse.js
+ */
+(function ($) {
+
+ // Detect touch support
+ $.support.touch = 'ontouchend' in document;
+
+ // Ignore browsers without touch support
+ if (!$.support.touch) {
+ return;
+ }
+
+ var mouseProto = $.ui.mouse.prototype,
+ _mouseInit = mouseProto._mouseInit,
+ _mouseDestroy = mouseProto._mouseDestroy,
+ touchHandled;
+
+ /**
+ * Simulate a mouse event based on a corresponding touch event
+ * @param {Object} event A touch event
+ * @param {String} simulatedType The corresponding mouse event
+ */
+ function simulateMouseEvent (event, simulatedType) {
+
+ // Ignore multi-touch events
+ if (event.originalEvent.touches.length > 1) {
+ return;
+ }
+
+ event.preventDefault();
+
+ var touch = event.originalEvent.changedTouches[0],
+ simulatedEvent = document.createEvent('MouseEvents');
+
+ // Initialize the simulated mouse event using the touch event's coordinates
+ simulatedEvent.initMouseEvent(
+ simulatedType, // type
+ true, // bubbles
+ true, // cancelable
+ window, // view
+ 1, // detail
+ touch.screenX, // screenX
+ touch.screenY, // screenY
+ touch.clientX, // clientX
+ touch.clientY, // clientY
+ false, // ctrlKey
+ false, // altKey
+ false, // shiftKey
+ false, // metaKey
+ 0, // button
+ null // relatedTarget
+ );
+
+ // Dispatch the simulated event to the target element
+ event.target.dispatchEvent(simulatedEvent);
+ }
+
+ /**
+ * Handle the jQuery UI widget's touchstart events
+ * @param {Object} event The widget element's touchstart event
+ */
+ mouseProto._touchStart = function (event) {
+
+ var self = this;
+
+ // Ignore the event if another widget is already being handled
+ if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
+ return;
+ }
+
+ // Set the flag to prevent other widgets from inheriting the touch event
+ touchHandled = true;
+
+ // Track movement to determine if interaction was a click
+ self._touchMoved = false;
+
+ // Simulate the mouseover event
+ simulateMouseEvent(event, 'mouseover');
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+
+ // Simulate the mousedown event
+ simulateMouseEvent(event, 'mousedown');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchmove events
+ * @param {Object} event The document's touchmove event
+ */
+ mouseProto._touchMove = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Interaction was not a click
+ this._touchMoved = true;
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchend events
+ * @param {Object} event The document's touchend event
+ */
+ mouseProto._touchEnd = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Simulate the mouseup event
+ simulateMouseEvent(event, 'mouseup');
+
+ // Simulate the mouseout event
+ simulateMouseEvent(event, 'mouseout');
+
+ // If the touch interaction did not move, it should trigger a click
+ if (!this._touchMoved) {
+
+ // Simulate the click event
+ simulateMouseEvent(event, 'click');
+ }
+
+ // Unset the flag to allow other widgets to inherit the touch event
+ touchHandled = false;
+ };
+
+ /**
+ * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
+ * This method extends the widget with bound touch event handlers that
+ * translate touch events to mouse events and pass them to the widget's
+ * original mouse event handling methods.
+ */
+ mouseProto._mouseInit = function () {
+
+ var self = this;
+
+ // Delegate the touch handlers to the widget's element
+ self.element.bind({
+ touchstart: $.proxy(self, '_touchStart'),
+ touchmove: $.proxy(self, '_touchMove'),
+ touchend: $.proxy(self, '_touchEnd')
+ });
+
+ // Call the original $.ui.mouse init method
+ _mouseInit.call(self);
+ };
+
+ /**
+ * Remove the touch event handlers
+ */
+ mouseProto._mouseDestroy = function () {
+
+ var self = this;
+
+ // Delegate the touch handlers to the widget's element
+ self.element.unbind({
+ touchstart: $.proxy(self, '_touchStart'),
+ touchmove: $.proxy(self, '_touchMove'),
+ touchend: $.proxy(self, '_touchEnd')
+ });
+
+ // Call the original $.ui.mouse destroy method
+ _mouseDestroy.call(self);
+ };
+
+})(jQuery);
diff --git a/services/web/frontend/js/vendor/libs/latex-log-parser.js b/services/web/frontend/js/vendor/libs/latex-log-parser.js
new file mode 100644
index 0000000000..cad979eb98
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/latex-log-parser.js
@@ -0,0 +1,298 @@
+// Generated by CoffeeScript 1.10.0
+define(function() {
+ var HBOX_WARNING_REGEX, LATEX_WARNING_REGEX, LINES_REGEX, LOG_WRAP_LIMIT, LatexParser, LogText, PACKAGE_REGEX, PACKAGE_WARNING_REGEX, state;
+ LOG_WRAP_LIMIT = 79;
+ LATEX_WARNING_REGEX = /^LaTeX Warning: (.*)$/;
+ HBOX_WARNING_REGEX = /^(Over|Under)full \\(v|h)box/;
+ PACKAGE_WARNING_REGEX = /^(Package \b.+\b Warning:.*)$/;
+ LINES_REGEX = /lines? ([0-9]+)/;
+ PACKAGE_REGEX = /^Package (\b.+\b) Warning/;
+ LogText = function(text) {
+ var i, wrappedLines;
+ this.text = text.replace(/(\r\n)|\r/g, '\n');
+ wrappedLines = this.text.split('\n');
+ this.lines = [wrappedLines[0]];
+ i = 1;
+ while (i < wrappedLines.length) {
+ if (wrappedLines[i - 1].length === LOG_WRAP_LIMIT && wrappedLines[i - 1].slice(-3) !== '...') {
+ this.lines[this.lines.length - 1] += wrappedLines[i];
+ } else {
+ this.lines.push(wrappedLines[i]);
+ }
+ i++;
+ }
+ this.row = 0;
+ };
+ (function() {
+ this.nextLine = function() {
+ this.row++;
+ if (this.row >= this.lines.length) {
+ return false;
+ } else {
+ return this.lines[this.row];
+ }
+ };
+ this.rewindLine = function() {
+ this.row--;
+ };
+ this.linesUpToNextWhitespaceLine = function() {
+ return this.linesUpToNextMatchingLine(/^ *$/);
+ };
+ this.linesUpToNextMatchingLine = function(match) {
+ var lines, nextLine;
+ lines = [];
+ nextLine = this.nextLine();
+ if (nextLine !== false) {
+ lines.push(nextLine);
+ }
+ while (nextLine !== false && !nextLine.match(match) && nextLine !== false) {
+ nextLine = this.nextLine();
+ if (nextLine !== false) {
+ lines.push(nextLine);
+ }
+ }
+ return lines;
+ };
+ }).call(LogText.prototype);
+ state = {
+ NORMAL: 0,
+ ERROR: 1
+ };
+ LatexParser = function(text, options) {
+ this.log = new LogText(text);
+ this.state = state.NORMAL;
+ options = options || {};
+ this.fileBaseNames = options.fileBaseNames || [/compiles/, /\/usr\/local/];
+ this.ignoreDuplicates = options.ignoreDuplicates;
+ this.data = [];
+ this.fileStack = [];
+ this.currentFileList = this.rootFileList = [];
+ this.openParens = 0;
+ };
+ (function() {
+ this.parse = function() {
+ var lineNo;
+ while ((this.currentLine = this.log.nextLine()) !== false) {
+ if (this.state === state.NORMAL) {
+ if (this.currentLineIsError()) {
+ this.state = state.ERROR;
+ this.currentError = {
+ line: null,
+ file: this.currentFilePath,
+ level: 'error',
+ message: this.currentLine.slice(2),
+ content: '',
+ raw: this.currentLine + '\n'
+ };
+ } else if (this.currentLineIsRunawayArgument()) {
+ this.parseRunawayArgumentError();
+ } else if (this.currentLineIsWarning()) {
+ this.parseSingleWarningLine(LATEX_WARNING_REGEX);
+ } else if (this.currentLineIsHboxWarning()) {
+ this.parseHboxLine();
+ } else if (this.currentLineIsPackageWarning()) {
+ this.parseMultipleWarningLine();
+ } else {
+ this.parseParensForFilenames();
+ }
+ }
+ if (this.state === state.ERROR) {
+ this.currentError.content += this.log.linesUpToNextMatchingLine(/^l\.[0-9]+/).join('\n');
+ this.currentError.content += '\n';
+ this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n');
+ this.currentError.content += '\n';
+ this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n');
+ this.currentError.raw += this.currentError.content;
+ lineNo = this.currentError.raw.match(/l\.([0-9]+)/);
+ if (lineNo) {
+ this.currentError.line = parseInt(lineNo[1], 10);
+ }
+ this.data.push(this.currentError);
+ this.state = state.NORMAL;
+ }
+ }
+ return this.postProcess(this.data);
+ };
+ this.currentLineIsError = function() {
+ return this.currentLine[0] === '!';
+ };
+ this.currentLineIsRunawayArgument = function() {
+ return this.currentLine.match(/^Runaway argument/);
+ };
+ this.currentLineIsWarning = function() {
+ return !!this.currentLine.match(LATEX_WARNING_REGEX);
+ };
+ this.currentLineIsPackageWarning = function() {
+ return !!this.currentLine.match(PACKAGE_WARNING_REGEX);
+ };
+ this.currentLineIsHboxWarning = function() {
+ return !!this.currentLine.match(HBOX_WARNING_REGEX);
+ };
+ this.parseRunawayArgumentError = function() {
+ var lineNo;
+ this.currentError = {
+ line: null,
+ file: this.currentFilePath,
+ level: 'error',
+ message: this.currentLine,
+ content: '',
+ raw: this.currentLine + '\n'
+ };
+ this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n');
+ this.currentError.content += '\n';
+ this.currentError.content += this.log.linesUpToNextWhitespaceLine().join('\n');
+ this.currentError.raw += this.currentError.content;
+ lineNo = this.currentError.raw.match(/l\.([0-9]+)/);
+ if (lineNo) {
+ this.currentError.line = parseInt(lineNo[1], 10);
+ }
+ return this.data.push(this.currentError);
+ };
+ this.parseSingleWarningLine = function(prefix_regex) {
+ var line, lineMatch, warning, warningMatch;
+ warningMatch = this.currentLine.match(prefix_regex);
+ if (!warningMatch) {
+ return;
+ }
+ warning = warningMatch[1];
+ lineMatch = warning.match(LINES_REGEX);
+ line = lineMatch ? parseInt(lineMatch[1], 10) : null;
+ this.data.push({
+ line: line,
+ file: this.currentFilePath,
+ level: 'warning',
+ message: warning,
+ raw: warning
+ });
+ };
+ this.parseMultipleWarningLine = function() {
+ var line, lineMatch, packageMatch, packageName, prefixRegex, raw_message, warningMatch, warning_lines;
+ warningMatch = this.currentLine.match(PACKAGE_WARNING_REGEX);
+ if (!warningMatch) {
+ return;
+ }
+ warning_lines = [warningMatch[1]];
+ lineMatch = this.currentLine.match(LINES_REGEX);
+ line = lineMatch ? parseInt(lineMatch[1], 10) : null;
+ packageMatch = this.currentLine.match(PACKAGE_REGEX);
+ packageName = packageMatch[1];
+ prefixRegex = new RegExp('(?:\\(' + packageName + '\\))*[\\s]*(.*)', 'i');
+ while (!!(this.currentLine = this.log.nextLine())) {
+ lineMatch = this.currentLine.match(LINES_REGEX);
+ line = lineMatch ? parseInt(lineMatch[1], 10) : line;
+ warningMatch = this.currentLine.match(prefixRegex);
+ warning_lines.push(warningMatch[1]);
+ }
+ raw_message = warning_lines.join(' ');
+ this.data.push({
+ line: line,
+ file: this.currentFilePath,
+ level: 'warning',
+ message: raw_message,
+ raw: raw_message
+ });
+ };
+ this.parseHboxLine = function() {
+ var line, lineMatch;
+ lineMatch = this.currentLine.match(LINES_REGEX);
+ line = lineMatch ? parseInt(lineMatch[1], 10) : null;
+ this.data.push({
+ line: line,
+ file: this.currentFilePath,
+ level: 'typesetting',
+ message: this.currentLine,
+ raw: this.currentLine
+ });
+ };
+ this.parseParensForFilenames = function() {
+ var filePath, newFile, pos, previousFile, token;
+ pos = this.currentLine.search(/\(|\)/);
+ if (pos !== -1) {
+ token = this.currentLine[pos];
+ this.currentLine = this.currentLine.slice(pos + 1);
+ if (token === '(') {
+ filePath = this.consumeFilePath();
+ if (filePath) {
+ this.currentFilePath = filePath;
+ newFile = {
+ path: filePath,
+ files: []
+ };
+ this.fileStack.push(newFile);
+ this.currentFileList.push(newFile);
+ this.currentFileList = newFile.files;
+ } else {
+ this.openParens++;
+ }
+ } else if (token === ')') {
+ if (this.openParens > 0) {
+ this.openParens--;
+ } else {
+ if (this.fileStack.length > 1) {
+ this.fileStack.pop();
+ previousFile = this.fileStack[this.fileStack.length - 1];
+ this.currentFilePath = previousFile.path;
+ this.currentFileList = previousFile.files;
+ }
+ }
+ }
+ this.parseParensForFilenames();
+ }
+ };
+ this.consumeFilePath = function() {
+ var endOfFilePath, path;
+ if (!this.currentLine.match(/^\/?([^ \)]+\/)+/)) {
+ return false;
+ }
+ endOfFilePath = this.currentLine.search(RegExp(' |\\)'));
+ path = void 0;
+ if (endOfFilePath === -1) {
+ path = this.currentLine;
+ this.currentLine = '';
+ } else {
+ path = this.currentLine.slice(0, endOfFilePath);
+ this.currentLine = this.currentLine.slice(endOfFilePath);
+ }
+ return path;
+ };
+ return this.postProcess = function(data) {
+ var all, errors, hashEntry, hashes, i, typesetting, warnings;
+ all = [];
+ errors = [];
+ warnings = [];
+ typesetting = [];
+ hashes = [];
+ hashEntry = function(entry) {
+ return entry.raw;
+ };
+ i = 0;
+ while (i < data.length) {
+ if (this.ignoreDuplicates && hashes.indexOf(hashEntry(data[i])) > -1) {
+ i++;
+ continue;
+ }
+ if (data[i].level === 'error') {
+ errors.push(data[i]);
+ } else if (data[i].level === 'typesetting') {
+ typesetting.push(data[i]);
+ } else if (data[i].level === 'warning') {
+ warnings.push(data[i]);
+ }
+ all.push(data[i]);
+ hashes.push(hashEntry(data[i]));
+ i++;
+ }
+ return {
+ errors: errors,
+ warnings: warnings,
+ typesetting: typesetting,
+ all: all,
+ files: this.rootFileList
+ };
+ };
+ }).call(LatexParser.prototype);
+ LatexParser.parse = function(text, options) {
+ return new LatexParser(text, options).parse();
+ };
+ return LatexParser;
+});
diff --git a/services/web/frontend/js/vendor/libs/ng-context-menu-0.1.4.js b/services/web/frontend/js/vendor/libs/ng-context-menu-0.1.4.js
new file mode 100644
index 0000000000..29a7d202f8
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/ng-context-menu-0.1.4.js
@@ -0,0 +1,108 @@
+/**
+ * ng-context-menu - v0.1.4 - An AngularJS directive to display a context menu when a right-click event is triggered
+ *
+ * @author Ian Kennington Walter (http://ianvonwalter.com)
+ */
+angular
+ .module('ng-context-menu', [])
+ .factory('ContextMenuService', function() {
+ return {
+ element: null,
+ menuElement: null,
+ container: null
+ };
+ })
+ .directive('contextMenu', ['$document', 'ContextMenuService', function($document, ContextMenuService) {
+ return {
+ restrict: 'A',
+ scope: {
+ 'callback': '&contextMenu',
+ 'disabled': '&contextMenuDisabled'
+ },
+ link: function($scope, $element, $attrs) {
+ var opened = false;
+
+ function open(event, menuElement, container) {
+ menuElement.addClass('open');
+
+ if (container) {
+ container.append(menuElement);
+ }
+
+ var doc = $document[0].documentElement;
+ var docLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
+ docTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0),
+ elementHeight = menuElement[0].scrollHeight;
+ var docHeight = doc.clientHeight + docTop,
+ totalHeight = elementHeight + event.pageY,
+ top = Math.max(event.pageY - docTop, 0);
+
+ if (totalHeight > docHeight) {
+ top = top - (totalHeight - docHeight);
+ }
+
+ menuElement.css('top', top + 'px');
+ menuElement.css('left', Math.max(event.pageX - docLeft, 0) + 'px');
+ opened = true;
+ }
+
+ function close(menuElement) {
+ menuElement.removeClass('open');
+ opened = false;
+ }
+
+ $element.bind('contextmenu', function(event) {
+ if (!$scope.disabled()) {
+ if (ContextMenuService.menuElement !== null) {
+ close(ContextMenuService.menuElement);
+ }
+ ContextMenuService.menuElement = angular.element(document.getElementById($attrs.target));
+ if (typeof($attrs.contextMenuContainer) != "undefined") {
+ ContextMenuService.container = angular.element($attrs.contextMenuContainer)
+ }
+ ContextMenuService.element = event.target;
+ // console.log('set', ContextMenuService.element);
+
+ event.preventDefault();
+ event.stopPropagation();
+ $scope.$apply(function() {
+ $scope.callback({ $event: event });
+ open(event, ContextMenuService.menuElement, ContextMenuService.container);
+ });
+ }
+ });
+
+ function handleKeyUpEvent(event) {
+ //console.log('keyup');
+ if (!$scope.disabled() && opened && event.keyCode === 27) {
+ $scope.$apply(function() {
+ close(ContextMenuService.menuElement);
+ });
+ }
+ }
+
+ function handleClickEvent(event) {
+ if (!$scope.disabled() &&
+ opened &&
+ (event.button !== 2 || event.target !== ContextMenuService.element)) {
+ $scope.$apply(function() {
+ close(ContextMenuService.menuElement);
+ });
+ }
+ }
+
+ $document.bind('keyup', handleKeyUpEvent);
+ // Firefox treats a right-click as a click and a contextmenu event while other browsers
+ // just treat it as a contextmenu event
+ $document.bind('click', handleClickEvent);
+ $document.bind('contextmenu', handleClickEvent);
+
+ $scope.$on('$destroy', function() {
+ //console.log('destroy');
+ $document.unbind('keyup', handleKeyUpEvent);
+ $document.unbind('click', handleClickEvent);
+ $document.unbind('contextmenu', handleClickEvent);
+ });
+ }
+ };
+ }]);
diff --git a/services/web/frontend/js/vendor/libs/passfield.js b/services/web/frontend/js/vendor/libs/passfield.js
new file mode 100644
index 0000000000..650da95c41
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/passfield.js
@@ -0,0 +1,2 @@
+/*! Pass*Field v1.1.9 | (c) 2014 Antelle | https://github.com/antelle/passfield/blob/master/MIT-LICENSE.txt */
+!function(a,b,c){"use strict";var d=c.PassField=c.PassField||{};d.Config=d.Config||{},d.Config.locales={en:{lower:!0,msg:{pass:"password",and:"and",showPass:"Show password",hidePass:"Hide password",genPass:"Random password",passTooShort:"password is too short (min. length: {})",noCharType:"password must contain {}",digits:"digits",letters:"letters",letters_up:"letters in UPPER case",symbols:"symbols",inBlackList:"password is in list of top used passwords",passRequired:"password is required",equalTo:"password is equal to login",repeat:"password consists of repeating characters",badChars:"password contains bad characters: “{}â€",weakWarn:"weak",invalidPassWarn:"*",weakTitle:"This password is weak",generateMsg:"To generate a strong password, click {} button."}},de:{lower:!1,msg:{pass:"Passwort",and:"und",showPass:"Passwort anzeigen",hidePass:"Passwort verbergen",genPass:"Zufallspasswort",passTooShort:"Passwort ist zu kurz (Mindestlänge: {})",noCharType:"Passwort muss {} enthalten",digits:"Ziffern",letters:"Buchstaben",letters_up:"Buchstaben in GROSSSCHRIFT",symbols:"Symbole",inBlackList:"Passwort steht auf der Liste der beliebtesten Passwörter",passRequired:"Passwort wird benötigt",equalTo:"Passwort ist wie Anmeldung",repeat:"Passwort besteht aus sich wiederholenden Zeichen",badChars:"Passwort enthält ungültige Zeichen: “{}â€",weakWarn:"Schwach",invalidPassWarn:"*",weakTitle:"Dieses Passwort ist schwach",generateMsg:"Klicken Sie auf den {}-Button, um ein starkes Passwort zu generieren."}},fr:{lower:!0,msg:{pass:"mot de passe",and:"et",showPass:"Montrer le mot de passe",hidePass:"Cacher le mot de passe",genPass:"Mot de passe aléatoire",passTooShort:"le mot de passe est trop court (min. longueur: {})",noCharType:"le mot de passe doit contenir des {}",digits:"chiffres",letters:"lettres",letters_up:"lettres en MAJUSCULES",symbols:"symboles",inBlackList:"le mot de passe est dans la liste des plus utilisés",passRequired:"le mot de passe est requis",equalTo:"le mot de passe est le même que l'identifiant",repeat:"le mot de passe est une répétition de caractères",badChars:"le mot de passe contient des caractères incorrects: “{}â€",weakWarn:"faible",invalidPassWarn:"*",weakTitle:"Ce mot de passe est faible",generateMsg:"Pour créer un mot de passe fort cliquez sur le bouton {}."}},it:{lower:!1,msg:{pass:"password",and:"e",showPass:"Mostra password",hidePass:"Nascondi password",genPass:"Password casuale",passTooShort:"la password è troppo breve (lunghezza min.: {})",noCharType:"la password deve contenere {}",digits:"numeri",letters:"lettere",letters_up:"lettere in MAIUSCOLO",symbols:"simboli",inBlackList:"la password è nella lista delle password più usate",passRequired:"è necessaria una password",equalTo:"la password è uguale al login",repeat:"la password è composta da caratteri che si ripetono",badChars:"la password contiene caratteri non accettati: “{}â€",weakWarn:"debole",invalidPassWarn:"*",weakTitle:"Questa password è debole",generateMsg:"Per generare una password forte, clicca sul tasto {}."}},ru:{lower:!0,msg:{pass:"пароль",and:"и",showPass:"Показать пароль",hidePass:"Скрыть пароль",genPass:"Случайный пароль",passTooShort:"пароль Ñлишком короткий (мин. длина: {})",noCharType:"в пароле должны быть {}",digits:"цифры",letters:"буквы",letters_up:"буквы в ВЕРХÐЕМ региÑтре",symbols:"Ñимволы",inBlackList:"Ñтот пароль чаÑто иÑпользуетÑÑ Ð² Интернете",passRequired:"пароль обÑзателен",equalTo:"пароль Ñовпадает Ñ Ð»Ð¾Ð³Ð¸Ð½Ð¾Ð¼",repeat:"пароль ÑоÑтоит из повторÑющихÑÑ Ñимволов",badChars:"в пароле еÑÑ‚ÑŒ недопуÑтимые Ñимволы: «{}»",weakWarn:"Ñлабый",invalidPassWarn:"*",weakTitle:"Пароль Ñлабый, его легко взломать",generateMsg:"Чтобы Ñгенерировать пароль, нажмите кнопку {}."}},ua:{lower:!0,msg:{pass:"пароль",and:"i",showPass:"Показати пароль",hidePass:"Сховати пароль",genPass:"Випадковий пароль",passTooShort:"пароль Ñ” занадто коротким (мiн. довжина: {})",noCharType:"пароль повинен міÑтити {}",digits:"цифри",letters:"букви",letters_up:"букви у ВЕРХÐЬОМУ регіÑтрі",symbols:"cимволи",inBlackList:"пароль входить до ÑпиÑку паролей, що викориÑтовуютьÑÑ Ð½Ð°Ð¹Ñ‡Ð°Ñтіше",passRequired:"пароль Ñ” обов'Ñзковим",equalTo:"пароль та логін однакові",repeat:"пароль міÑтить повторювані Ñимволи",badChars:"пароль міÑтить неприпуÑтимі Ñимволи: «{}»",weakWarn:"Ñлабкий",invalidPassWarn:"*",weakTitle:"Цей пароль Ñ” Ñлабким",generateMsg:"Щоб ​​Ñтворити надійний пароль, натиÑніть кнопку {}."}},es:{lower:!0,msg:{pass:"contraseña",and:"y",showPass:"Mostrar contraseña",hidePass:"Ocultar contraseña",genPass:"Contraseña aleatoria",passTooShort:"contraseña demasiado corta (longitud mÃn.: {})",noCharType:"la contraseña debe contener {}",digits:"dÃgitos",letters:"letras",letters_up:"letras en MAYÚSCULAS",symbols:"sÃmbolos",inBlackList:"la contraseña está en la lista de las contraseñas más usadas",passRequired:"se requiere contraseña",equalTo:"la contraseña es igual al inicio de sesión",repeat:"la contraseña tiene caracteres repetidos",badChars:"la contraseña contiene caracteres no permitidos: “{}â€",weakWarn:"débil",invalidPassWarn:"*",weakTitle:"Esta contraseña es débil",generateMsg:"Para generar una contraseña segura, haga clic en el botón de {}."}},el:{lower:!0,msg:{pass:"Ï€Ïόσβασης",and:"και",showPass:"Î Ïοβολή ÎºÏ‰Î´Î¹ÎºÎ¿Ï Ï€Ïόσβασης",hidePass:"ΑπόκÏυψη ÎºÏ‰Î´Î¹ÎºÎ¿Ï Ï€Ïόσβασης",genPass:"Τυχαίος κωδικός Ï€Ïόσβασης",passTooShort:"ο κωδικός Ï€Ïόσβασης είναι Ï€Î¿Î»Ï Î¼Î¹ÎºÏός (ελάχιστο μήκος: {})",noCharType:"ο κωδικός Ï€Ïόσβασης Ï€ÏÎπει να πεÏιÎχει {}",digits:"ψηφία",letters:"λατινικά γÏάμματα",letters_up:"λατινικά γÏάμματα με ΚΕΦΑΛΑΙΑ",symbols:"σÏμβολα",inBlackList:"ο κωδικός Ï€Ïόσβασης βÏίσκεται σε κατάλογο δημοφιλÎστεÏων κωδικών",passRequired:"απαιτείται κωδικός Ï€Ïόσβασης",equalTo:"ο κωδικός είναι όμοιος με το όνομα χÏήστη",repeat:"ο κωδικός αποτελείται από επαναλαμβανόμενους χαÏακτήÏες",badChars:"ο κωδικός πεÏιÎχει μη επιτÏεπτοÏÏ‚ χαÏακτήÏες: “{}â€",weakWarn:"αδÏναμος",invalidPassWarn:"*",weakTitle:"Αυτός ο κωδικός Ï€Ïόσβασης είναι αδÏναμος",generateMsg:"Για να δημιουÏγήσετε δυνατό κωδικό Ï€Ïόσβασης, κάντε κλικ στο κουμπί {}."}},pt:{lower:!0,msg:{pass:"senha",and:"e",showPass:"Mostrar senha",hidePass:"Ocultar senha",genPass:"Senha aleatória",passTooShort:"senha muito curta (tamanho mÃnimo: {})",noCharType:"Senha deve conter {}",digits:"dÃgito",letters:"letras",letters_up:"letras maiúsculas",symbols:"sÃmbolos",inBlackList:"senha está na lista das senhas mais usadas",passRequired:"senha é obrigatória",equalTo:"senha igual ao login",repeat:"senha consiste em uma repetição de caracteres",badChars:"senha tem caracteres inválidos: “{}â€",weakWarn:"fraca",invalidPassWarn:"*",weakTitle:"Esta senha é fraca",generateMsg:"Para gerar uma senha forte, clique no botão {}."}}}}(window.jQuery,document,window),function(a,b,c,d){"use strict";var e=c.PassField=c.PassField||{};e.CharTypes={DIGIT:"digits",LETTER:"letters",LETTER_UP:"letters_up",SYMBOL:"symbols",UNKNOWN:"unknown"},e.CheckModes={MODERATE:0,STRICT:1},e.Config={defaults:{pattern:"abcdef12",acceptRate:.8,allowEmpty:!0,isMasked:!0,showToggle:!0,showGenerate:!0,showWarn:!0,showTip:!0,tipPopoverStyle:{},strengthCheckTimeout:500,validationCallback:null,blackList:[],locale:"",localeMsg:{},warnMsgClassName:"help-inline",errorWrapClassName:"error",allowAnyChars:!0,checkMode:e.CheckModes.MODERATE,chars:{digits:"1234567890",letters:"abcdefghijklmnopqrstuvwxyzßабвгедёжзийклмнопрÑтуфхцчшщъыьÑÑŽÑґєåäâáà ãéèêëÃìîїóòôõöüúùûýñçøåæþðαβγδεζηθικλμνξοπÏσςτυφχψω",letters_up:"ABCDEFGHIJKLMNOPQRSTUVWXYZÐБВГЕДÐЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬÐЮЯÒЄÅÄÂÃÀÃÉÈÊËÃÌÎЇÓÒÔÕÖÜÚÙÛÃÑÇØÅÆÞÃΑΒΓΔΕΖΗΘΙΚΛΜÎΞΟΠΡΣΤΥΦΧΨΩ",symbols:"@#$%^&*()-_=+[]{};:<>/?!"},events:{generated:null,switched:null},nonMatchField:null,length:{min:null,max:null},maskBtn:{textMasked:"abc",textUnmasked:"•••",className:!1,classMasked:!1,classUnmasked:!1}},locales:e.Config?e.Config.locales:{},blackList:["password","123456","12345678","abc123","qwerty","monkey","letmein","dragon","111111","baseball","iloveyou","trustno1","1234567","sunshine","master","123123","welcome","shadow","ashley","football","jesus","michael","ninja","mustang","password1","p@ssw0rd","miss","root","secret"],generationChars:{digits:"1234567890",letters:"abcdefghijklmnopqrstuvwxyz",letters_up:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},dataAttr:"PassField.Field"},e.Field=function(g,h){function i(){j(),k()&&(l(),n(),C(),o(),E(),N(Cb.isMasked,!1),Q(),tb(e.Config.dataAttr,this))}function j(){Cb.blackList=(Cb.blackList||[]).concat(e.Config.blackList)}function k(){return"string"==typeof g&&(g=b.getElementById(g)),Bb.mainInput=g,!!Bb.mainInput}function l(){var a="en",b=Cb.locale;!b&&navigator.language&&(b=navigator.language.replace(/\-.*/g,"")),b&&(ub=Ab.locales[b]),ub&&(ub=f.extend({},Ab.locales[a],ub)),ub||(ub=f.extend({},Ab.locales[a])),Cb.localeMsg&&f.extend(ub.msg,Cb.localeMsg)}function m(a){Bb.mainInput.value=a,Bb.clearInput&&(Bb.clearInput.value=a),H()}function n(){vb=Bb.mainInput.id,vb||(vb="i"+Math.round(1e5*Math.random()),Bb.mainInput.id=vb)}function o(){var a=ib(Bb.mainInput);a.top+=lb(Bb.mainInput,"marginTop"),p(),q(),r(),s(),t(),u(),v(a),w(a),x(),setTimeout(y,0)}function p(){Bb.wrapper=Bb.mainInput.parentNode,pb(Bb.wrapper,"wrap"),zb.hasInlineBlock||pb(Bb.wrapper,"wrap-no-ib"),"static"==kb(Bb.wrapper,"position")&&(Bb.wrapper.style.position="relative")}function q(){Cb.length&&Cb.length.max&&Bb.mainInput.setAttribute("maxLength",Cb.length.max.toString())}function r(){if(!zb.changeType){Bb.clearInput=cb("input",{type:"text",id:"txt-clear",className:"txt-clear",value:Bb.mainInput.value},{display:"none"});var a=Bb.mainInput.className;a&&pb(Bb.clearInput,a,!0);var b=Bb.mainInput.style.cssText;b&&(Bb.clearInput.style.cssText=b),f.each(["maxLength","size","placeholder"],function(a){var b=Bb.mainInput.getAttribute(a);b&&Bb.clearInput.setAttribute(a,b)}),mb(Bb.mainInput,Bb.clearInput)}pb(Bb.mainInput,"txt-pass")}function s(){Cb.showWarn&&(Bb.warnMsg=cb("div",{id:"warn",className:"warn"},{margin:"0 0 0 3px"}),Cb.warnMsgClassName&&pb(Bb.warnMsg,Cb.warnMsgClassName,!0),mb(Bb.clearInput||Bb.mainInput,Bb.warnMsg))}function t(){Cb.showToggle&&(Bb.maskBtn=cb("div",{id:"btn-mask",className:"btn-mask",title:ub.msg.showPass},{position:"absolute",margin:"0",padding:"0"}),pb(Bb.maskBtn,"btn"),Cb.maskBtn.className&&pb(Bb.maskBtn,Cb.maskBtn.className,!0),Cb.maskBtn.classMasked&&pb(Bb.maskBtn,Cb.maskBtn.classMasked,!0),nb(Bb.maskBtn,Cb.maskBtn.textMasked),mb(Bb.mainInput,Bb.maskBtn))}function u(){Cb.showGenerate&&(Bb.genBtn=cb("div",{id:"btn-gen",className:"btn-gen",title:ub.msg.genPass},{position:"absolute",margin:"0",padding:"0"}),pb(Bb.genBtn,"btn"),mb(Bb.mainInput,Bb.genBtn),Bb.genBtnInner=cb("div",{id:"btn-gen-i",className:"btn-gen-i",title:ub.msg.genPass}),Bb.genBtn.appendChild(Bb.genBtnInner))}function v(b){if(Cb.showTip)if(Cb.tipPopoverStyle&&a&&"function"==typeof a.fn.popover)a(Bb.mainInput).popover(f.extend({title:null,placement:Cb.tipPopoverStyle.placement||function(b,d){var e=a(d).position().top-a(c).scrollTop(),f=a(c).height()-e;return f>300||f>e?"bottom":"top"},animation:!1},Cb.tipPopoverStyle,{trigger:"manual",html:!0,content:function(){return Lb}}));else{Bb.tip=cb("div",{id:"tip",className:"tip"},{position:"absolute",margin:"0",padding:"0",width:b.width+"px"}),mb(Bb.mainInput,Bb.tip);var d=cb("div",{id:"tip-arr-wrap",className:"tip-arr-wrap"});Bb.tip.appendChild(d),d.appendChild(cb("div",{id:"tip-arr",className:"tip-arr"})),d.appendChild(cb("div",{id:"tip-arr-in",className:"tip-arr-in"})),Bb.tipBody=cb("div",{id:"tip-body",className:"tip-body"}),Bb.tip.appendChild(Bb.tipBody)}}function w(a){if(zb.placeholders)!Bb.mainInput.getAttribute("placeholder")&&Bb.mainInput.getAttribute("data-placeholder")&&Bb.mainInput.setAttribute("placeholder",Bb.mainInput.getAttribute("data-placeholder"));else{var b=Bb.mainInput.getAttribute("placeholder")||Bb.mainInput.getAttribute("data-placeholder");b&&(Bb.placeholder=cb("div",{id:"placeholder",className:"placeholder"},{position:"absolute",margin:"0",padding:"0",height:a.height+"px",lineHeight:a.height+"px"}),nb(Bb.placeholder,b),mb(Bb.mainInput,Bb.placeholder))}}function x(){zb.passSymbol&&(Bb.passLengthChecker=cb("div",{id:"len"},{position:"absolute",height:kb(Bb.mainInput,"height"),top:"-10000px",left:"-10000px",display:"block",color:"transparent",border:"none"}),mb(Bb.mainInput,Bb.passLengthChecker),setTimeout(function(){f.each(["marginLeft","fontFamily","fontSize","fontWeight","fontStyle","fontVariant"],function(a){var b=kb(Bb.mainInput,a);b&&(Bb.passLengthChecker.style[a]=b)})},50))}function y(){A(),B();var a=ib(D()),b=z();Bb.maskBtn&&"none"!=Bb.maskBtn.style.display&&(b+=lb(Bb.maskBtn,"width"),jb(Bb.maskBtn,{top:a.top,left:a.left+a.width-b,height:a.height})),Bb.genBtn&&"none"!=Bb.genBtn.style.display&&(b+=lb(Bb.genBtn,"width"),jb(Bb.genBtn,{top:a.top,left:a.left+a.width-b,height:a.height}),Bb.genBtnInner.style.marginTop=Math.max(0,Math.round((a.height-19)/2))+"px"),Bb.placeholder&&"none"!=Bb.placeholder.style.display&&jb(Bb.placeholder,{top:a.top,left:a.left+7,height:a.height}),Bb.tip&&"none"!=Bb.tip.style.display&&jb(Bb.tip,{left:a.left,top:a.top+a.height,width:a.width})}function z(){var a=lb(D(),"paddingRight");return Math.max(Ob,a)}function A(){Bb.genBtn&&(Bb.genBtn.style.display=Gb||Hb&&!Ib?"block":"none"),Bb.maskBtn&&(Bb.maskBtn.style.display=Gb||Hb&&!Jb?"block":"none")}function B(){if(Cb.showTip)if(Bb.tip)Bb.tip.style.display=Eb&&Hb?"block":"none";else if(Eb&&Hb){if(!Kb||Lb!=Kb){var b=a(Bb.mainInput).data("popover")||a(Bb.mainInput).data("bs.popover"),c=b.options,d=c.animation;Kb&&(c.animation=!1);var e=D().offsetWidth-2,f=b.$tip;f?f.width(e):b.options.template&&(b.options.template=b.options.template.replace('class="popover"','class="popover" style="width: '+e+'px"')),Bb.clearInput&&(b.$element=a(D())),a(Bb.mainInput).popover("show"),Kb=Lb,c.animation=d}}else Kb&&(Kb=null,a(Bb.mainInput).popover("hide"))}function C(){var a=!0,c=!0,d=b.createElement("input");"placeholder"in d||(a=!1),d.setAttribute("style","position:absolute;left:-10000px;top:-10000px;"),b.body.appendChild(d);try{d.setAttribute("type","password")}catch(e){c=!1}b.body.removeChild(d);var f=b.createElement("div");f.setAttribute("style","display:inline-block"),f.style.paddingLeft=f.style.width="1px",b.body.appendChild(f);var g=2==f.offsetWidth,h="inline-block"===kb(f,"display");b.body.removeChild(f);var i=navigator.userAgent.indexOf("AppleWebKit")>=0||navigator.userAgent.indexOf("Opera")>=0||navigator.userAgent.indexOf("Firefox")>=0&&navigator.platform.indexOf("Mac")>=0?"•":"â—";zb={placeholders:a,changeType:c,boxModel:g,hasInlineBlock:h,passSymbol:i}}function D(){return Db?Bb.mainInput:Bb.clearInput||Bb.mainInput}function E(){if(f.each(Bb.clearInput?[Bb.mainInput,Bb.clearInput]:[Bb.mainInput],function(a){f.attachEvent(a,"onkeyup",H),f.attachEvent(a,"onfocus",K),f.attachEvent(a,"onblur",L),f.attachEvent(a,"onmouseover",G),f.attachEvent(a,"onmouseout",G),Bb.placeholder&&f.attachEvent(a,"onkeydown",J)}),f.attachEvent(c,"onresize",y),Bb.maskBtn&&(f.attachEvent(Bb.maskBtn,"onclick",function(){N()}),f.attachEvent(Bb.maskBtn,"onmouseover",G),f.attachEvent(Bb.maskBtn,"onmouseout",G)),Bb.genBtn&&(f.attachEvent(Bb.genBtn,"onclick",function(){R()}),f.attachEvent(Bb.genBtn,"onmouseover",G),f.attachEvent(Bb.genBtn,"onmouseout",G)),Bb.placeholder&&f.attachEvent(Bb.placeholder,"onclick",F),Cb.nonMatchField){var a=ob(Cb.nonMatchField);a&&f.attachEvent(a,"onkeyup",M)}}function F(){D().focus()}function G(a){var b="mouseover"===a.type,c=a.relatedTarget?a.relatedTarget:b?a.fromElement:a.toElement;(!c||!c.id||0!=c.id.indexOf(Mb+"btn")&&c!==Bb.mainInput&&c!==Bb.clearInput)&&(Gb=b,y())}function H(a){var b,c=a?a.which||a.keyCode:null,d=c===Qb||c===Pb;b=Bb.clearInput?Db?Bb.clearInput.value=Bb.mainInput.value:Bb.mainInput.value=Bb.clearInput.value:Bb.mainInput.value,Cb.strengthCheckTimeout>0&&!Eb&&!d?(wb&&clearTimeout(wb),wb=setTimeout(S,Cb.strengthCheckTimeout)):S(),Bb.placeholder&&!b&&(Bb.placeholder.style.display="block"),I()}function I(){if(Bb.passLengthChecker){var a=D().value;Db&&(a=a.replace(/./g,zb.passSymbol)),nb(Bb.passLengthChecker,a);var b=Bb.passLengthChecker.offsetWidth;b+=lb(Bb.mainInput,"paddingLeft");var c=0,d=0,e=hb(D()),f=e.width,g=!1,h=z();if(Bb.maskBtn){c=lb(Bb.maskBtn,"width");var i=f-c-h,j=b>i;Jb!=j&&(g=!0,Jb=j)}if(Bb.genBtn){d=lb(Bb.genBtn,"width");var k=f-c-d-h,l=b>k;Ib!=l&&(g=!0,Ib=l)}g&&y()}}function J(){Bb.placeholder&&(Bb.placeholder.style.display="none")}function K(){xb&&(clearTimeout(xb),xb=null),yb&&(clearTimeout(yb),yb=null),Hb=!0,y()}function L(){xb=setTimeout(function(){xb=null,Hb=!1,y(),Cb.isMasked&&!yb&&(yb=setTimeout(function(){yb=null,N(!0,!1)},1500))},100)}function M(){Eb&&S()}function N(a,b){b===d&&(b=!0);var c=a!=Db;if(a=a===d?!Db:!!a,zb.changeType){var e=D(),g=O(e);e.setAttribute("type",a?"password":"text"),b&&(P(e,g),e.focus())}else{var h=kb(D(),"display")||"block",i=a?Bb.clearInput:Bb.mainInput,j=a?Bb.mainInput:Bb.clearInput;Db!=a&&f.each(["paddingRight","width","backgroundImage","backgroundPosition","backgroundRepeat","backgroundAttachment","border"],function(a){var b=i.style[a];b&&(j.style[a]=b)});var k=O(i);j.style.display=h,i.style.display="none",j.value=i.value,b&&(P(j,k),j.focus()),Bb.mainInput.nextSibling!=Bb.clearInput&&mb(Bb.mainInput,Bb.clearInput)}Bb.maskBtn&&(nb(Bb.maskBtn,a?Cb.maskBtn.textMasked:Cb.maskBtn.textUnmasked),a?(Cb.maskBtn.classUnmasked&&qb(Bb.maskBtn,Cb.maskBtn.classUnmasked,!0),Cb.maskBtn.classMasked&&pb(Bb.maskBtn,Cb.maskBtn.classMasked,!0)):(Cb.maskBtn.classMasked&&qb(Bb.maskBtn,Cb.maskBtn.classMasked,!0),Cb.maskBtn.classUnmasked&&pb(Bb.maskBtn,Cb.maskBtn.classUnmasked,!0)),Bb.maskBtn.title=a?ub.msg.showPass:ub.msg.hidePass),Db=a,I(),y(),c&&sb("switched",Db)}function O(a){return"number"==typeof a.selectionStart&&"number"==typeof a.selectionEnd?{start:a.selectionStart,end:a.selectionEnd}:null}function P(a,b){b&&"number"==typeof a.selectionStart&&"number"==typeof a.selectionEnd&&(a.selectionStart=b.start,a.selectionEnd=b.end)}function Q(){("function"==typeof Bb.mainInput.hasAttribute&&Bb.mainInput.hasAttribute("autofocus")||Bb.mainInput.getAttribute("autofocus"))&&(Bb.mainInput.focus(),K())}function R(){var a=$();Bb.mainInput.value=a,Bb.clearInput&&(Bb.clearInput.value=a),sb("generated",a),N(!1),wb&&(clearTimeout(wb),wb=null),S(),Bb.placeholder&&(Bb.placeholder.style.display="none")}function S(){wb&&(clearTimeout(wb),wb=null);var a=D().value,b=T(a);if(0==a.length)b={strength:Cb.allowEmpty?0:null,messages:[ub.msg.passRequired]};else{!Cb.allowAnyChars&&b.charTypes[e.CharTypes.UNKNOWN]&&(b={strength:null,messages:[ub.msg.badChars.replace("{}",b.charTypes[e.CharTypes.UNKNOWN])]}),delete b.charTypes;var c=!1;f.each(Cb.blackList,function(b){return b==a?(c=!0,!1):!0}),c&&(b={strength:0,messages:[ub.msg.inBlackList]}),a&&a===X()&&(b={strength:0,messages:[ub.msg.equalTo]})}if("function"==typeof Cb.validationCallback){var d,g,h=Cb.validationCallback(Bb.mainInput,b);h&&h.messages&&f.isArray(h.messages)&&(d=h.messages),h&&Object.prototype.hasOwnProperty.call(h,"strength")&&("number"==typeof h.strength||null===h.strength)&&(g=h.strength),d&&d.length?(b.messages=d,b.strength=g):g&&g>b.strength&&(b.strength=g)}return 0==a.length&&Cb.allowEmpty?(W(),Fb={strength:0},!0):null===b.strength||b.strengthf&&(h=h.substring(0,f)),b=b+" ("+h+")"}d.push(b)}});var h=1-d.length/g;if(d.length&&(d=[U(d)]),Cb.checkMode==e.CheckModes.MODERATE){var i=0;f.each(c,function(a){b[a]||i++}),h+=i/g}var j=Cb.pattern.length,k=a.length/j-1;if(Cb.length&&Cb.length.min&&a.lengthj&&(j=Cb.length.min)),0>k?(h+=k,d.push(ub.msg.passTooShort.replace("{}",j.toString()))):Cb.checkMode==e.CheckModes.MODERATE&&(h+=k/g),a.length>2){for(var l=a.charAt(0),m=!0,n=0;nh&&(h=0),h>1&&(h=1),{strength:h,messages:d,charTypes:c}}function U(a){for(var b=a[0],c=1;c ",f=f.toUpperCase()),d+=f+b[e].substring(1),d&&"."!=d.charAt(d.length-1)&&(d+=".")}if(d&&"."!=d.charAt(d.length-1)&&(d+="."),Fb={strength:a,message:d},Bb.warnMsg&&(nb(Bb.warnMsg,c),Bb.warnMsg.title=d,Cb.errorWrapClassName&&pb(Bb.wrapper,Cb.errorWrapClassName,!0)),Cb.showTip){var g=d;Bb.genBtn&&(g+=" "+ub.msg.generateMsg.replace("{}",'
')),Lb=g,Bb.tipBody&&nb(Bb.tipBody,g)}Eb=!0,y()}function W(){Bb.warnMsg&&(nb(Bb.warnMsg,""),Bb.warnMsg.title="",Cb.errorWrapClassName&&qb(Bb.wrapper,Cb.errorWrapClassName,!0)),Lb=null,Eb=!1,y()}function X(){if(!Cb.nonMatchField)return null;var a=ob(Cb.nonMatchField);return a?a.value:null}function Y(){return Fb?Fb.message:null}function Z(){return Fb?Fb.strength:-1}function $(){var a="",b=_(Cb.pattern,e.CharTypes.SYMBOL),c=[];return f.each(b,function(a,b){for(var d=0;d=0?(g=a,!1):!0}),c[g]=(c[g]||"")+e}return c}function ab(a){return Mb+a+"-"+vb}function bb(a){return Mb+a}function cb(a,b,c){return b.id&&(b.id=ab(b.id)),b.className&&(b.className=bb(b.className)),f.newEl(a,b,c)}function db(a){try{return a.getBoundingClientRect()}catch(b){return{top:0,left:0}}}function eb(a){var b=a.ownerDocument;if(!b)return{top:0,left:0};var d=db(a);return{top:d.top+(c.pageYOffset||0)-(b.documentElement.clientTop||0),left:d.left+(c.pageXOffset||0)-(b.documentElement.clientLeft||0)}}function fb(a){var c;try{c=a.offsetParent}catch(d){}for(c||(c=b.documentElement);c&&"html"!=c.nodeName.toLowerCase()&&"static"===kb(c,"position");)c=c.offsetParent;return c||b.documentElement}function gb(a){var b,c={top:0,left:0};if("fixed"===kb(a,"position"))b=db(a);else{var d=fb(a);b=eb(a),"html"!=d.nodeName.toLowerCase()&&(c=eb(d)),c.top+=lb(d,"borderTopWidth"),c.left+=lb(d,"borderLeftWidth")}return{top:b.top-c.top-lb(a,"marginTop"),left:b.left-c.left-lb(a,"marginLeft")}}function hb(a){return{width:a.offsetWidth,height:a.offsetHeight}}function ib(a){return f.extend(eb(a),hb(a))}function jb(a,b){if(b.height&&!isNaN(b.height)&&(a.style.height=b.height+"px",a.style.lineHeight=b.height+"px"),b.width&&!isNaN(b.width)&&(a.style.width=b.width+"px"),b.top||b.left){if("none"==kb(a,"display"))return a.style.top=b.top+"px",a.style.left=b.left+"px",void 0;var c,d,e;if(e=eb(a),d=kb(a,"top")||0,c=kb(a,"left")||0,(d+c+"").indexOf("auto")>-1){var f=gb(a);d=f.top,c=f.left}else d=parseFloat(d)||0,c=parseFloat(c)||0;b.top&&(a.style.top=b.top-e.top+d+"px"),b.left&&(a.style.left=b.left-e.left+c+"px")}}function kb(a,b){var d="function"==typeof c.getComputedStyle?c.getComputedStyle(a,null):a.currentStyle;return d?d[b]:null}function lb(a,b){var c=kb(a,b);if(!c)return 0;var d=parseFloat(c);return isNaN(d)?0:d}function mb(a,b){a.parentNode&&a.parentNode.insertBefore(b,a.nextSibling)}function nb(a,c){try{a.innerHTML=c}catch(d){var e=b.createElement("c");for(e.innerHTML=c;a.firstChild;)a.removeChild(a.firstChild);a.appendChild(e)}}function ob(a){return"string"==typeof a?b.getElementById(a):a.jquery?a[0]:a}function pb(a,b,c){rb(a,b,c)||(a.className=a.className+(a.className?" ":"")+(c===!0?b:bb(b)))}function qb(a,b,c){rb(a,b,c)&&(a.className=(" "+a.className+" ").replace((c===!0?b:bb(b))+" ","").replace(/^\s+|\s+$/g,""))}function rb(a,b,c){return b=" "+(c===!0?b:bb(b))+" ",(" "+a.className+" ").replace(/[\n\t]/g," ").indexOf(b)>-1}function sb(b,c){if(a)try{a(Bb.mainInput).trigger(Nb+b,c)}catch(d){}if(Cb.events&&"function"==typeof Cb.events[b])try{Cb.events[b].call(Bb.mainInput,c)}catch(d){}}function tb(b,c){a&&a(Bb.mainInput).data(b,c)}var ub,vb,wb,xb,yb,zb,Ab=e.Config,Bb={},Cb=f.extend({},Ab.defaults,h),Db=!0,Eb=!1,Fb=null,Gb=!1,Hb=!1,Ib=!1,Jb=!1,Kb=!1,Lb=null,Mb="a_pf-",Nb="pass:",Ob=5,Pb=46,Qb=8;this.toggleMasking=function(a){N(a)},this.setPass=m,this.validatePass=S,this.getPassValidationMessage=Y,this.getPassStrength=Z,i.call(this)};var f={};f.extend=function(){for(var a=arguments,b=1;b= VerbosityLevel.INFOS) {
+ console.log('Info: ' + msg);
+ }
+}
+
+function warn(msg) {
+ if (verbosity >= VerbosityLevel.WARNINGS) {
+ console.log('Warning: ' + msg);
+ }
+}
+
+function unreachable(msg) {
+ throw new Error(msg);
+}
+
+function assert(cond, msg) {
+ if (!cond) {
+ unreachable(msg);
+ }
+}
+
+function isSameOrigin(baseUrl, otherUrl) {
+ try {
+ var base = new _url_polyfill.URL(baseUrl);
+
+ if (!base.origin || base.origin === 'null') {
+ return false;
+ }
+ } catch (e) {
+ return false;
+ }
+
+ var other = new _url_polyfill.URL(otherUrl, base);
+ return base.origin === other.origin;
+}
+
+function _isValidProtocol(url) {
+ if (!url) {
+ return false;
+ }
+
+ switch (url.protocol) {
+ case 'http:':
+ case 'https:':
+ case 'ftp:':
+ case 'mailto:':
+ case 'tel:':
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+function createValidAbsoluteUrl(url, baseUrl) {
+ if (!url) {
+ return null;
+ }
+
+ try {
+ var absoluteUrl = baseUrl ? new _url_polyfill.URL(url, baseUrl) : new _url_polyfill.URL(url);
+
+ if (_isValidProtocol(absoluteUrl)) {
+ return absoluteUrl;
+ }
+ } catch (ex) {}
+
+ return null;
+}
+
+function shadow(obj, prop, value) {
+ Object.defineProperty(obj, prop, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: false
+ });
+ return value;
+}
+
+var PasswordException = function PasswordExceptionClosure() {
+ function PasswordException(msg, code) {
+ this.name = 'PasswordException';
+ this.message = msg;
+ this.code = code;
+ }
+
+ PasswordException.prototype = new Error();
+ PasswordException.constructor = PasswordException;
+ return PasswordException;
+}();
+
+exports.PasswordException = PasswordException;
+
+var UnknownErrorException = function UnknownErrorExceptionClosure() {
+ function UnknownErrorException(msg, details) {
+ this.name = 'UnknownErrorException';
+ this.message = msg;
+ this.details = details;
+ }
+
+ UnknownErrorException.prototype = new Error();
+ UnknownErrorException.constructor = UnknownErrorException;
+ return UnknownErrorException;
+}();
+
+exports.UnknownErrorException = UnknownErrorException;
+
+var InvalidPDFException = function InvalidPDFExceptionClosure() {
+ function InvalidPDFException(msg) {
+ this.name = 'InvalidPDFException';
+ this.message = msg;
+ }
+
+ InvalidPDFException.prototype = new Error();
+ InvalidPDFException.constructor = InvalidPDFException;
+ return InvalidPDFException;
+}();
+
+exports.InvalidPDFException = InvalidPDFException;
+
+var MissingPDFException = function MissingPDFExceptionClosure() {
+ function MissingPDFException(msg) {
+ this.name = 'MissingPDFException';
+ this.message = msg;
+ }
+
+ MissingPDFException.prototype = new Error();
+ MissingPDFException.constructor = MissingPDFException;
+ return MissingPDFException;
+}();
+
+exports.MissingPDFException = MissingPDFException;
+
+var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
+ function UnexpectedResponseException(msg, status) {
+ this.name = 'UnexpectedResponseException';
+ this.message = msg;
+ this.status = status;
+ }
+
+ UnexpectedResponseException.prototype = new Error();
+ UnexpectedResponseException.constructor = UnexpectedResponseException;
+ return UnexpectedResponseException;
+}();
+
+exports.UnexpectedResponseException = UnexpectedResponseException;
+
+var FormatError = function FormatErrorClosure() {
+ function FormatError(msg) {
+ this.message = msg;
+ }
+
+ FormatError.prototype = new Error();
+ FormatError.prototype.name = 'FormatError';
+ FormatError.constructor = FormatError;
+ return FormatError;
+}();
+
+exports.FormatError = FormatError;
+
+var AbortException = function AbortExceptionClosure() {
+ function AbortException(msg) {
+ this.name = 'AbortException';
+ this.message = msg;
+ }
+
+ AbortException.prototype = new Error();
+ AbortException.constructor = AbortException;
+ return AbortException;
+}();
+
+exports.AbortException = AbortException;
+var NullCharactersRegExp = /\x00/g;
+
+function removeNullCharacters(str) {
+ if (typeof str !== 'string') {
+ warn('The argument for removeNullCharacters must be a string.');
+ return str;
+ }
+
+ return str.replace(NullCharactersRegExp, '');
+}
+
+function bytesToString(bytes) {
+ assert(bytes !== null && _typeof(bytes) === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
+ var length = bytes.length;
+ var MAX_ARGUMENT_COUNT = 8192;
+
+ if (length < MAX_ARGUMENT_COUNT) {
+ return String.fromCharCode.apply(null, bytes);
+ }
+
+ var strBuf = [];
+
+ for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
+ var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
+ var chunk = bytes.subarray(i, chunkEnd);
+ strBuf.push(String.fromCharCode.apply(null, chunk));
+ }
+
+ return strBuf.join('');
+}
+
+function stringToBytes(str) {
+ assert(typeof str === 'string', 'Invalid argument for stringToBytes');
+ var length = str.length;
+ var bytes = new Uint8Array(length);
+
+ for (var i = 0; i < length; ++i) {
+ bytes[i] = str.charCodeAt(i) & 0xFF;
+ }
+
+ return bytes;
+}
+
+function arrayByteLength(arr) {
+ if (arr.length !== undefined) {
+ return arr.length;
+ }
+
+ assert(arr.byteLength !== undefined);
+ return arr.byteLength;
+}
+
+function arraysToBytes(arr) {
+ if (arr.length === 1 && arr[0] instanceof Uint8Array) {
+ return arr[0];
+ }
+
+ var resultLength = 0;
+ var i,
+ ii = arr.length;
+ var item, itemLength;
+
+ for (i = 0; i < ii; i++) {
+ item = arr[i];
+ itemLength = arrayByteLength(item);
+ resultLength += itemLength;
+ }
+
+ var pos = 0;
+ var data = new Uint8Array(resultLength);
+
+ for (i = 0; i < ii; i++) {
+ item = arr[i];
+
+ if (!(item instanceof Uint8Array)) {
+ if (typeof item === 'string') {
+ item = stringToBytes(item);
+ } else {
+ item = new Uint8Array(item);
+ }
+ }
+
+ itemLength = item.byteLength;
+ data.set(item, pos);
+ pos += itemLength;
+ }
+
+ return data;
+}
+
+function string32(value) {
+ return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
+}
+
+function log2(x) {
+ if (x <= 0) {
+ return 0;
+ }
+
+ return Math.ceil(Math.log2(x));
+}
+
+function readInt8(data, start) {
+ return data[start] << 24 >> 24;
+}
+
+function readUint16(data, offset) {
+ return data[offset] << 8 | data[offset + 1];
+}
+
+function readUint32(data, offset) {
+ return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
+}
+
+function isLittleEndian() {
+ var buffer8 = new Uint8Array(4);
+ buffer8[0] = 1;
+ var view32 = new Uint32Array(buffer8.buffer, 0, 1);
+ return view32[0] === 1;
+}
+
+function isEvalSupported() {
+ try {
+ new Function('');
+ return true;
+ } catch (e) {
+ return false;
+ }
+}
+
+var Util = function UtilClosure() {
+ function Util() {}
+
+ var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
+
+ Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
+ rgbBuf[1] = r;
+ rgbBuf[3] = g;
+ rgbBuf[5] = b;
+ return rgbBuf.join('');
+ };
+
+ Util.transform = function Util_transform(m1, m2) {
+ return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
+ };
+
+ Util.applyTransform = function Util_applyTransform(p, m) {
+ var xt = p[0] * m[0] + p[1] * m[2] + m[4];
+ var yt = p[0] * m[1] + p[1] * m[3] + m[5];
+ return [xt, yt];
+ };
+
+ Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
+ var d = m[0] * m[3] - m[1] * m[2];
+ var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
+ var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
+ return [xt, yt];
+ };
+
+ Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
+ var p1 = Util.applyTransform(r, m);
+ var p2 = Util.applyTransform(r.slice(2, 4), m);
+ var p3 = Util.applyTransform([r[0], r[3]], m);
+ var p4 = Util.applyTransform([r[2], r[1]], m);
+ return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
+ };
+
+ Util.inverseTransform = function Util_inverseTransform(m) {
+ var d = m[0] * m[3] - m[1] * m[2];
+ return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
+ };
+
+ Util.apply3dTransform = function Util_apply3dTransform(m, v) {
+ return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
+ };
+
+ Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
+ var transpose = [m[0], m[2], m[1], m[3]];
+ var a = m[0] * transpose[0] + m[1] * transpose[2];
+ var b = m[0] * transpose[1] + m[1] * transpose[3];
+ var c = m[2] * transpose[0] + m[3] * transpose[2];
+ var d = m[2] * transpose[1] + m[3] * transpose[3];
+ var first = (a + d) / 2;
+ var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
+ var sx = first + second || 1;
+ var sy = first - second || 1;
+ return [Math.sqrt(sx), Math.sqrt(sy)];
+ };
+
+ Util.normalizeRect = function Util_normalizeRect(rect) {
+ var r = rect.slice(0);
+
+ if (rect[0] > rect[2]) {
+ r[0] = rect[2];
+ r[2] = rect[0];
+ }
+
+ if (rect[1] > rect[3]) {
+ r[1] = rect[3];
+ r[3] = rect[1];
+ }
+
+ return r;
+ };
+
+ Util.intersect = function Util_intersect(rect1, rect2) {
+ function compare(a, b) {
+ return a - b;
+ }
+
+ var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
+ orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
+ result = [];
+ rect1 = Util.normalizeRect(rect1);
+ rect2 = Util.normalizeRect(rect2);
+
+ if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
+ result[0] = orderedX[1];
+ result[2] = orderedX[2];
+ } else {
+ return false;
+ }
+
+ if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
+ result[1] = orderedY[1];
+ result[3] = orderedY[2];
+ } else {
+ return false;
+ }
+
+ return result;
+ };
+
+ return Util;
+}();
+
+exports.Util = Util;
+var PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC];
+
+function stringToPDFString(str) {
+ var i,
+ n = str.length,
+ strBuf = [];
+
+ if (str[0] === '\xFE' && str[1] === '\xFF') {
+ for (i = 2; i < n; i += 2) {
+ strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
+ }
+ } else {
+ for (i = 0; i < n; ++i) {
+ var code = PDFStringTranslateTable[str.charCodeAt(i)];
+ strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
+ }
+ }
+
+ return strBuf.join('');
+}
+
+function stringToUTF8String(str) {
+ return decodeURIComponent(escape(str));
+}
+
+function utf8StringToString(str) {
+ return unescape(encodeURIComponent(str));
+}
+
+function isEmptyObj(obj) {
+ for (var key in obj) {
+ return false;
+ }
+
+ return true;
+}
+
+function isBool(v) {
+ return typeof v === 'boolean';
+}
+
+function isNum(v) {
+ return typeof v === 'number';
+}
+
+function isString(v) {
+ return typeof v === 'string';
+}
+
+function isArrayBuffer(v) {
+ return _typeof(v) === 'object' && v !== null && v.byteLength !== undefined;
+}
+
+function isArrayEqual(arr1, arr2) {
+ if (arr1.length !== arr2.length) {
+ return false;
+ }
+
+ return arr1.every(function (element, index) {
+ return element === arr2[index];
+ });
+}
+
+function isSpace(ch) {
+ return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
+}
+
+function createPromiseCapability() {
+ var capability = Object.create(null);
+ var isSettled = false;
+ Object.defineProperty(capability, 'settled', {
+ get: function get() {
+ return isSettled;
+ }
+ });
+ capability.promise = new Promise(function (resolve, reject) {
+ capability.resolve = function (data) {
+ isSettled = true;
+ resolve(data);
+ };
+
+ capability.reject = function (reason) {
+ isSettled = true;
+ reject(reason);
+ };
+ });
+ return capability;
+}
+
+var createObjectURL = function createObjectURLClosure() {
+ var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+ return function createObjectURL(data, contentType) {
+ var forceDataSchema = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
+ if (!forceDataSchema && _url_polyfill.URL.createObjectURL) {
+ var blob = new Blob([data], {
+ type: contentType
+ });
+ return _url_polyfill.URL.createObjectURL(blob);
+ }
+
+ var buffer = 'data:' + contentType + ';base64,';
+
+ for (var i = 0, ii = data.length; i < ii; i += 3) {
+ var b1 = data[i] & 0xFF;
+ var b2 = data[i + 1] & 0xFF;
+ var b3 = data[i + 2] & 0xFF;
+ var d1 = b1 >> 2,
+ d2 = (b1 & 3) << 4 | b2 >> 4;
+ var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
+ var d4 = i + 2 < ii ? b3 & 0x3F : 64;
+ buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
+ }
+
+ return buffer;
+ };
+}();
+
+exports.createObjectURL = createObjectURL;
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+var globalScope = __w_pdfjs_require__(3);
+
+if (!globalScope._pdfjsCompatibilityChecked) {
+ globalScope._pdfjsCompatibilityChecked = true;
+
+ var isNodeJS = __w_pdfjs_require__(4);
+
+ var hasDOM = (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object';
+
+ (function checkNodeBtoa() {
+ if (globalScope.btoa || !isNodeJS()) {
+ return;
+ }
+
+ globalScope.btoa = function (chars) {
+ return Buffer.from(chars, 'binary').toString('base64');
+ };
+ })();
+
+ (function checkNodeAtob() {
+ if (globalScope.atob || !isNodeJS()) {
+ return;
+ }
+
+ globalScope.atob = function (input) {
+ return Buffer.from(input, 'base64').toString('binary');
+ };
+ })();
+
+ (function checkChildNodeRemove() {
+ if (!hasDOM) {
+ return;
+ }
+
+ if (typeof Element.prototype.remove !== 'undefined') {
+ return;
+ }
+
+ Element.prototype.remove = function () {
+ if (this.parentNode) {
+ this.parentNode.removeChild(this);
+ }
+ };
+ })();
+
+ (function checkDOMTokenListAddRemove() {
+ if (!hasDOM || isNodeJS()) {
+ return;
+ }
+
+ var div = document.createElement('div');
+ div.classList.add('testOne', 'testTwo');
+
+ if (div.classList.contains('testOne') === true && div.classList.contains('testTwo') === true) {
+ return;
+ }
+
+ var OriginalDOMTokenListAdd = DOMTokenList.prototype.add;
+ var OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;
+
+ DOMTokenList.prototype.add = function () {
+ for (var _len = arguments.length, tokens = new Array(_len), _key = 0; _key < _len; _key++) {
+ tokens[_key] = arguments[_key];
+ }
+
+ for (var _i = 0, _tokens = tokens; _i < _tokens.length; _i++) {
+ var token = _tokens[_i];
+ OriginalDOMTokenListAdd.call(this, token);
+ }
+ };
+
+ DOMTokenList.prototype.remove = function () {
+ for (var _len2 = arguments.length, tokens = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ tokens[_key2] = arguments[_key2];
+ }
+
+ for (var _i2 = 0, _tokens2 = tokens; _i2 < _tokens2.length; _i2++) {
+ var token = _tokens2[_i2];
+ OriginalDOMTokenListRemove.call(this, token);
+ }
+ };
+ })();
+
+ (function checkDOMTokenListToggle() {
+ if (!hasDOM || isNodeJS()) {
+ return;
+ }
+
+ var div = document.createElement('div');
+
+ if (div.classList.toggle('test', 0) === false) {
+ return;
+ }
+
+ DOMTokenList.prototype.toggle = function (token) {
+ var force = arguments.length > 1 ? !!arguments[1] : !this.contains(token);
+ return this[force ? 'add' : 'remove'](token), force;
+ };
+ })();
+
+ (function checkStringStartsWith() {
+ if (String.prototype.startsWith) {
+ return;
+ }
+
+ __w_pdfjs_require__(5);
+ })();
+
+ (function checkStringEndsWith() {
+ if (String.prototype.endsWith) {
+ return;
+ }
+
+ __w_pdfjs_require__(36);
+ })();
+
+ (function checkStringIncludes() {
+ if (String.prototype.includes) {
+ return;
+ }
+
+ __w_pdfjs_require__(38);
+ })();
+
+ (function checkArrayIncludes() {
+ if (Array.prototype.includes) {
+ return;
+ }
+
+ __w_pdfjs_require__(40);
+ })();
+
+ (function checkArrayFrom() {
+ if (Array.from) {
+ return;
+ }
+
+ __w_pdfjs_require__(47);
+ })();
+
+ (function checkObjectAssign() {
+ if (Object.assign) {
+ return;
+ }
+
+ __w_pdfjs_require__(70);
+ })();
+
+ (function checkMathLog2() {
+ if (Math.log2) {
+ return;
+ }
+
+ Math.log2 = __w_pdfjs_require__(75);
+ })();
+
+ (function checkNumberIsNaN() {
+ if (Number.isNaN) {
+ return;
+ }
+
+ Number.isNaN = __w_pdfjs_require__(77);
+ })();
+
+ (function checkNumberIsInteger() {
+ if (Number.isInteger) {
+ return;
+ }
+
+ Number.isInteger = __w_pdfjs_require__(79);
+ })();
+
+ (function checkPromise() {
+ if (globalScope.Promise && globalScope.Promise.prototype && globalScope.Promise.prototype["finally"]) {
+ return;
+ }
+
+ globalScope.Promise = __w_pdfjs_require__(82);
+ })();
+
+ (function checkWeakMap() {
+ if (globalScope.WeakMap) {
+ return;
+ }
+
+ globalScope.WeakMap = __w_pdfjs_require__(102);
+ })();
+
+ (function checkWeakSet() {
+ if (globalScope.WeakSet) {
+ return;
+ }
+
+ globalScope.WeakSet = __w_pdfjs_require__(119);
+ })();
+
+ (function checkStringCodePointAt() {
+ if (String.codePointAt) {
+ return;
+ }
+
+ String.codePointAt = __w_pdfjs_require__(123);
+ })();
+
+ (function checkStringFromCodePoint() {
+ if (String.fromCodePoint) {
+ return;
+ }
+
+ String.fromCodePoint = __w_pdfjs_require__(125);
+ })();
+
+ (function checkSymbol() {
+ if (globalScope.Symbol) {
+ return;
+ }
+
+ __w_pdfjs_require__(127);
+ })();
+
+ (function checkStringPadStart() {
+ if (String.prototype.padStart) {
+ return;
+ }
+
+ __w_pdfjs_require__(134);
+ })();
+
+ (function checkStringPadEnd() {
+ if (String.prototype.padEnd) {
+ return;
+ }
+
+ __w_pdfjs_require__(138);
+ })();
+
+ (function checkObjectValues() {
+ if (Object.values) {
+ return;
+ }
+
+ Object.values = __w_pdfjs_require__(140);
+ })();
+}
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : {};
+
+/***/ }),
+/* 4 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+module.exports = function isNodeJS() {
+ return (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && process + '' === '[object process]' && !process.versions['nw'] && !process.versions['electron'];
+};
+
+/***/ }),
+/* 5 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(6);
+
+module.exports = __w_pdfjs_require__(9).String.startsWith;
+
+/***/ }),
+/* 6 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var toLength = __w_pdfjs_require__(28);
+
+var context = __w_pdfjs_require__(30);
+
+var STARTS_WITH = 'startsWith';
+var $startsWith = ''[STARTS_WITH];
+$export($export.P + $export.F * __w_pdfjs_require__(35)(STARTS_WITH), 'String', {
+ startsWith: function startsWith(searchString) {
+ var that = context(this, searchString, STARTS_WITH);
+ var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
+ var search = String(searchString);
+ return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search;
+ }
+});
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var core = __w_pdfjs_require__(9);
+
+var hide = __w_pdfjs_require__(10);
+
+var redefine = __w_pdfjs_require__(20);
+
+var ctx = __w_pdfjs_require__(26);
+
+var PROTOTYPE = 'prototype';
+
+var $export = function $export(type, name, source) {
+ var IS_FORCED = type & $export.F;
+ var IS_GLOBAL = type & $export.G;
+ var IS_STATIC = type & $export.S;
+ var IS_PROTO = type & $export.P;
+ var IS_BIND = type & $export.B;
+ var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
+ var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
+ var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
+ var key, own, out, exp;
+ if (IS_GLOBAL) source = name;
+
+ for (key in source) {
+ own = !IS_FORCED && target && target[key] !== undefined;
+ out = (own ? target : source)[key];
+ exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
+ if (target) redefine(target, key, out, type & $export.U);
+ if (exports[key] != out) hide(exports, key, exp);
+ if (IS_PROTO && expProto[key] != out) expProto[key] = out;
+ }
+};
+
+global.core = core;
+$export.F = 1;
+$export.G = 2;
+$export.S = 4;
+$export.P = 8;
+$export.B = 16;
+$export.W = 32;
+$export.U = 64;
+$export.R = 128;
+module.exports = $export;
+
+/***/ }),
+/* 8 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
+if (typeof __g == 'number') __g = global;
+
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var core = module.exports = {
+ version: '2.6.9'
+};
+if (typeof __e == 'number') __e = core;
+
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var dP = __w_pdfjs_require__(11);
+
+var createDesc = __w_pdfjs_require__(19);
+
+module.exports = __w_pdfjs_require__(15) ? function (object, key, value) {
+ return dP.f(object, key, createDesc(1, value));
+} : function (object, key, value) {
+ object[key] = value;
+ return object;
+};
+
+/***/ }),
+/* 11 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var anObject = __w_pdfjs_require__(12);
+
+var IE8_DOM_DEFINE = __w_pdfjs_require__(14);
+
+var toPrimitive = __w_pdfjs_require__(18);
+
+var dP = Object.defineProperty;
+exports.f = __w_pdfjs_require__(15) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
+ anObject(O);
+ P = toPrimitive(P, true);
+ anObject(Attributes);
+ if (IE8_DOM_DEFINE) try {
+ return dP(O, P, Attributes);
+ } catch (e) {}
+ if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
+ if ('value' in Attributes) O[P] = Attributes.value;
+ return O;
+};
+
+/***/ }),
+/* 12 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+module.exports = function (it) {
+ if (!isObject(it)) throw TypeError(it + ' is not an object!');
+ return it;
+};
+
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+module.exports = function (it) {
+ return _typeof(it) === 'object' ? it !== null : typeof it === 'function';
+};
+
+/***/ }),
+/* 14 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = !__w_pdfjs_require__(15) && !__w_pdfjs_require__(16)(function () {
+ return Object.defineProperty(__w_pdfjs_require__(17)('div'), 'a', {
+ get: function get() {
+ return 7;
+ }
+ }).a != 7;
+});
+
+/***/ }),
+/* 15 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = !__w_pdfjs_require__(16)(function () {
+ return Object.defineProperty({}, 'a', {
+ get: function get() {
+ return 7;
+ }
+ }).a != 7;
+});
+
+/***/ }),
+/* 16 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (exec) {
+ try {
+ return !!exec();
+ } catch (e) {
+ return true;
+ }
+};
+
+/***/ }),
+/* 17 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var document = __w_pdfjs_require__(8).document;
+
+var is = isObject(document) && isObject(document.createElement);
+
+module.exports = function (it) {
+ return is ? document.createElement(it) : {};
+};
+
+/***/ }),
+/* 18 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+module.exports = function (it, S) {
+ if (!isObject(it)) return it;
+ var fn, val;
+ if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
+ if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
+ if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
+ throw TypeError("Can't convert object to primitive value");
+};
+
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (bitmap, value) {
+ return {
+ enumerable: !(bitmap & 1),
+ configurable: !(bitmap & 2),
+ writable: !(bitmap & 4),
+ value: value
+ };
+};
+
+/***/ }),
+/* 20 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var hide = __w_pdfjs_require__(10);
+
+var has = __w_pdfjs_require__(21);
+
+var SRC = __w_pdfjs_require__(22)('src');
+
+var $toString = __w_pdfjs_require__(23);
+
+var TO_STRING = 'toString';
+var TPL = ('' + $toString).split(TO_STRING);
+
+__w_pdfjs_require__(9).inspectSource = function (it) {
+ return $toString.call(it);
+};
+
+(module.exports = function (O, key, val, safe) {
+ var isFunction = typeof val == 'function';
+ if (isFunction) has(val, 'name') || hide(val, 'name', key);
+ if (O[key] === val) return;
+ if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
+
+ if (O === global) {
+ O[key] = val;
+ } else if (!safe) {
+ delete O[key];
+ hide(O, key, val);
+ } else if (O[key]) {
+ O[key] = val;
+ } else {
+ hide(O, key, val);
+ }
+})(Function.prototype, TO_STRING, function toString() {
+ return typeof this == 'function' && this[SRC] || $toString.call(this);
+});
+
+/***/ }),
+/* 21 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var hasOwnProperty = {}.hasOwnProperty;
+
+module.exports = function (it, key) {
+ return hasOwnProperty.call(it, key);
+};
+
+/***/ }),
+/* 22 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var id = 0;
+var px = Math.random();
+
+module.exports = function (key) {
+ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
+};
+
+/***/ }),
+/* 23 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = __w_pdfjs_require__(24)('native-function-to-string', Function.toString);
+
+/***/ }),
+/* 24 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var core = __w_pdfjs_require__(9);
+
+var global = __w_pdfjs_require__(8);
+
+var SHARED = '__core-js_shared__';
+var store = global[SHARED] || (global[SHARED] = {});
+(module.exports = function (key, value) {
+ return store[key] || (store[key] = value !== undefined ? value : {});
+})('versions', []).push({
+ version: core.version,
+ mode: __w_pdfjs_require__(25) ? 'pure' : 'global',
+ copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
+});
+
+/***/ }),
+/* 25 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = false;
+
+/***/ }),
+/* 26 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var aFunction = __w_pdfjs_require__(27);
+
+module.exports = function (fn, that, length) {
+ aFunction(fn);
+ if (that === undefined) return fn;
+
+ switch (length) {
+ case 1:
+ return function (a) {
+ return fn.call(that, a);
+ };
+
+ case 2:
+ return function (a, b) {
+ return fn.call(that, a, b);
+ };
+
+ case 3:
+ return function (a, b, c) {
+ return fn.call(that, a, b, c);
+ };
+ }
+
+ return function () {
+ return fn.apply(that, arguments);
+ };
+};
+
+/***/ }),
+/* 27 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (it) {
+ if (typeof it != 'function') throw TypeError(it + ' is not a function!');
+ return it;
+};
+
+/***/ }),
+/* 28 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toInteger = __w_pdfjs_require__(29);
+
+var min = Math.min;
+
+module.exports = function (it) {
+ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0;
+};
+
+/***/ }),
+/* 29 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ceil = Math.ceil;
+var floor = Math.floor;
+
+module.exports = function (it) {
+ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
+};
+
+/***/ }),
+/* 30 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isRegExp = __w_pdfjs_require__(31);
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function (that, searchString, NAME) {
+ if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
+ return String(defined(that));
+};
+
+/***/ }),
+/* 31 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var cof = __w_pdfjs_require__(32);
+
+var MATCH = __w_pdfjs_require__(33)('match');
+
+module.exports = function (it) {
+ var isRegExp;
+ return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
+};
+
+/***/ }),
+/* 32 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toString = {}.toString;
+
+module.exports = function (it) {
+ return toString.call(it).slice(8, -1);
+};
+
+/***/ }),
+/* 33 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var store = __w_pdfjs_require__(24)('wks');
+
+var uid = __w_pdfjs_require__(22);
+
+var _Symbol = __w_pdfjs_require__(8).Symbol;
+
+var USE_SYMBOL = typeof _Symbol == 'function';
+
+var $exports = module.exports = function (name) {
+ return store[name] || (store[name] = USE_SYMBOL && _Symbol[name] || (USE_SYMBOL ? _Symbol : uid)('Symbol.' + name));
+};
+
+$exports.store = store;
+
+/***/ }),
+/* 34 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (it) {
+ if (it == undefined) throw TypeError("Can't call method on " + it);
+ return it;
+};
+
+/***/ }),
+/* 35 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var MATCH = __w_pdfjs_require__(33)('match');
+
+module.exports = function (KEY) {
+ var re = /./;
+
+ try {
+ '/./'[KEY](re);
+ } catch (e) {
+ try {
+ re[MATCH] = false;
+ return !'/./'[KEY](re);
+ } catch (f) {}
+ }
+
+ return true;
+};
+
+/***/ }),
+/* 36 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(37);
+
+module.exports = __w_pdfjs_require__(9).String.endsWith;
+
+/***/ }),
+/* 37 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var toLength = __w_pdfjs_require__(28);
+
+var context = __w_pdfjs_require__(30);
+
+var ENDS_WITH = 'endsWith';
+var $endsWith = ''[ENDS_WITH];
+$export($export.P + $export.F * __w_pdfjs_require__(35)(ENDS_WITH), 'String', {
+ endsWith: function endsWith(searchString) {
+ var that = context(this, searchString, ENDS_WITH);
+ var endPosition = arguments.length > 1 ? arguments[1] : undefined;
+ var len = toLength(that.length);
+ var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
+ var search = String(searchString);
+ return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search;
+ }
+});
+
+/***/ }),
+/* 38 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(39);
+
+module.exports = __w_pdfjs_require__(9).String.includes;
+
+/***/ }),
+/* 39 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var context = __w_pdfjs_require__(30);
+
+var INCLUDES = 'includes';
+$export($export.P + $export.F * __w_pdfjs_require__(35)(INCLUDES), 'String', {
+ includes: function includes(searchString) {
+ return !!~context(this, searchString, INCLUDES).indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
+ }
+});
+
+/***/ }),
+/* 40 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(41);
+
+module.exports = __w_pdfjs_require__(9).Array.includes;
+
+/***/ }),
+/* 41 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var $includes = __w_pdfjs_require__(42)(true);
+
+$export($export.P, 'Array', {
+ includes: function includes(el) {
+ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
+ }
+});
+
+__w_pdfjs_require__(46)('includes');
+
+/***/ }),
+/* 42 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toIObject = __w_pdfjs_require__(43);
+
+var toLength = __w_pdfjs_require__(28);
+
+var toAbsoluteIndex = __w_pdfjs_require__(45);
+
+module.exports = function (IS_INCLUDES) {
+ return function ($this, el, fromIndex) {
+ var O = toIObject($this);
+ var length = toLength(O.length);
+ var index = toAbsoluteIndex(fromIndex, length);
+ var value;
+ if (IS_INCLUDES && el != el) while (length > index) {
+ value = O[index++];
+ if (value != value) return true;
+ } else for (; length > index; index++) {
+ if (IS_INCLUDES || index in O) {
+ if (O[index] === el) return IS_INCLUDES || index || 0;
+ }
+ }
+ return !IS_INCLUDES && -1;
+ };
+};
+
+/***/ }),
+/* 43 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var IObject = __w_pdfjs_require__(44);
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function (it) {
+ return IObject(defined(it));
+};
+
+/***/ }),
+/* 44 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var cof = __w_pdfjs_require__(32);
+
+module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
+ return cof(it) == 'String' ? it.split('') : Object(it);
+};
+
+/***/ }),
+/* 45 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toInteger = __w_pdfjs_require__(29);
+
+var max = Math.max;
+var min = Math.min;
+
+module.exports = function (index, length) {
+ index = toInteger(index);
+ return index < 0 ? max(index + length, 0) : min(index, length);
+};
+
+/***/ }),
+/* 46 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var UNSCOPABLES = __w_pdfjs_require__(33)('unscopables');
+
+var ArrayProto = Array.prototype;
+if (ArrayProto[UNSCOPABLES] == undefined) __w_pdfjs_require__(10)(ArrayProto, UNSCOPABLES, {});
+
+module.exports = function (key) {
+ ArrayProto[UNSCOPABLES][key] = true;
+};
+
+/***/ }),
+/* 47 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(48);
+
+__w_pdfjs_require__(63);
+
+module.exports = __w_pdfjs_require__(9).Array.from;
+
+/***/ }),
+/* 48 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $at = __w_pdfjs_require__(49)(true);
+
+__w_pdfjs_require__(50)(String, 'String', function (iterated) {
+ this._t = String(iterated);
+ this._i = 0;
+}, function () {
+ var O = this._t;
+ var index = this._i;
+ var point;
+ if (index >= O.length) return {
+ value: undefined,
+ done: true
+ };
+ point = $at(O, index);
+ this._i += point.length;
+ return {
+ value: point,
+ done: false
+ };
+});
+
+/***/ }),
+/* 49 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toInteger = __w_pdfjs_require__(29);
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function (TO_STRING) {
+ return function (that, pos) {
+ var s = String(defined(that));
+ var i = toInteger(pos);
+ var l = s.length;
+ var a, b;
+ if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
+ a = s.charCodeAt(i);
+ return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
+ };
+};
+
+/***/ }),
+/* 50 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var LIBRARY = __w_pdfjs_require__(25);
+
+var $export = __w_pdfjs_require__(7);
+
+var redefine = __w_pdfjs_require__(20);
+
+var hide = __w_pdfjs_require__(10);
+
+var Iterators = __w_pdfjs_require__(51);
+
+var $iterCreate = __w_pdfjs_require__(52);
+
+var setToStringTag = __w_pdfjs_require__(60);
+
+var getPrototypeOf = __w_pdfjs_require__(61);
+
+var ITERATOR = __w_pdfjs_require__(33)('iterator');
+
+var BUGGY = !([].keys && 'next' in [].keys());
+var FF_ITERATOR = '@@iterator';
+var KEYS = 'keys';
+var VALUES = 'values';
+
+var returnThis = function returnThis() {
+ return this;
+};
+
+module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
+ $iterCreate(Constructor, NAME, next);
+
+ var getMethod = function getMethod(kind) {
+ if (!BUGGY && kind in proto) return proto[kind];
+
+ switch (kind) {
+ case KEYS:
+ return function keys() {
+ return new Constructor(this, kind);
+ };
+
+ case VALUES:
+ return function values() {
+ return new Constructor(this, kind);
+ };
+ }
+
+ return function entries() {
+ return new Constructor(this, kind);
+ };
+ };
+
+ var TAG = NAME + ' Iterator';
+ var DEF_VALUES = DEFAULT == VALUES;
+ var VALUES_BUG = false;
+ var proto = Base.prototype;
+ var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
+ var $default = $native || getMethod(DEFAULT);
+ var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
+ var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
+ var methods, key, IteratorPrototype;
+
+ if ($anyNative) {
+ IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
+
+ if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
+ setToStringTag(IteratorPrototype, TAG, true);
+ if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
+ }
+ }
+
+ if (DEF_VALUES && $native && $native.name !== VALUES) {
+ VALUES_BUG = true;
+
+ $default = function values() {
+ return $native.call(this);
+ };
+ }
+
+ if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
+ hide(proto, ITERATOR, $default);
+ }
+
+ Iterators[NAME] = $default;
+ Iterators[TAG] = returnThis;
+
+ if (DEFAULT) {
+ methods = {
+ values: DEF_VALUES ? $default : getMethod(VALUES),
+ keys: IS_SET ? $default : getMethod(KEYS),
+ entries: $entries
+ };
+ if (FORCED) for (key in methods) {
+ if (!(key in proto)) redefine(proto, key, methods[key]);
+ } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
+ }
+
+ return methods;
+};
+
+/***/ }),
+/* 51 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = {};
+
+/***/ }),
+/* 52 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var create = __w_pdfjs_require__(53);
+
+var descriptor = __w_pdfjs_require__(19);
+
+var setToStringTag = __w_pdfjs_require__(60);
+
+var IteratorPrototype = {};
+
+__w_pdfjs_require__(10)(IteratorPrototype, __w_pdfjs_require__(33)('iterator'), function () {
+ return this;
+});
+
+module.exports = function (Constructor, NAME, next) {
+ Constructor.prototype = create(IteratorPrototype, {
+ next: descriptor(1, next)
+ });
+ setToStringTag(Constructor, NAME + ' Iterator');
+};
+
+/***/ }),
+/* 53 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var anObject = __w_pdfjs_require__(12);
+
+var dPs = __w_pdfjs_require__(54);
+
+var enumBugKeys = __w_pdfjs_require__(58);
+
+var IE_PROTO = __w_pdfjs_require__(57)('IE_PROTO');
+
+var Empty = function Empty() {};
+
+var PROTOTYPE = 'prototype';
+
+var _createDict = function createDict() {
+ var iframe = __w_pdfjs_require__(17)('iframe');
+
+ var i = enumBugKeys.length;
+ var lt = '<';
+ var gt = '>';
+ var iframeDocument;
+ iframe.style.display = 'none';
+
+ __w_pdfjs_require__(59).appendChild(iframe);
+
+ iframe.src = 'javascript:';
+ iframeDocument = iframe.contentWindow.document;
+ iframeDocument.open();
+ iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
+ iframeDocument.close();
+ _createDict = iframeDocument.F;
+
+ while (i--) {
+ delete _createDict[PROTOTYPE][enumBugKeys[i]];
+ }
+
+ return _createDict();
+};
+
+module.exports = Object.create || function create(O, Properties) {
+ var result;
+
+ if (O !== null) {
+ Empty[PROTOTYPE] = anObject(O);
+ result = new Empty();
+ Empty[PROTOTYPE] = null;
+ result[IE_PROTO] = O;
+ } else result = _createDict();
+
+ return Properties === undefined ? result : dPs(result, Properties);
+};
+
+/***/ }),
+/* 54 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var dP = __w_pdfjs_require__(11);
+
+var anObject = __w_pdfjs_require__(12);
+
+var getKeys = __w_pdfjs_require__(55);
+
+module.exports = __w_pdfjs_require__(15) ? Object.defineProperties : function defineProperties(O, Properties) {
+ anObject(O);
+ var keys = getKeys(Properties);
+ var length = keys.length;
+ var i = 0;
+ var P;
+
+ while (length > i) {
+ dP.f(O, P = keys[i++], Properties[P]);
+ }
+
+ return O;
+};
+
+/***/ }),
+/* 55 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $keys = __w_pdfjs_require__(56);
+
+var enumBugKeys = __w_pdfjs_require__(58);
+
+module.exports = Object.keys || function keys(O) {
+ return $keys(O, enumBugKeys);
+};
+
+/***/ }),
+/* 56 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var has = __w_pdfjs_require__(21);
+
+var toIObject = __w_pdfjs_require__(43);
+
+var arrayIndexOf = __w_pdfjs_require__(42)(false);
+
+var IE_PROTO = __w_pdfjs_require__(57)('IE_PROTO');
+
+module.exports = function (object, names) {
+ var O = toIObject(object);
+ var i = 0;
+ var result = [];
+ var key;
+
+ for (key in O) {
+ if (key != IE_PROTO) has(O, key) && result.push(key);
+ }
+
+ while (names.length > i) {
+ if (has(O, key = names[i++])) {
+ ~arrayIndexOf(result, key) || result.push(key);
+ }
+ }
+
+ return result;
+};
+
+/***/ }),
+/* 57 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var shared = __w_pdfjs_require__(24)('keys');
+
+var uid = __w_pdfjs_require__(22);
+
+module.exports = function (key) {
+ return shared[key] || (shared[key] = uid(key));
+};
+
+/***/ }),
+/* 58 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'.split(',');
+
+/***/ }),
+/* 59 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var document = __w_pdfjs_require__(8).document;
+
+module.exports = document && document.documentElement;
+
+/***/ }),
+/* 60 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var def = __w_pdfjs_require__(11).f;
+
+var has = __w_pdfjs_require__(21);
+
+var TAG = __w_pdfjs_require__(33)('toStringTag');
+
+module.exports = function (it, tag, stat) {
+ if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, {
+ configurable: true,
+ value: tag
+ });
+};
+
+/***/ }),
+/* 61 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var has = __w_pdfjs_require__(21);
+
+var toObject = __w_pdfjs_require__(62);
+
+var IE_PROTO = __w_pdfjs_require__(57)('IE_PROTO');
+
+var ObjectProto = Object.prototype;
+
+module.exports = Object.getPrototypeOf || function (O) {
+ O = toObject(O);
+ if (has(O, IE_PROTO)) return O[IE_PROTO];
+
+ if (typeof O.constructor == 'function' && O instanceof O.constructor) {
+ return O.constructor.prototype;
+ }
+
+ return O instanceof Object ? ObjectProto : null;
+};
+
+/***/ }),
+/* 62 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function (it) {
+ return Object(defined(it));
+};
+
+/***/ }),
+/* 63 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ctx = __w_pdfjs_require__(26);
+
+var $export = __w_pdfjs_require__(7);
+
+var toObject = __w_pdfjs_require__(62);
+
+var call = __w_pdfjs_require__(64);
+
+var isArrayIter = __w_pdfjs_require__(65);
+
+var toLength = __w_pdfjs_require__(28);
+
+var createProperty = __w_pdfjs_require__(66);
+
+var getIterFn = __w_pdfjs_require__(67);
+
+$export($export.S + $export.F * !__w_pdfjs_require__(69)(function (iter) {
+ Array.from(iter);
+}), 'Array', {
+ from: function from(arrayLike) {
+ var O = toObject(arrayLike);
+ var C = typeof this == 'function' ? this : Array;
+ var aLen = arguments.length;
+ var mapfn = aLen > 1 ? arguments[1] : undefined;
+ var mapping = mapfn !== undefined;
+ var index = 0;
+ var iterFn = getIterFn(O);
+ var length, result, step, iterator;
+ if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
+
+ if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
+ for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
+ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
+ }
+ } else {
+ length = toLength(O.length);
+
+ for (result = new C(length); length > index; index++) {
+ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
+ }
+ }
+
+ result.length = index;
+ return result;
+ }
+});
+
+/***/ }),
+/* 64 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var anObject = __w_pdfjs_require__(12);
+
+module.exports = function (iterator, fn, value, entries) {
+ try {
+ return entries ? fn(anObject(value)[0], value[1]) : fn(value);
+ } catch (e) {
+ var ret = iterator['return'];
+ if (ret !== undefined) anObject(ret.call(iterator));
+ throw e;
+ }
+};
+
+/***/ }),
+/* 65 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var Iterators = __w_pdfjs_require__(51);
+
+var ITERATOR = __w_pdfjs_require__(33)('iterator');
+
+var ArrayProto = Array.prototype;
+
+module.exports = function (it) {
+ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
+};
+
+/***/ }),
+/* 66 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $defineProperty = __w_pdfjs_require__(11);
+
+var createDesc = __w_pdfjs_require__(19);
+
+module.exports = function (object, index, value) {
+ if (index in object) $defineProperty.f(object, index, createDesc(0, value));else object[index] = value;
+};
+
+/***/ }),
+/* 67 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var classof = __w_pdfjs_require__(68);
+
+var ITERATOR = __w_pdfjs_require__(33)('iterator');
+
+var Iterators = __w_pdfjs_require__(51);
+
+module.exports = __w_pdfjs_require__(9).getIteratorMethod = function (it) {
+ if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)];
+};
+
+/***/ }),
+/* 68 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var cof = __w_pdfjs_require__(32);
+
+var TAG = __w_pdfjs_require__(33)('toStringTag');
+
+var ARG = cof(function () {
+ return arguments;
+}()) == 'Arguments';
+
+var tryGet = function tryGet(it, key) {
+ try {
+ return it[key];
+ } catch (e) {}
+};
+
+module.exports = function (it) {
+ var O, T, B;
+ return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
+};
+
+/***/ }),
+/* 69 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ITERATOR = __w_pdfjs_require__(33)('iterator');
+
+var SAFE_CLOSING = false;
+
+try {
+ var riter = [7][ITERATOR]();
+
+ riter['return'] = function () {
+ SAFE_CLOSING = true;
+ };
+
+ Array.from(riter, function () {
+ throw 2;
+ });
+} catch (e) {}
+
+module.exports = function (exec, skipClosing) {
+ if (!skipClosing && !SAFE_CLOSING) return false;
+ var safe = false;
+
+ try {
+ var arr = [7];
+ var iter = arr[ITERATOR]();
+
+ iter.next = function () {
+ return {
+ done: safe = true
+ };
+ };
+
+ arr[ITERATOR] = function () {
+ return iter;
+ };
+
+ exec(arr);
+ } catch (e) {}
+
+ return safe;
+};
+
+/***/ }),
+/* 70 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(71);
+
+module.exports = __w_pdfjs_require__(9).Object.assign;
+
+/***/ }),
+/* 71 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+$export($export.S + $export.F, 'Object', {
+ assign: __w_pdfjs_require__(72)
+});
+
+/***/ }),
+/* 72 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var DESCRIPTORS = __w_pdfjs_require__(15);
+
+var getKeys = __w_pdfjs_require__(55);
+
+var gOPS = __w_pdfjs_require__(73);
+
+var pIE = __w_pdfjs_require__(74);
+
+var toObject = __w_pdfjs_require__(62);
+
+var IObject = __w_pdfjs_require__(44);
+
+var $assign = Object.assign;
+module.exports = !$assign || __w_pdfjs_require__(16)(function () {
+ var A = {};
+ var B = {};
+ var S = Symbol();
+ var K = 'abcdefghijklmnopqrst';
+ A[S] = 7;
+ K.split('').forEach(function (k) {
+ B[k] = k;
+ });
+ return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
+}) ? function assign(target, source) {
+ var T = toObject(target);
+ var aLen = arguments.length;
+ var index = 1;
+ var getSymbols = gOPS.f;
+ var isEnum = pIE.f;
+
+ while (aLen > index) {
+ var S = IObject(arguments[index++]);
+ var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
+ var length = keys.length;
+ var j = 0;
+ var key;
+
+ while (length > j) {
+ key = keys[j++];
+ if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
+ }
+ }
+
+ return T;
+} : $assign;
+
+/***/ }),
+/* 73 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+exports.f = Object.getOwnPropertySymbols;
+
+/***/ }),
+/* 74 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+exports.f = {}.propertyIsEnumerable;
+
+/***/ }),
+/* 75 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(76);
+
+module.exports = __w_pdfjs_require__(9).Math.log2;
+
+/***/ }),
+/* 76 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+$export($export.S, 'Math', {
+ log2: function log2(x) {
+ return Math.log(x) / Math.LN2;
+ }
+});
+
+/***/ }),
+/* 77 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(78);
+
+module.exports = __w_pdfjs_require__(9).Number.isNaN;
+
+/***/ }),
+/* 78 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+$export($export.S, 'Number', {
+ isNaN: function isNaN(number) {
+ return number != number;
+ }
+});
+
+/***/ }),
+/* 79 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(80);
+
+module.exports = __w_pdfjs_require__(9).Number.isInteger;
+
+/***/ }),
+/* 80 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+$export($export.S, 'Number', {
+ isInteger: __w_pdfjs_require__(81)
+});
+
+/***/ }),
+/* 81 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var floor = Math.floor;
+
+module.exports = function isInteger(it) {
+ return !isObject(it) && isFinite(it) && floor(it) === it;
+};
+
+/***/ }),
+/* 82 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(83);
+
+__w_pdfjs_require__(48);
+
+__w_pdfjs_require__(84);
+
+__w_pdfjs_require__(87);
+
+__w_pdfjs_require__(100);
+
+__w_pdfjs_require__(101);
+
+module.exports = __w_pdfjs_require__(9).Promise;
+
+/***/ }),
+/* 83 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var classof = __w_pdfjs_require__(68);
+
+var test = {};
+test[__w_pdfjs_require__(33)('toStringTag')] = 'z';
+
+if (test + '' != '[object z]') {
+ __w_pdfjs_require__(20)(Object.prototype, 'toString', function toString() {
+ return '[object ' + classof(this) + ']';
+ }, true);
+}
+
+/***/ }),
+/* 84 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $iterators = __w_pdfjs_require__(85);
+
+var getKeys = __w_pdfjs_require__(55);
+
+var redefine = __w_pdfjs_require__(20);
+
+var global = __w_pdfjs_require__(8);
+
+var hide = __w_pdfjs_require__(10);
+
+var Iterators = __w_pdfjs_require__(51);
+
+var wks = __w_pdfjs_require__(33);
+
+var ITERATOR = wks('iterator');
+var TO_STRING_TAG = wks('toStringTag');
+var ArrayValues = Iterators.Array;
+var DOMIterables = {
+ CSSRuleList: true,
+ CSSStyleDeclaration: false,
+ CSSValueList: false,
+ ClientRectList: false,
+ DOMRectList: false,
+ DOMStringList: false,
+ DOMTokenList: true,
+ DataTransferItemList: false,
+ FileList: false,
+ HTMLAllCollection: false,
+ HTMLCollection: false,
+ HTMLFormElement: false,
+ HTMLSelectElement: false,
+ MediaList: true,
+ MimeTypeArray: false,
+ NamedNodeMap: false,
+ NodeList: true,
+ PaintRequestList: false,
+ Plugin: false,
+ PluginArray: false,
+ SVGLengthList: false,
+ SVGNumberList: false,
+ SVGPathSegList: false,
+ SVGPointList: false,
+ SVGStringList: false,
+ SVGTransformList: false,
+ SourceBufferList: false,
+ StyleSheetList: true,
+ TextTrackCueList: false,
+ TextTrackList: false,
+ TouchList: false
+};
+
+for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
+ var NAME = collections[i];
+ var explicit = DOMIterables[NAME];
+ var Collection = global[NAME];
+ var proto = Collection && Collection.prototype;
+ var key;
+
+ if (proto) {
+ if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
+ if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
+ Iterators[NAME] = ArrayValues;
+ if (explicit) for (key in $iterators) {
+ if (!proto[key]) redefine(proto, key, $iterators[key], true);
+ }
+ }
+}
+
+/***/ }),
+/* 85 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var addToUnscopables = __w_pdfjs_require__(46);
+
+var step = __w_pdfjs_require__(86);
+
+var Iterators = __w_pdfjs_require__(51);
+
+var toIObject = __w_pdfjs_require__(43);
+
+module.exports = __w_pdfjs_require__(50)(Array, 'Array', function (iterated, kind) {
+ this._t = toIObject(iterated);
+ this._i = 0;
+ this._k = kind;
+}, function () {
+ var O = this._t;
+ var kind = this._k;
+ var index = this._i++;
+
+ if (!O || index >= O.length) {
+ this._t = undefined;
+ return step(1);
+ }
+
+ if (kind == 'keys') return step(0, index);
+ if (kind == 'values') return step(0, O[index]);
+ return step(0, [index, O[index]]);
+}, 'values');
+Iterators.Arguments = Iterators.Array;
+addToUnscopables('keys');
+addToUnscopables('values');
+addToUnscopables('entries');
+
+/***/ }),
+/* 86 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (done, value) {
+ return {
+ value: value,
+ done: !!done
+ };
+};
+
+/***/ }),
+/* 87 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var LIBRARY = __w_pdfjs_require__(25);
+
+var global = __w_pdfjs_require__(8);
+
+var ctx = __w_pdfjs_require__(26);
+
+var classof = __w_pdfjs_require__(68);
+
+var $export = __w_pdfjs_require__(7);
+
+var isObject = __w_pdfjs_require__(13);
+
+var aFunction = __w_pdfjs_require__(27);
+
+var anInstance = __w_pdfjs_require__(88);
+
+var forOf = __w_pdfjs_require__(89);
+
+var speciesConstructor = __w_pdfjs_require__(90);
+
+var task = __w_pdfjs_require__(91).set;
+
+var microtask = __w_pdfjs_require__(93)();
+
+var newPromiseCapabilityModule = __w_pdfjs_require__(94);
+
+var perform = __w_pdfjs_require__(95);
+
+var userAgent = __w_pdfjs_require__(96);
+
+var promiseResolve = __w_pdfjs_require__(97);
+
+var PROMISE = 'Promise';
+var TypeError = global.TypeError;
+var process = global.process;
+var versions = process && process.versions;
+var v8 = versions && versions.v8 || '';
+var $Promise = global[PROMISE];
+var isNode = classof(process) == 'process';
+
+var empty = function empty() {};
+
+var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
+var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
+var USE_NATIVE = !!function () {
+ try {
+ var promise = $Promise.resolve(1);
+
+ var FakePromise = (promise.constructor = {})[__w_pdfjs_require__(33)('species')] = function (exec) {
+ exec(empty, empty);
+ };
+
+ return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise && v8.indexOf('6.6') !== 0 && userAgent.indexOf('Chrome/66') === -1;
+ } catch (e) {}
+}();
+
+var isThenable = function isThenable(it) {
+ var then;
+ return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
+};
+
+var notify = function notify(promise, isReject) {
+ if (promise._n) return;
+ promise._n = true;
+ var chain = promise._c;
+ microtask(function () {
+ var value = promise._v;
+ var ok = promise._s == 1;
+ var i = 0;
+
+ var run = function run(reaction) {
+ var handler = ok ? reaction.ok : reaction.fail;
+ var resolve = reaction.resolve;
+ var reject = reaction.reject;
+ var domain = reaction.domain;
+ var result, then, exited;
+
+ try {
+ if (handler) {
+ if (!ok) {
+ if (promise._h == 2) onHandleUnhandled(promise);
+ promise._h = 1;
+ }
+
+ if (handler === true) result = value;else {
+ if (domain) domain.enter();
+ result = handler(value);
+
+ if (domain) {
+ domain.exit();
+ exited = true;
+ }
+ }
+
+ if (result === reaction.promise) {
+ reject(TypeError('Promise-chain cycle'));
+ } else if (then = isThenable(result)) {
+ then.call(result, resolve, reject);
+ } else resolve(result);
+ } else reject(value);
+ } catch (e) {
+ if (domain && !exited) domain.exit();
+ reject(e);
+ }
+ };
+
+ while (chain.length > i) {
+ run(chain[i++]);
+ }
+
+ promise._c = [];
+ promise._n = false;
+ if (isReject && !promise._h) onUnhandled(promise);
+ });
+};
+
+var onUnhandled = function onUnhandled(promise) {
+ task.call(global, function () {
+ var value = promise._v;
+ var unhandled = isUnhandled(promise);
+ var result, handler, console;
+
+ if (unhandled) {
+ result = perform(function () {
+ if (isNode) {
+ process.emit('unhandledRejection', value, promise);
+ } else if (handler = global.onunhandledrejection) {
+ handler({
+ promise: promise,
+ reason: value
+ });
+ } else if ((console = global.console) && console.error) {
+ console.error('Unhandled promise rejection', value);
+ }
+ });
+ promise._h = isNode || isUnhandled(promise) ? 2 : 1;
+ }
+
+ promise._a = undefined;
+ if (unhandled && result.e) throw result.v;
+ });
+};
+
+var isUnhandled = function isUnhandled(promise) {
+ return promise._h !== 1 && (promise._a || promise._c).length === 0;
+};
+
+var onHandleUnhandled = function onHandleUnhandled(promise) {
+ task.call(global, function () {
+ var handler;
+
+ if (isNode) {
+ process.emit('rejectionHandled', promise);
+ } else if (handler = global.onrejectionhandled) {
+ handler({
+ promise: promise,
+ reason: promise._v
+ });
+ }
+ });
+};
+
+var $reject = function $reject(value) {
+ var promise = this;
+ if (promise._d) return;
+ promise._d = true;
+ promise = promise._w || promise;
+ promise._v = value;
+ promise._s = 2;
+ if (!promise._a) promise._a = promise._c.slice();
+ notify(promise, true);
+};
+
+var $resolve = function $resolve(value) {
+ var promise = this;
+ var then;
+ if (promise._d) return;
+ promise._d = true;
+ promise = promise._w || promise;
+
+ try {
+ if (promise === value) throw TypeError("Promise can't be resolved itself");
+
+ if (then = isThenable(value)) {
+ microtask(function () {
+ var wrapper = {
+ _w: promise,
+ _d: false
+ };
+
+ try {
+ then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
+ } catch (e) {
+ $reject.call(wrapper, e);
+ }
+ });
+ } else {
+ promise._v = value;
+ promise._s = 1;
+ notify(promise, false);
+ }
+ } catch (e) {
+ $reject.call({
+ _w: promise,
+ _d: false
+ }, e);
+ }
+};
+
+if (!USE_NATIVE) {
+ $Promise = function Promise(executor) {
+ anInstance(this, $Promise, PROMISE, '_h');
+ aFunction(executor);
+ Internal.call(this);
+
+ try {
+ executor(ctx($resolve, this, 1), ctx($reject, this, 1));
+ } catch (err) {
+ $reject.call(this, err);
+ }
+ };
+
+ Internal = function Promise(executor) {
+ this._c = [];
+ this._a = undefined;
+ this._s = 0;
+ this._d = false;
+ this._v = undefined;
+ this._h = 0;
+ this._n = false;
+ };
+
+ Internal.prototype = __w_pdfjs_require__(98)($Promise.prototype, {
+ then: function then(onFulfilled, onRejected) {
+ var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
+ reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
+ reaction.fail = typeof onRejected == 'function' && onRejected;
+ reaction.domain = isNode ? process.domain : undefined;
+
+ this._c.push(reaction);
+
+ if (this._a) this._a.push(reaction);
+ if (this._s) notify(this, false);
+ return reaction.promise;
+ },
+ 'catch': function _catch(onRejected) {
+ return this.then(undefined, onRejected);
+ }
+ });
+
+ OwnPromiseCapability = function OwnPromiseCapability() {
+ var promise = new Internal();
+ this.promise = promise;
+ this.resolve = ctx($resolve, promise, 1);
+ this.reject = ctx($reject, promise, 1);
+ };
+
+ newPromiseCapabilityModule.f = newPromiseCapability = function newPromiseCapability(C) {
+ return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C);
+ };
+}
+
+$export($export.G + $export.W + $export.F * !USE_NATIVE, {
+ Promise: $Promise
+});
+
+__w_pdfjs_require__(60)($Promise, PROMISE);
+
+__w_pdfjs_require__(99)(PROMISE);
+
+Wrapper = __w_pdfjs_require__(9)[PROMISE];
+$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
+ reject: function reject(r) {
+ var capability = newPromiseCapability(this);
+ var $$reject = capability.reject;
+ $$reject(r);
+ return capability.promise;
+ }
+});
+$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
+ resolve: function resolve(x) {
+ return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
+ }
+});
+$export($export.S + $export.F * !(USE_NATIVE && __w_pdfjs_require__(69)(function (iter) {
+ $Promise.all(iter)['catch'](empty);
+})), PROMISE, {
+ all: function all(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var resolve = capability.resolve;
+ var reject = capability.reject;
+ var result = perform(function () {
+ var values = [];
+ var index = 0;
+ var remaining = 1;
+ forOf(iterable, false, function (promise) {
+ var $index = index++;
+ var alreadyCalled = false;
+ values.push(undefined);
+ remaining++;
+ C.resolve(promise).then(function (value) {
+ if (alreadyCalled) return;
+ alreadyCalled = true;
+ values[$index] = value;
+ --remaining || resolve(values);
+ }, reject);
+ });
+ --remaining || resolve(values);
+ });
+ if (result.e) reject(result.v);
+ return capability.promise;
+ },
+ race: function race(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var reject = capability.reject;
+ var result = perform(function () {
+ forOf(iterable, false, function (promise) {
+ C.resolve(promise).then(capability.resolve, reject);
+ });
+ });
+ if (result.e) reject(result.v);
+ return capability.promise;
+ }
+});
+
+/***/ }),
+/* 88 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (it, Constructor, name, forbiddenField) {
+ if (!(it instanceof Constructor) || forbiddenField !== undefined && forbiddenField in it) {
+ throw TypeError(name + ': incorrect invocation!');
+ }
+
+ return it;
+};
+
+/***/ }),
+/* 89 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ctx = __w_pdfjs_require__(26);
+
+var call = __w_pdfjs_require__(64);
+
+var isArrayIter = __w_pdfjs_require__(65);
+
+var anObject = __w_pdfjs_require__(12);
+
+var toLength = __w_pdfjs_require__(28);
+
+var getIterFn = __w_pdfjs_require__(67);
+
+var BREAK = {};
+var RETURN = {};
+
+var _exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
+ var iterFn = ITERATOR ? function () {
+ return iterable;
+ } : getIterFn(iterable);
+ var f = ctx(fn, that, entries ? 2 : 1);
+ var index = 0;
+ var length, step, iterator, result;
+ if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
+ if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
+ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
+ if (result === BREAK || result === RETURN) return result;
+ } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
+ result = call(iterator, f, step.value, entries);
+ if (result === BREAK || result === RETURN) return result;
+ }
+};
+
+_exports.BREAK = BREAK;
+_exports.RETURN = RETURN;
+
+/***/ }),
+/* 90 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var anObject = __w_pdfjs_require__(12);
+
+var aFunction = __w_pdfjs_require__(27);
+
+var SPECIES = __w_pdfjs_require__(33)('species');
+
+module.exports = function (O, D) {
+ var C = anObject(O).constructor;
+ var S;
+ return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
+};
+
+/***/ }),
+/* 91 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ctx = __w_pdfjs_require__(26);
+
+var invoke = __w_pdfjs_require__(92);
+
+var html = __w_pdfjs_require__(59);
+
+var cel = __w_pdfjs_require__(17);
+
+var global = __w_pdfjs_require__(8);
+
+var process = global.process;
+var setTask = global.setImmediate;
+var clearTask = global.clearImmediate;
+var MessageChannel = global.MessageChannel;
+var Dispatch = global.Dispatch;
+var counter = 0;
+var queue = {};
+var ONREADYSTATECHANGE = 'onreadystatechange';
+var defer, channel, port;
+
+var run = function run() {
+ var id = +this;
+
+ if (queue.hasOwnProperty(id)) {
+ var fn = queue[id];
+ delete queue[id];
+ fn();
+ }
+};
+
+var listener = function listener(event) {
+ run.call(event.data);
+};
+
+if (!setTask || !clearTask) {
+ setTask = function setImmediate(fn) {
+ var args = [];
+ var i = 1;
+
+ while (arguments.length > i) {
+ args.push(arguments[i++]);
+ }
+
+ queue[++counter] = function () {
+ invoke(typeof fn == 'function' ? fn : Function(fn), args);
+ };
+
+ defer(counter);
+ return counter;
+ };
+
+ clearTask = function clearImmediate(id) {
+ delete queue[id];
+ };
+
+ if (__w_pdfjs_require__(32)(process) == 'process') {
+ defer = function defer(id) {
+ process.nextTick(ctx(run, id, 1));
+ };
+ } else if (Dispatch && Dispatch.now) {
+ defer = function defer(id) {
+ Dispatch.now(ctx(run, id, 1));
+ };
+ } else if (MessageChannel) {
+ channel = new MessageChannel();
+ port = channel.port2;
+ channel.port1.onmessage = listener;
+ defer = ctx(port.postMessage, port, 1);
+ } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
+ defer = function defer(id) {
+ global.postMessage(id + '', '*');
+ };
+
+ global.addEventListener('message', listener, false);
+ } else if (ONREADYSTATECHANGE in cel('script')) {
+ defer = function defer(id) {
+ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
+ html.removeChild(this);
+ run.call(id);
+ };
+ };
+ } else {
+ defer = function defer(id) {
+ setTimeout(ctx(run, id, 1), 0);
+ };
+ }
+}
+
+module.exports = {
+ set: setTask,
+ clear: clearTask
+};
+
+/***/ }),
+/* 92 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (fn, args, that) {
+ var un = that === undefined;
+
+ switch (args.length) {
+ case 0:
+ return un ? fn() : fn.call(that);
+
+ case 1:
+ return un ? fn(args[0]) : fn.call(that, args[0]);
+
+ case 2:
+ return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]);
+
+ case 3:
+ return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]);
+
+ case 4:
+ return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]);
+ }
+
+ return fn.apply(that, args);
+};
+
+/***/ }),
+/* 93 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var macrotask = __w_pdfjs_require__(91).set;
+
+var Observer = global.MutationObserver || global.WebKitMutationObserver;
+var process = global.process;
+var Promise = global.Promise;
+var isNode = __w_pdfjs_require__(32)(process) == 'process';
+
+module.exports = function () {
+ var head, last, notify;
+
+ var flush = function flush() {
+ var parent, fn;
+ if (isNode && (parent = process.domain)) parent.exit();
+
+ while (head) {
+ fn = head.fn;
+ head = head.next;
+
+ try {
+ fn();
+ } catch (e) {
+ if (head) notify();else last = undefined;
+ throw e;
+ }
+ }
+
+ last = undefined;
+ if (parent) parent.enter();
+ };
+
+ if (isNode) {
+ notify = function notify() {
+ process.nextTick(flush);
+ };
+ } else if (Observer && !(global.navigator && global.navigator.standalone)) {
+ var toggle = true;
+ var node = document.createTextNode('');
+ new Observer(flush).observe(node, {
+ characterData: true
+ });
+
+ notify = function notify() {
+ node.data = toggle = !toggle;
+ };
+ } else if (Promise && Promise.resolve) {
+ var promise = Promise.resolve(undefined);
+
+ notify = function notify() {
+ promise.then(flush);
+ };
+ } else {
+ notify = function notify() {
+ macrotask.call(global, flush);
+ };
+ }
+
+ return function (fn) {
+ var task = {
+ fn: fn,
+ next: undefined
+ };
+ if (last) last.next = task;
+
+ if (!head) {
+ head = task;
+ notify();
+ }
+
+ last = task;
+ };
+};
+
+/***/ }),
+/* 94 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var aFunction = __w_pdfjs_require__(27);
+
+function PromiseCapability(C) {
+ var resolve, reject;
+ this.promise = new C(function ($$resolve, $$reject) {
+ if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
+ resolve = $$resolve;
+ reject = $$reject;
+ });
+ this.resolve = aFunction(resolve);
+ this.reject = aFunction(reject);
+}
+
+module.exports.f = function (C) {
+ return new PromiseCapability(C);
+};
+
+/***/ }),
+/* 95 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (exec) {
+ try {
+ return {
+ e: false,
+ v: exec()
+ };
+ } catch (e) {
+ return {
+ e: true,
+ v: e
+ };
+ }
+};
+
+/***/ }),
+/* 96 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var navigator = global.navigator;
+module.exports = navigator && navigator.userAgent || '';
+
+/***/ }),
+/* 97 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var anObject = __w_pdfjs_require__(12);
+
+var isObject = __w_pdfjs_require__(13);
+
+var newPromiseCapability = __w_pdfjs_require__(94);
+
+module.exports = function (C, x) {
+ anObject(C);
+ if (isObject(x) && x.constructor === C) return x;
+ var promiseCapability = newPromiseCapability.f(C);
+ var resolve = promiseCapability.resolve;
+ resolve(x);
+ return promiseCapability.promise;
+};
+
+/***/ }),
+/* 98 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var redefine = __w_pdfjs_require__(20);
+
+module.exports = function (target, src, safe) {
+ for (var key in src) {
+ redefine(target, key, src[key], safe);
+ }
+
+ return target;
+};
+
+/***/ }),
+/* 99 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var dP = __w_pdfjs_require__(11);
+
+var DESCRIPTORS = __w_pdfjs_require__(15);
+
+var SPECIES = __w_pdfjs_require__(33)('species');
+
+module.exports = function (KEY) {
+ var C = global[KEY];
+ if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
+ configurable: true,
+ get: function get() {
+ return this;
+ }
+ });
+};
+
+/***/ }),
+/* 100 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var core = __w_pdfjs_require__(9);
+
+var global = __w_pdfjs_require__(8);
+
+var speciesConstructor = __w_pdfjs_require__(90);
+
+var promiseResolve = __w_pdfjs_require__(97);
+
+$export($export.P + $export.R, 'Promise', {
+ 'finally': function _finally(onFinally) {
+ var C = speciesConstructor(this, core.Promise || global.Promise);
+ var isFunction = typeof onFinally == 'function';
+ return this.then(isFunction ? function (x) {
+ return promiseResolve(C, onFinally()).then(function () {
+ return x;
+ });
+ } : onFinally, isFunction ? function (e) {
+ return promiseResolve(C, onFinally()).then(function () {
+ throw e;
+ });
+ } : onFinally);
+ }
+});
+
+/***/ }),
+/* 101 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var newPromiseCapability = __w_pdfjs_require__(94);
+
+var perform = __w_pdfjs_require__(95);
+
+$export($export.S, 'Promise', {
+ 'try': function _try(callbackfn) {
+ var promiseCapability = newPromiseCapability.f(this);
+ var result = perform(callbackfn);
+ (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
+ return promiseCapability.promise;
+ }
+});
+
+/***/ }),
+/* 102 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(83);
+
+__w_pdfjs_require__(84);
+
+__w_pdfjs_require__(103);
+
+__w_pdfjs_require__(115);
+
+__w_pdfjs_require__(117);
+
+module.exports = __w_pdfjs_require__(9).WeakMap;
+
+/***/ }),
+/* 103 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var each = __w_pdfjs_require__(104)(0);
+
+var redefine = __w_pdfjs_require__(20);
+
+var meta = __w_pdfjs_require__(108);
+
+var assign = __w_pdfjs_require__(72);
+
+var weak = __w_pdfjs_require__(109);
+
+var isObject = __w_pdfjs_require__(13);
+
+var validate = __w_pdfjs_require__(110);
+
+var NATIVE_WEAK_MAP = __w_pdfjs_require__(110);
+
+var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;
+var WEAK_MAP = 'WeakMap';
+var getWeak = meta.getWeak;
+var isExtensible = Object.isExtensible;
+var uncaughtFrozenStore = weak.ufstore;
+var InternalMap;
+
+var wrapper = function wrapper(get) {
+ return function WeakMap() {
+ return get(this, arguments.length > 0 ? arguments[0] : undefined);
+ };
+};
+
+var methods = {
+ get: function get(key) {
+ if (isObject(key)) {
+ var data = getWeak(key);
+ if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
+ return data ? data[this._i] : undefined;
+ }
+ },
+ set: function set(key, value) {
+ return weak.def(validate(this, WEAK_MAP), key, value);
+ }
+};
+
+var $WeakMap = module.exports = __w_pdfjs_require__(111)(WEAK_MAP, wrapper, methods, weak, true, true);
+
+if (NATIVE_WEAK_MAP && IS_IE11) {
+ InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
+ assign(InternalMap.prototype, methods);
+ meta.NEED = true;
+ each(['delete', 'has', 'get', 'set'], function (key) {
+ var proto = $WeakMap.prototype;
+ var method = proto[key];
+ redefine(proto, key, function (a, b) {
+ if (isObject(a) && !isExtensible(a)) {
+ if (!this._f) this._f = new InternalMap();
+
+ var result = this._f[key](a, b);
+
+ return key == 'set' ? this : result;
+ }
+
+ return method.call(this, a, b);
+ });
+ });
+}
+
+/***/ }),
+/* 104 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var ctx = __w_pdfjs_require__(26);
+
+var IObject = __w_pdfjs_require__(44);
+
+var toObject = __w_pdfjs_require__(62);
+
+var toLength = __w_pdfjs_require__(28);
+
+var asc = __w_pdfjs_require__(105);
+
+module.exports = function (TYPE, $create) {
+ var IS_MAP = TYPE == 1;
+ var IS_FILTER = TYPE == 2;
+ var IS_SOME = TYPE == 3;
+ var IS_EVERY = TYPE == 4;
+ var IS_FIND_INDEX = TYPE == 6;
+ var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
+ var create = $create || asc;
+ return function ($this, callbackfn, that) {
+ var O = toObject($this);
+ var self = IObject(O);
+ var f = ctx(callbackfn, that, 3);
+ var length = toLength(self.length);
+ var index = 0;
+ var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
+ var val, res;
+
+ for (; length > index; index++) {
+ if (NO_HOLES || index in self) {
+ val = self[index];
+ res = f(val, index, O);
+
+ if (TYPE) {
+ if (IS_MAP) result[index] = res;else if (res) switch (TYPE) {
+ case 3:
+ return true;
+
+ case 5:
+ return val;
+
+ case 6:
+ return index;
+
+ case 2:
+ result.push(val);
+ } else if (IS_EVERY) return false;
+ }
+ }
+ }
+
+ return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
+ };
+};
+
+/***/ }),
+/* 105 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var speciesConstructor = __w_pdfjs_require__(106);
+
+module.exports = function (original, length) {
+ return new (speciesConstructor(original))(length);
+};
+
+/***/ }),
+/* 106 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var isArray = __w_pdfjs_require__(107);
+
+var SPECIES = __w_pdfjs_require__(33)('species');
+
+module.exports = function (original) {
+ var C;
+
+ if (isArray(original)) {
+ C = original.constructor;
+ if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
+
+ if (isObject(C)) {
+ C = C[SPECIES];
+ if (C === null) C = undefined;
+ }
+ }
+
+ return C === undefined ? Array : C;
+};
+
+/***/ }),
+/* 107 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var cof = __w_pdfjs_require__(32);
+
+module.exports = Array.isArray || function isArray(arg) {
+ return cof(arg) == 'Array';
+};
+
+/***/ }),
+/* 108 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+var META = __w_pdfjs_require__(22)('meta');
+
+var isObject = __w_pdfjs_require__(13);
+
+var has = __w_pdfjs_require__(21);
+
+var setDesc = __w_pdfjs_require__(11).f;
+
+var id = 0;
+
+var isExtensible = Object.isExtensible || function () {
+ return true;
+};
+
+var FREEZE = !__w_pdfjs_require__(16)(function () {
+ return isExtensible(Object.preventExtensions({}));
+});
+
+var setMeta = function setMeta(it) {
+ setDesc(it, META, {
+ value: {
+ i: 'O' + ++id,
+ w: {}
+ }
+ });
+};
+
+var fastKey = function fastKey(it, create) {
+ if (!isObject(it)) return _typeof(it) == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
+
+ if (!has(it, META)) {
+ if (!isExtensible(it)) return 'F';
+ if (!create) return 'E';
+ setMeta(it);
+ }
+
+ return it[META].i;
+};
+
+var getWeak = function getWeak(it, create) {
+ if (!has(it, META)) {
+ if (!isExtensible(it)) return true;
+ if (!create) return false;
+ setMeta(it);
+ }
+
+ return it[META].w;
+};
+
+var onFreeze = function onFreeze(it) {
+ if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
+ return it;
+};
+
+var meta = module.exports = {
+ KEY: META,
+ NEED: false,
+ fastKey: fastKey,
+ getWeak: getWeak,
+ onFreeze: onFreeze
+};
+
+/***/ }),
+/* 109 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var redefineAll = __w_pdfjs_require__(98);
+
+var getWeak = __w_pdfjs_require__(108).getWeak;
+
+var anObject = __w_pdfjs_require__(12);
+
+var isObject = __w_pdfjs_require__(13);
+
+var anInstance = __w_pdfjs_require__(88);
+
+var forOf = __w_pdfjs_require__(89);
+
+var createArrayMethod = __w_pdfjs_require__(104);
+
+var $has = __w_pdfjs_require__(21);
+
+var validate = __w_pdfjs_require__(110);
+
+var arrayFind = createArrayMethod(5);
+var arrayFindIndex = createArrayMethod(6);
+var id = 0;
+
+var uncaughtFrozenStore = function uncaughtFrozenStore(that) {
+ return that._l || (that._l = new UncaughtFrozenStore());
+};
+
+var UncaughtFrozenStore = function UncaughtFrozenStore() {
+ this.a = [];
+};
+
+var findUncaughtFrozen = function findUncaughtFrozen(store, key) {
+ return arrayFind(store.a, function (it) {
+ return it[0] === key;
+ });
+};
+
+UncaughtFrozenStore.prototype = {
+ get: function get(key) {
+ var entry = findUncaughtFrozen(this, key);
+ if (entry) return entry[1];
+ },
+ has: function has(key) {
+ return !!findUncaughtFrozen(this, key);
+ },
+ set: function set(key, value) {
+ var entry = findUncaughtFrozen(this, key);
+ if (entry) entry[1] = value;else this.a.push([key, value]);
+ },
+ 'delete': function _delete(key) {
+ var index = arrayFindIndex(this.a, function (it) {
+ return it[0] === key;
+ });
+ if (~index) this.a.splice(index, 1);
+ return !!~index;
+ }
+};
+module.exports = {
+ getConstructor: function getConstructor(wrapper, NAME, IS_MAP, ADDER) {
+ var C = wrapper(function (that, iterable) {
+ anInstance(that, C, NAME, '_i');
+ that._t = NAME;
+ that._i = id++;
+ that._l = undefined;
+ if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
+ });
+ redefineAll(C.prototype, {
+ 'delete': function _delete(key) {
+ if (!isObject(key)) return false;
+ var data = getWeak(key);
+ if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
+ return data && $has(data, this._i) && delete data[this._i];
+ },
+ has: function has(key) {
+ if (!isObject(key)) return false;
+ var data = getWeak(key);
+ if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
+ return data && $has(data, this._i);
+ }
+ });
+ return C;
+ },
+ def: function def(that, key, value) {
+ var data = getWeak(anObject(key), true);
+ if (data === true) uncaughtFrozenStore(that).set(key, value);else data[that._i] = value;
+ return that;
+ },
+ ufstore: uncaughtFrozenStore
+};
+
+/***/ }),
+/* 110 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+module.exports = function (it, TYPE) {
+ if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
+ return it;
+};
+
+/***/ }),
+/* 111 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var $export = __w_pdfjs_require__(7);
+
+var redefine = __w_pdfjs_require__(20);
+
+var redefineAll = __w_pdfjs_require__(98);
+
+var meta = __w_pdfjs_require__(108);
+
+var forOf = __w_pdfjs_require__(89);
+
+var anInstance = __w_pdfjs_require__(88);
+
+var isObject = __w_pdfjs_require__(13);
+
+var fails = __w_pdfjs_require__(16);
+
+var $iterDetect = __w_pdfjs_require__(69);
+
+var setToStringTag = __w_pdfjs_require__(60);
+
+var inheritIfRequired = __w_pdfjs_require__(112);
+
+module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
+ var Base = global[NAME];
+ var C = Base;
+ var ADDER = IS_MAP ? 'set' : 'add';
+ var proto = C && C.prototype;
+ var O = {};
+
+ var fixMethod = function fixMethod(KEY) {
+ var fn = proto[KEY];
+ redefine(proto, KEY, KEY == 'delete' ? function (a) {
+ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
+ } : KEY == 'has' ? function has(a) {
+ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
+ } : KEY == 'get' ? function get(a) {
+ return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
+ } : KEY == 'add' ? function add(a) {
+ fn.call(this, a === 0 ? 0 : a);
+ return this;
+ } : function set(a, b) {
+ fn.call(this, a === 0 ? 0 : a, b);
+ return this;
+ });
+ };
+
+ if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
+ new C().entries().next();
+ }))) {
+ C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
+ redefineAll(C.prototype, methods);
+ meta.NEED = true;
+ } else {
+ var instance = new C();
+ var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
+ var THROWS_ON_PRIMITIVES = fails(function () {
+ instance.has(1);
+ });
+ var ACCEPT_ITERABLES = $iterDetect(function (iter) {
+ new C(iter);
+ });
+ var BUGGY_ZERO = !IS_WEAK && fails(function () {
+ var $instance = new C();
+ var index = 5;
+
+ while (index--) {
+ $instance[ADDER](index, index);
+ }
+
+ return !$instance.has(-0);
+ });
+
+ if (!ACCEPT_ITERABLES) {
+ C = wrapper(function (target, iterable) {
+ anInstance(target, C, NAME);
+ var that = inheritIfRequired(new Base(), target, C);
+ if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
+ return that;
+ });
+ C.prototype = proto;
+ proto.constructor = C;
+ }
+
+ if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
+ fixMethod('delete');
+ fixMethod('has');
+ IS_MAP && fixMethod('get');
+ }
+
+ if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
+ if (IS_WEAK && proto.clear) delete proto.clear;
+ }
+
+ setToStringTag(C, NAME);
+ O[NAME] = C;
+ $export($export.G + $export.W + $export.F * (C != Base), O);
+ if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
+ return C;
+};
+
+/***/ }),
+/* 112 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var setPrototypeOf = __w_pdfjs_require__(113).set;
+
+module.exports = function (that, target, C) {
+ var S = target.constructor;
+ var P;
+
+ if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
+ setPrototypeOf(that, P);
+ }
+
+ return that;
+};
+
+/***/ }),
+/* 113 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var isObject = __w_pdfjs_require__(13);
+
+var anObject = __w_pdfjs_require__(12);
+
+var check = function check(O, proto) {
+ anObject(O);
+ if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
+};
+
+module.exports = {
+ set: Object.setPrototypeOf || ('__proto__' in {} ? function (test, buggy, set) {
+ try {
+ set = __w_pdfjs_require__(26)(Function.call, __w_pdfjs_require__(114).f(Object.prototype, '__proto__').set, 2);
+ set(test, []);
+ buggy = !(test instanceof Array);
+ } catch (e) {
+ buggy = true;
+ }
+
+ return function setPrototypeOf(O, proto) {
+ check(O, proto);
+ if (buggy) O.__proto__ = proto;else set(O, proto);
+ return O;
+ };
+ }({}, false) : undefined),
+ check: check
+};
+
+/***/ }),
+/* 114 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var pIE = __w_pdfjs_require__(74);
+
+var createDesc = __w_pdfjs_require__(19);
+
+var toIObject = __w_pdfjs_require__(43);
+
+var toPrimitive = __w_pdfjs_require__(18);
+
+var has = __w_pdfjs_require__(21);
+
+var IE8_DOM_DEFINE = __w_pdfjs_require__(14);
+
+var gOPD = Object.getOwnPropertyDescriptor;
+exports.f = __w_pdfjs_require__(15) ? gOPD : function getOwnPropertyDescriptor(O, P) {
+ O = toIObject(O);
+ P = toPrimitive(P, true);
+ if (IE8_DOM_DEFINE) try {
+ return gOPD(O, P);
+ } catch (e) {}
+ if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
+};
+
+/***/ }),
+/* 115 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(116)('WeakMap');
+
+/***/ }),
+/* 116 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+module.exports = function (COLLECTION) {
+ $export($export.S, COLLECTION, {
+ of: function of() {
+ var length = arguments.length;
+ var A = new Array(length);
+
+ while (length--) {
+ A[length] = arguments[length];
+ }
+
+ return new this(A);
+ }
+ });
+};
+
+/***/ }),
+/* 117 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(118)('WeakMap');
+
+/***/ }),
+/* 118 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var aFunction = __w_pdfjs_require__(27);
+
+var ctx = __w_pdfjs_require__(26);
+
+var forOf = __w_pdfjs_require__(89);
+
+module.exports = function (COLLECTION) {
+ $export($export.S, COLLECTION, {
+ from: function from(source) {
+ var mapFn = arguments[1];
+ var mapping, A, n, cb;
+ aFunction(this);
+ mapping = mapFn !== undefined;
+ if (mapping) aFunction(mapFn);
+ if (source == undefined) return new this();
+ A = [];
+
+ if (mapping) {
+ n = 0;
+ cb = ctx(mapFn, arguments[2], 2);
+ forOf(source, false, function (nextItem) {
+ A.push(cb(nextItem, n++));
+ });
+ } else {
+ forOf(source, false, A.push, A);
+ }
+
+ return new this(A);
+ }
+ });
+};
+
+/***/ }),
+/* 119 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(83);
+
+__w_pdfjs_require__(84);
+
+__w_pdfjs_require__(120);
+
+__w_pdfjs_require__(121);
+
+__w_pdfjs_require__(122);
+
+module.exports = __w_pdfjs_require__(9).WeakSet;
+
+/***/ }),
+/* 120 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var weak = __w_pdfjs_require__(109);
+
+var validate = __w_pdfjs_require__(110);
+
+var WEAK_SET = 'WeakSet';
+
+__w_pdfjs_require__(111)(WEAK_SET, function (get) {
+ return function WeakSet() {
+ return get(this, arguments.length > 0 ? arguments[0] : undefined);
+ };
+}, {
+ add: function add(value) {
+ return weak.def(validate(this, WEAK_SET), value, true);
+ }
+}, weak, false, true);
+
+/***/ }),
+/* 121 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(116)('WeakSet');
+
+/***/ }),
+/* 122 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(118)('WeakSet');
+
+/***/ }),
+/* 123 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(124);
+
+module.exports = __w_pdfjs_require__(9).String.codePointAt;
+
+/***/ }),
+/* 124 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var $at = __w_pdfjs_require__(49)(false);
+
+$export($export.P, 'String', {
+ codePointAt: function codePointAt(pos) {
+ return $at(this, pos);
+ }
+});
+
+/***/ }),
+/* 125 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(126);
+
+module.exports = __w_pdfjs_require__(9).String.fromCodePoint;
+
+/***/ }),
+/* 126 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var toAbsoluteIndex = __w_pdfjs_require__(45);
+
+var fromCharCode = String.fromCharCode;
+var $fromCodePoint = String.fromCodePoint;
+$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
+ fromCodePoint: function fromCodePoint(x) {
+ var res = [];
+ var aLen = arguments.length;
+ var i = 0;
+ var code;
+
+ while (aLen > i) {
+ code = +arguments[i++];
+ if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
+ res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00));
+ }
+
+ return res.join('');
+ }
+});
+
+/***/ }),
+/* 127 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(128);
+
+__w_pdfjs_require__(83);
+
+module.exports = __w_pdfjs_require__(9).Symbol;
+
+/***/ }),
+/* 128 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+var global = __w_pdfjs_require__(8);
+
+var has = __w_pdfjs_require__(21);
+
+var DESCRIPTORS = __w_pdfjs_require__(15);
+
+var $export = __w_pdfjs_require__(7);
+
+var redefine = __w_pdfjs_require__(20);
+
+var META = __w_pdfjs_require__(108).KEY;
+
+var $fails = __w_pdfjs_require__(16);
+
+var shared = __w_pdfjs_require__(24);
+
+var setToStringTag = __w_pdfjs_require__(60);
+
+var uid = __w_pdfjs_require__(22);
+
+var wks = __w_pdfjs_require__(33);
+
+var wksExt = __w_pdfjs_require__(129);
+
+var wksDefine = __w_pdfjs_require__(130);
+
+var enumKeys = __w_pdfjs_require__(131);
+
+var isArray = __w_pdfjs_require__(107);
+
+var anObject = __w_pdfjs_require__(12);
+
+var isObject = __w_pdfjs_require__(13);
+
+var toObject = __w_pdfjs_require__(62);
+
+var toIObject = __w_pdfjs_require__(43);
+
+var toPrimitive = __w_pdfjs_require__(18);
+
+var createDesc = __w_pdfjs_require__(19);
+
+var _create = __w_pdfjs_require__(53);
+
+var gOPNExt = __w_pdfjs_require__(132);
+
+var $GOPD = __w_pdfjs_require__(114);
+
+var $GOPS = __w_pdfjs_require__(73);
+
+var $DP = __w_pdfjs_require__(11);
+
+var $keys = __w_pdfjs_require__(55);
+
+var gOPD = $GOPD.f;
+var dP = $DP.f;
+var gOPN = gOPNExt.f;
+var $Symbol = global.Symbol;
+var $JSON = global.JSON;
+
+var _stringify = $JSON && $JSON.stringify;
+
+var PROTOTYPE = 'prototype';
+var HIDDEN = wks('_hidden');
+var TO_PRIMITIVE = wks('toPrimitive');
+var isEnum = {}.propertyIsEnumerable;
+var SymbolRegistry = shared('symbol-registry');
+var AllSymbols = shared('symbols');
+var OPSymbols = shared('op-symbols');
+var ObjectProto = Object[PROTOTYPE];
+var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
+var QObject = global.QObject;
+var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
+var setSymbolDesc = DESCRIPTORS && $fails(function () {
+ return _create(dP({}, 'a', {
+ get: function get() {
+ return dP(this, 'a', {
+ value: 7
+ }).a;
+ }
+ })).a != 7;
+}) ? function (it, key, D) {
+ var protoDesc = gOPD(ObjectProto, key);
+ if (protoDesc) delete ObjectProto[key];
+ dP(it, key, D);
+ if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
+} : dP;
+
+var wrap = function wrap(tag) {
+ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
+
+ sym._k = tag;
+ return sym;
+};
+
+var isSymbol = USE_NATIVE && _typeof($Symbol.iterator) == 'symbol' ? function (it) {
+ return _typeof(it) == 'symbol';
+} : function (it) {
+ return it instanceof $Symbol;
+};
+
+var $defineProperty = function defineProperty(it, key, D) {
+ if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
+ anObject(it);
+ key = toPrimitive(key, true);
+ anObject(D);
+
+ if (has(AllSymbols, key)) {
+ if (!D.enumerable) {
+ if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
+ it[HIDDEN][key] = true;
+ } else {
+ if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
+ D = _create(D, {
+ enumerable: createDesc(0, false)
+ });
+ }
+
+ return setSymbolDesc(it, key, D);
+ }
+
+ return dP(it, key, D);
+};
+
+var $defineProperties = function defineProperties(it, P) {
+ anObject(it);
+ var keys = enumKeys(P = toIObject(P));
+ var i = 0;
+ var l = keys.length;
+ var key;
+
+ while (l > i) {
+ $defineProperty(it, key = keys[i++], P[key]);
+ }
+
+ return it;
+};
+
+var $create = function create(it, P) {
+ return P === undefined ? _create(it) : $defineProperties(_create(it), P);
+};
+
+var $propertyIsEnumerable = function propertyIsEnumerable(key) {
+ var E = isEnum.call(this, key = toPrimitive(key, true));
+ if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
+ return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
+};
+
+var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
+ it = toIObject(it);
+ key = toPrimitive(key, true);
+ if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
+ var D = gOPD(it, key);
+ if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
+ return D;
+};
+
+var $getOwnPropertyNames = function getOwnPropertyNames(it) {
+ var names = gOPN(toIObject(it));
+ var result = [];
+ var i = 0;
+ var key;
+
+ while (names.length > i) {
+ if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
+ }
+
+ return result;
+};
+
+var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
+ var IS_OP = it === ObjectProto;
+ var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
+ var result = [];
+ var i = 0;
+ var key;
+
+ while (names.length > i) {
+ if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
+ }
+
+ return result;
+};
+
+if (!USE_NATIVE) {
+ $Symbol = function _Symbol() {
+ if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
+ var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
+
+ var $set = function $set(value) {
+ if (this === ObjectProto) $set.call(OPSymbols, value);
+ if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
+ setSymbolDesc(this, tag, createDesc(1, value));
+ };
+
+ if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, {
+ configurable: true,
+ set: $set
+ });
+ return wrap(tag);
+ };
+
+ redefine($Symbol[PROTOTYPE], 'toString', function toString() {
+ return this._k;
+ });
+ $GOPD.f = $getOwnPropertyDescriptor;
+ $DP.f = $defineProperty;
+ __w_pdfjs_require__(133).f = gOPNExt.f = $getOwnPropertyNames;
+ __w_pdfjs_require__(74).f = $propertyIsEnumerable;
+ $GOPS.f = $getOwnPropertySymbols;
+
+ if (DESCRIPTORS && !__w_pdfjs_require__(25)) {
+ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
+ }
+
+ wksExt.f = function (name) {
+ return wrap(wks(name));
+ };
+}
+
+$export($export.G + $export.W + $export.F * !USE_NATIVE, {
+ Symbol: $Symbol
+});
+
+for (var es6Symbols = 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'.split(','), j = 0; es6Symbols.length > j;) {
+ wks(es6Symbols[j++]);
+}
+
+for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) {
+ wksDefine(wellKnownSymbols[k++]);
+}
+
+$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
+ 'for': function _for(key) {
+ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key);
+ },
+ keyFor: function keyFor(sym) {
+ if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
+
+ for (var key in SymbolRegistry) {
+ if (SymbolRegistry[key] === sym) return key;
+ }
+ },
+ useSetter: function useSetter() {
+ setter = true;
+ },
+ useSimple: function useSimple() {
+ setter = false;
+ }
+});
+$export($export.S + $export.F * !USE_NATIVE, 'Object', {
+ create: $create,
+ defineProperty: $defineProperty,
+ defineProperties: $defineProperties,
+ getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
+ getOwnPropertyNames: $getOwnPropertyNames,
+ getOwnPropertySymbols: $getOwnPropertySymbols
+});
+var FAILS_ON_PRIMITIVES = $fails(function () {
+ $GOPS.f(1);
+});
+$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
+ getOwnPropertySymbols: function getOwnPropertySymbols(it) {
+ return $GOPS.f(toObject(it));
+ }
+});
+$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
+ var S = $Symbol();
+ return _stringify([S]) != '[null]' || _stringify({
+ a: S
+ }) != '{}' || _stringify(Object(S)) != '{}';
+})), 'JSON', {
+ stringify: function stringify(it) {
+ var args = [it];
+ var i = 1;
+ var replacer, $replacer;
+
+ while (arguments.length > i) {
+ args.push(arguments[i++]);
+ }
+
+ $replacer = replacer = args[1];
+ if (!isObject(replacer) && it === undefined || isSymbol(it)) return;
+ if (!isArray(replacer)) replacer = function replacer(key, value) {
+ if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
+ if (!isSymbol(value)) return value;
+ };
+ args[1] = replacer;
+ return _stringify.apply($JSON, args);
+ }
+});
+$Symbol[PROTOTYPE][TO_PRIMITIVE] || __w_pdfjs_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
+setToStringTag($Symbol, 'Symbol');
+setToStringTag(Math, 'Math', true);
+setToStringTag(global.JSON, 'JSON', true);
+
+/***/ }),
+/* 129 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+exports.f = __w_pdfjs_require__(33);
+
+/***/ }),
+/* 130 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var global = __w_pdfjs_require__(8);
+
+var core = __w_pdfjs_require__(9);
+
+var LIBRARY = __w_pdfjs_require__(25);
+
+var wksExt = __w_pdfjs_require__(129);
+
+var defineProperty = __w_pdfjs_require__(11).f;
+
+module.exports = function (name) {
+ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
+ if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, {
+ value: wksExt.f(name)
+ });
+};
+
+/***/ }),
+/* 131 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var getKeys = __w_pdfjs_require__(55);
+
+var gOPS = __w_pdfjs_require__(73);
+
+var pIE = __w_pdfjs_require__(74);
+
+module.exports = function (it) {
+ var result = getKeys(it);
+ var getSymbols = gOPS.f;
+
+ if (getSymbols) {
+ var symbols = getSymbols(it);
+ var isEnum = pIE.f;
+ var i = 0;
+ var key;
+
+ while (symbols.length > i) {
+ if (isEnum.call(it, key = symbols[i++])) result.push(key);
+ }
+ }
+
+ return result;
+};
+
+/***/ }),
+/* 132 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+var toIObject = __w_pdfjs_require__(43);
+
+var gOPN = __w_pdfjs_require__(133).f;
+
+var toString = {}.toString;
+var windowNames = (typeof window === "undefined" ? "undefined" : _typeof(window)) == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [];
+
+var getWindowNames = function getWindowNames(it) {
+ try {
+ return gOPN(it);
+ } catch (e) {
+ return windowNames.slice();
+ }
+};
+
+module.exports.f = function getOwnPropertyNames(it) {
+ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
+};
+
+/***/ }),
+/* 133 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $keys = __w_pdfjs_require__(56);
+
+var hiddenKeys = __w_pdfjs_require__(58).concat('length', 'prototype');
+
+exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
+ return $keys(O, hiddenKeys);
+};
+
+/***/ }),
+/* 134 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(135);
+
+module.exports = __w_pdfjs_require__(9).String.padStart;
+
+/***/ }),
+/* 135 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var $pad = __w_pdfjs_require__(136);
+
+var userAgent = __w_pdfjs_require__(96);
+
+var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent);
+$export($export.P + $export.F * WEBKIT_BUG, 'String', {
+ padStart: function padStart(maxLength) {
+ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
+ }
+});
+
+/***/ }),
+/* 136 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toLength = __w_pdfjs_require__(28);
+
+var repeat = __w_pdfjs_require__(137);
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function (that, maxLength, fillString, left) {
+ var S = String(defined(that));
+ var stringLength = S.length;
+ var fillStr = fillString === undefined ? ' ' : String(fillString);
+ var intMaxLength = toLength(maxLength);
+ if (intMaxLength <= stringLength || fillStr == '') return S;
+ var fillLen = intMaxLength - stringLength;
+ var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
+ if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
+ return left ? stringFiller + S : S + stringFiller;
+};
+
+/***/ }),
+/* 137 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var toInteger = __w_pdfjs_require__(29);
+
+var defined = __w_pdfjs_require__(34);
+
+module.exports = function repeat(count) {
+ var str = String(defined(this));
+ var res = '';
+ var n = toInteger(count);
+ if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
+
+ for (; n > 0; (n >>>= 1) && (str += str)) {
+ if (n & 1) res += str;
+ }
+
+ return res;
+};
+
+/***/ }),
+/* 138 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(139);
+
+module.exports = __w_pdfjs_require__(9).String.padEnd;
+
+/***/ }),
+/* 139 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var $pad = __w_pdfjs_require__(136);
+
+var userAgent = __w_pdfjs_require__(96);
+
+var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent);
+$export($export.P + $export.F * WEBKIT_BUG, 'String', {
+ padEnd: function padEnd(maxLength) {
+ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
+ }
+});
+
+/***/ }),
+/* 140 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+__w_pdfjs_require__(141);
+
+module.exports = __w_pdfjs_require__(9).Object.values;
+
+/***/ }),
+/* 141 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var $export = __w_pdfjs_require__(7);
+
+var $values = __w_pdfjs_require__(142)(false);
+
+$export($export.S, 'Object', {
+ values: function values(it) {
+ return $values(it);
+ }
+});
+
+/***/ }),
+/* 142 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var DESCRIPTORS = __w_pdfjs_require__(15);
+
+var getKeys = __w_pdfjs_require__(55);
+
+var toIObject = __w_pdfjs_require__(43);
+
+var isEnum = __w_pdfjs_require__(74).f;
+
+module.exports = function (isEntries) {
+ return function (it) {
+ var O = toIObject(it);
+ var keys = getKeys(O);
+ var length = keys.length;
+ var i = 0;
+ var result = [];
+ var key;
+
+ while (length > i) {
+ key = keys[i++];
+
+ if (!DESCRIPTORS || isEnum.call(O, key)) {
+ result.push(isEntries ? [key, O[key]] : O[key]);
+ }
+ }
+
+ return result;
+ };
+};
+
+/***/ }),
+/* 143 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+{
+ var isReadableStreamSupported = false;
+
+ if (typeof ReadableStream !== 'undefined') {
+ try {
+ new ReadableStream({
+ start: function start(controller) {
+ controller.close();
+ }
+ });
+ isReadableStreamSupported = true;
+ } catch (e) {}
+ }
+
+ if (isReadableStreamSupported) {
+ exports.ReadableStream = ReadableStream;
+ } else {
+ exports.ReadableStream = __w_pdfjs_require__(144).ReadableStream;
+ }
+}
+
+/***/ }),
+/* 144 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
+
+(function (e, a) {
+ for (var i in a) {
+ e[i] = a[i];
+ }
+})(exports, function (modules) {
+ var installedModules = {};
+
+ function __w_pdfjs_require__(moduleId) {
+ if (installedModules[moduleId]) return installedModules[moduleId].exports;
+ var module = installedModules[moduleId] = {
+ i: moduleId,
+ l: false,
+ exports: {}
+ };
+ modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__);
+ module.l = true;
+ return module.exports;
+ }
+
+ __w_pdfjs_require__.m = modules;
+ __w_pdfjs_require__.c = installedModules;
+
+ __w_pdfjs_require__.i = function (value) {
+ return value;
+ };
+
+ __w_pdfjs_require__.d = function (exports, name, getter) {
+ if (!__w_pdfjs_require__.o(exports, name)) {
+ Object.defineProperty(exports, name, {
+ configurable: false,
+ enumerable: true,
+ get: getter
+ });
+ }
+ };
+
+ __w_pdfjs_require__.n = function (module) {
+ var getter = module && module.__esModule ? function getDefault() {
+ return module['default'];
+ } : function getModuleExports() {
+ return module;
+ };
+
+ __w_pdfjs_require__.d(getter, 'a', getter);
+
+ return getter;
+ };
+
+ __w_pdfjs_require__.o = function (object, property) {
+ return Object.prototype.hasOwnProperty.call(object, property);
+ };
+
+ __w_pdfjs_require__.p = "";
+ return __w_pdfjs_require__(__w_pdfjs_require__.s = 7);
+}([function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
+ return _typeof2(obj);
+ } : function (obj) {
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
+ };
+
+ var _require = __w_pdfjs_require__(1),
+ assert = _require.assert;
+
+ function IsPropertyKey(argument) {
+ return typeof argument === 'string' || (typeof argument === 'undefined' ? 'undefined' : _typeof(argument)) === 'symbol';
+ }
+
+ exports.typeIsObject = function (x) {
+ return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x !== null || typeof x === 'function';
+ };
+
+ exports.createDataProperty = function (o, p, v) {
+ assert(exports.typeIsObject(o));
+ Object.defineProperty(o, p, {
+ value: v,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ };
+
+ exports.createArrayFromList = function (elements) {
+ return elements.slice();
+ };
+
+ exports.ArrayBufferCopy = function (dest, destOffset, src, srcOffset, n) {
+ new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
+ };
+
+ exports.CreateIterResultObject = function (value, done) {
+ assert(typeof done === 'boolean');
+ var obj = {};
+ Object.defineProperty(obj, 'value', {
+ value: value,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ Object.defineProperty(obj, 'done', {
+ value: done,
+ enumerable: true,
+ writable: true,
+ configurable: true
+ });
+ return obj;
+ };
+
+ exports.IsFiniteNonNegativeNumber = function (v) {
+ if (Number.isNaN(v)) {
+ return false;
+ }
+
+ if (v === Infinity) {
+ return false;
+ }
+
+ if (v < 0) {
+ return false;
+ }
+
+ return true;
+ };
+
+ function Call(F, V, args) {
+ if (typeof F !== 'function') {
+ throw new TypeError('Argument is not a function');
+ }
+
+ return Function.prototype.apply.call(F, V, args);
+ }
+
+ exports.InvokeOrNoop = function (O, P, args) {
+ assert(O !== undefined);
+ assert(IsPropertyKey(P));
+ assert(Array.isArray(args));
+ var method = O[P];
+
+ if (method === undefined) {
+ return undefined;
+ }
+
+ return Call(method, O, args);
+ };
+
+ exports.PromiseInvokeOrNoop = function (O, P, args) {
+ assert(O !== undefined);
+ assert(IsPropertyKey(P));
+ assert(Array.isArray(args));
+
+ try {
+ return Promise.resolve(exports.InvokeOrNoop(O, P, args));
+ } catch (returnValueE) {
+ return Promise.reject(returnValueE);
+ }
+ };
+
+ exports.PromiseInvokeOrPerformFallback = function (O, P, args, F, argsF) {
+ assert(O !== undefined);
+ assert(IsPropertyKey(P));
+ assert(Array.isArray(args));
+ assert(Array.isArray(argsF));
+ var method = void 0;
+
+ try {
+ method = O[P];
+ } catch (methodE) {
+ return Promise.reject(methodE);
+ }
+
+ if (method === undefined) {
+ return F.apply(null, argsF);
+ }
+
+ try {
+ return Promise.resolve(Call(method, O, args));
+ } catch (e) {
+ return Promise.reject(e);
+ }
+ };
+
+ exports.TransferArrayBuffer = function (O) {
+ return O.slice();
+ };
+
+ exports.ValidateAndNormalizeHighWaterMark = function (highWaterMark) {
+ highWaterMark = Number(highWaterMark);
+
+ if (Number.isNaN(highWaterMark) || highWaterMark < 0) {
+ throw new RangeError('highWaterMark property of a queuing strategy must be non-negative and non-NaN');
+ }
+
+ return highWaterMark;
+ };
+
+ exports.ValidateAndNormalizeQueuingStrategy = function (size, highWaterMark) {
+ if (size !== undefined && typeof size !== 'function') {
+ throw new TypeError('size property of a queuing strategy must be a function');
+ }
+
+ highWaterMark = exports.ValidateAndNormalizeHighWaterMark(highWaterMark);
+ return {
+ size: size,
+ highWaterMark: highWaterMark
+ };
+ };
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ function rethrowAssertionErrorRejection(e) {
+ if (e && e.constructor === AssertionError) {
+ setTimeout(function () {
+ throw e;
+ }, 0);
+ }
+ }
+
+ function AssertionError(message) {
+ this.name = 'AssertionError';
+ this.message = message || '';
+ this.stack = new Error().stack;
+ }
+
+ AssertionError.prototype = Object.create(Error.prototype);
+ AssertionError.prototype.constructor = AssertionError;
+
+ function assert(value, message) {
+ if (!value) {
+ throw new AssertionError(message);
+ }
+ }
+
+ module.exports = {
+ rethrowAssertionErrorRejection: rethrowAssertionErrorRejection,
+ AssertionError: AssertionError,
+ assert: assert
+ };
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var _createClass = function () {
+ function defineProperties(target, props) {
+ for (var i = 0; i < props.length; i++) {
+ var descriptor = props[i];
+ descriptor.enumerable = descriptor.enumerable || false;
+ descriptor.configurable = true;
+ if ("value" in descriptor) descriptor.writable = true;
+ Object.defineProperty(target, descriptor.key, descriptor);
+ }
+ }
+
+ return function (Constructor, protoProps, staticProps) {
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
+ if (staticProps) defineProperties(Constructor, staticProps);
+ return Constructor;
+ };
+ }();
+
+ function _classCallCheck(instance, Constructor) {
+ if (!(instance instanceof Constructor)) {
+ throw new TypeError("Cannot call a class as a function");
+ }
+ }
+
+ var _require = __w_pdfjs_require__(0),
+ InvokeOrNoop = _require.InvokeOrNoop,
+ PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop,
+ ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy,
+ typeIsObject = _require.typeIsObject;
+
+ var _require2 = __w_pdfjs_require__(1),
+ assert = _require2.assert,
+ rethrowAssertionErrorRejection = _require2.rethrowAssertionErrorRejection;
+
+ var _require3 = __w_pdfjs_require__(3),
+ DequeueValue = _require3.DequeueValue,
+ EnqueueValueWithSize = _require3.EnqueueValueWithSize,
+ PeekQueueValue = _require3.PeekQueueValue,
+ ResetQueue = _require3.ResetQueue;
+
+ var WritableStream = function () {
+ function WritableStream() {
+ var underlyingSink = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ size = _ref.size,
+ _ref$highWaterMark = _ref.highWaterMark,
+ highWaterMark = _ref$highWaterMark === undefined ? 1 : _ref$highWaterMark;
+
+ _classCallCheck(this, WritableStream);
+
+ this._state = 'writable';
+ this._storedError = undefined;
+ this._writer = undefined;
+ this._writableStreamController = undefined;
+ this._writeRequests = [];
+ this._inFlightWriteRequest = undefined;
+ this._closeRequest = undefined;
+ this._inFlightCloseRequest = undefined;
+ this._pendingAbortRequest = undefined;
+ this._backpressure = false;
+ var type = underlyingSink.type;
+
+ if (type !== undefined) {
+ throw new RangeError('Invalid type is specified');
+ }
+
+ this._writableStreamController = new WritableStreamDefaultController(this, underlyingSink, size, highWaterMark);
+
+ this._writableStreamController.__startSteps();
+ }
+
+ _createClass(WritableStream, [{
+ key: 'abort',
+ value: function abort(reason) {
+ if (IsWritableStream(this) === false) {
+ return Promise.reject(streamBrandCheckException('abort'));
+ }
+
+ if (IsWritableStreamLocked(this) === true) {
+ return Promise.reject(new TypeError('Cannot abort a stream that already has a writer'));
+ }
+
+ return WritableStreamAbort(this, reason);
+ }
+ }, {
+ key: 'getWriter',
+ value: function getWriter() {
+ if (IsWritableStream(this) === false) {
+ throw streamBrandCheckException('getWriter');
+ }
+
+ return AcquireWritableStreamDefaultWriter(this);
+ }
+ }, {
+ key: 'locked',
+ get: function get() {
+ if (IsWritableStream(this) === false) {
+ throw streamBrandCheckException('locked');
+ }
+
+ return IsWritableStreamLocked(this);
+ }
+ }]);
+
+ return WritableStream;
+ }();
+
+ module.exports = {
+ AcquireWritableStreamDefaultWriter: AcquireWritableStreamDefaultWriter,
+ IsWritableStream: IsWritableStream,
+ IsWritableStreamLocked: IsWritableStreamLocked,
+ WritableStream: WritableStream,
+ WritableStreamAbort: WritableStreamAbort,
+ WritableStreamDefaultControllerError: WritableStreamDefaultControllerError,
+ WritableStreamDefaultWriterCloseWithErrorPropagation: WritableStreamDefaultWriterCloseWithErrorPropagation,
+ WritableStreamDefaultWriterRelease: WritableStreamDefaultWriterRelease,
+ WritableStreamDefaultWriterWrite: WritableStreamDefaultWriterWrite,
+ WritableStreamCloseQueuedOrInFlight: WritableStreamCloseQueuedOrInFlight
+ };
+
+ function AcquireWritableStreamDefaultWriter(stream) {
+ return new WritableStreamDefaultWriter(stream);
+ }
+
+ function IsWritableStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function IsWritableStreamLocked(stream) {
+ assert(IsWritableStream(stream) === true, 'IsWritableStreamLocked should only be used on known writable streams');
+
+ if (stream._writer === undefined) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function WritableStreamAbort(stream, reason) {
+ var state = stream._state;
+
+ if (state === 'closed') {
+ return Promise.resolve(undefined);
+ }
+
+ if (state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ var error = new TypeError('Requested to abort');
+
+ if (stream._pendingAbortRequest !== undefined) {
+ return Promise.reject(error);
+ }
+
+ assert(state === 'writable' || state === 'erroring', 'state must be writable or erroring');
+ var wasAlreadyErroring = false;
+
+ if (state === 'erroring') {
+ wasAlreadyErroring = true;
+ reason = undefined;
+ }
+
+ var promise = new Promise(function (resolve, reject) {
+ stream._pendingAbortRequest = {
+ _resolve: resolve,
+ _reject: reject,
+ _reason: reason,
+ _wasAlreadyErroring: wasAlreadyErroring
+ };
+ });
+
+ if (wasAlreadyErroring === false) {
+ WritableStreamStartErroring(stream, error);
+ }
+
+ return promise;
+ }
+
+ function WritableStreamAddWriteRequest(stream) {
+ assert(IsWritableStreamLocked(stream) === true);
+ assert(stream._state === 'writable');
+ var promise = new Promise(function (resolve, reject) {
+ var writeRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+
+ stream._writeRequests.push(writeRequest);
+ });
+ return promise;
+ }
+
+ function WritableStreamDealWithRejection(stream, error) {
+ var state = stream._state;
+
+ if (state === 'writable') {
+ WritableStreamStartErroring(stream, error);
+ return;
+ }
+
+ assert(state === 'erroring');
+ WritableStreamFinishErroring(stream);
+ }
+
+ function WritableStreamStartErroring(stream, reason) {
+ assert(stream._storedError === undefined, 'stream._storedError === undefined');
+ assert(stream._state === 'writable', 'state must be writable');
+ var controller = stream._writableStreamController;
+ assert(controller !== undefined, 'controller must not be undefined');
+ stream._state = 'erroring';
+ stream._storedError = reason;
+ var writer = stream._writer;
+
+ if (writer !== undefined) {
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
+ }
+
+ if (WritableStreamHasOperationMarkedInFlight(stream) === false && controller._started === true) {
+ WritableStreamFinishErroring(stream);
+ }
+ }
+
+ function WritableStreamFinishErroring(stream) {
+ assert(stream._state === 'erroring', 'stream._state === erroring');
+ assert(WritableStreamHasOperationMarkedInFlight(stream) === false, 'WritableStreamHasOperationMarkedInFlight(stream) === false');
+ stream._state = 'errored';
+
+ stream._writableStreamController.__errorSteps();
+
+ var storedError = stream._storedError;
+
+ for (var i = 0; i < stream._writeRequests.length; i++) {
+ var writeRequest = stream._writeRequests[i];
+
+ writeRequest._reject(storedError);
+ }
+
+ stream._writeRequests = [];
+
+ if (stream._pendingAbortRequest === undefined) {
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ return;
+ }
+
+ var abortRequest = stream._pendingAbortRequest;
+ stream._pendingAbortRequest = undefined;
+
+ if (abortRequest._wasAlreadyErroring === true) {
+ abortRequest._reject(storedError);
+
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ return;
+ }
+
+ var promise = stream._writableStreamController.__abortSteps(abortRequest._reason);
+
+ promise.then(function () {
+ abortRequest._resolve();
+
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ }, function (reason) {
+ abortRequest._reject(reason);
+
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ });
+ }
+
+ function WritableStreamFinishInFlightWrite(stream) {
+ assert(stream._inFlightWriteRequest !== undefined);
+
+ stream._inFlightWriteRequest._resolve(undefined);
+
+ stream._inFlightWriteRequest = undefined;
+ }
+
+ function WritableStreamFinishInFlightWriteWithError(stream, error) {
+ assert(stream._inFlightWriteRequest !== undefined);
+
+ stream._inFlightWriteRequest._reject(error);
+
+ stream._inFlightWriteRequest = undefined;
+ assert(stream._state === 'writable' || stream._state === 'erroring');
+ WritableStreamDealWithRejection(stream, error);
+ }
+
+ function WritableStreamFinishInFlightClose(stream) {
+ assert(stream._inFlightCloseRequest !== undefined);
+
+ stream._inFlightCloseRequest._resolve(undefined);
+
+ stream._inFlightCloseRequest = undefined;
+ var state = stream._state;
+ assert(state === 'writable' || state === 'erroring');
+
+ if (state === 'erroring') {
+ stream._storedError = undefined;
+
+ if (stream._pendingAbortRequest !== undefined) {
+ stream._pendingAbortRequest._resolve();
+
+ stream._pendingAbortRequest = undefined;
+ }
+ }
+
+ stream._state = 'closed';
+ var writer = stream._writer;
+
+ if (writer !== undefined) {
+ defaultWriterClosedPromiseResolve(writer);
+ }
+
+ assert(stream._pendingAbortRequest === undefined, 'stream._pendingAbortRequest === undefined');
+ assert(stream._storedError === undefined, 'stream._storedError === undefined');
+ }
+
+ function WritableStreamFinishInFlightCloseWithError(stream, error) {
+ assert(stream._inFlightCloseRequest !== undefined);
+
+ stream._inFlightCloseRequest._reject(error);
+
+ stream._inFlightCloseRequest = undefined;
+ assert(stream._state === 'writable' || stream._state === 'erroring');
+
+ if (stream._pendingAbortRequest !== undefined) {
+ stream._pendingAbortRequest._reject(error);
+
+ stream._pendingAbortRequest = undefined;
+ }
+
+ WritableStreamDealWithRejection(stream, error);
+ }
+
+ function WritableStreamCloseQueuedOrInFlight(stream) {
+ if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function WritableStreamHasOperationMarkedInFlight(stream) {
+ if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function WritableStreamMarkCloseRequestInFlight(stream) {
+ assert(stream._inFlightCloseRequest === undefined);
+ assert(stream._closeRequest !== undefined);
+ stream._inFlightCloseRequest = stream._closeRequest;
+ stream._closeRequest = undefined;
+ }
+
+ function WritableStreamMarkFirstWriteRequestInFlight(stream) {
+ assert(stream._inFlightWriteRequest === undefined, 'there must be no pending write request');
+ assert(stream._writeRequests.length !== 0, 'writeRequests must not be empty');
+ stream._inFlightWriteRequest = stream._writeRequests.shift();
+ }
+
+ function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
+ assert(stream._state === 'errored', '_stream_.[[state]] is `"errored"`');
+
+ if (stream._closeRequest !== undefined) {
+ assert(stream._inFlightCloseRequest === undefined);
+
+ stream._closeRequest._reject(stream._storedError);
+
+ stream._closeRequest = undefined;
+ }
+
+ var writer = stream._writer;
+
+ if (writer !== undefined) {
+ defaultWriterClosedPromiseReject(writer, stream._storedError);
+
+ writer._closedPromise["catch"](function () {});
+ }
+ }
+
+ function WritableStreamUpdateBackpressure(stream, backpressure) {
+ assert(stream._state === 'writable');
+ assert(WritableStreamCloseQueuedOrInFlight(stream) === false);
+ var writer = stream._writer;
+
+ if (writer !== undefined && backpressure !== stream._backpressure) {
+ if (backpressure === true) {
+ defaultWriterReadyPromiseReset(writer);
+ } else {
+ assert(backpressure === false);
+ defaultWriterReadyPromiseResolve(writer);
+ }
+ }
+
+ stream._backpressure = backpressure;
+ }
+
+ var WritableStreamDefaultWriter = function () {
+ function WritableStreamDefaultWriter(stream) {
+ _classCallCheck(this, WritableStreamDefaultWriter);
+
+ if (IsWritableStream(stream) === false) {
+ throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance');
+ }
+
+ if (IsWritableStreamLocked(stream) === true) {
+ throw new TypeError('This stream has already been locked for exclusive writing by another writer');
+ }
+
+ this._ownerWritableStream = stream;
+ stream._writer = this;
+ var state = stream._state;
+
+ if (state === 'writable') {
+ if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._backpressure === true) {
+ defaultWriterReadyPromiseInitialize(this);
+ } else {
+ defaultWriterReadyPromiseInitializeAsResolved(this);
+ }
+
+ defaultWriterClosedPromiseInitialize(this);
+ } else if (state === 'erroring') {
+ defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
+
+ this._readyPromise["catch"](function () {});
+
+ defaultWriterClosedPromiseInitialize(this);
+ } else if (state === 'closed') {
+ defaultWriterReadyPromiseInitializeAsResolved(this);
+ defaultWriterClosedPromiseInitializeAsResolved(this);
+ } else {
+ assert(state === 'errored', 'state must be errored');
+ var storedError = stream._storedError;
+ defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
+
+ this._readyPromise["catch"](function () {});
+
+ defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
+
+ this._closedPromise["catch"](function () {});
+ }
+ }
+
+ _createClass(WritableStreamDefaultWriter, [{
+ key: 'abort',
+ value: function abort(reason) {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ return Promise.reject(defaultWriterBrandCheckException('abort'));
+ }
+
+ if (this._ownerWritableStream === undefined) {
+ return Promise.reject(defaultWriterLockException('abort'));
+ }
+
+ return WritableStreamDefaultWriterAbort(this, reason);
+ }
+ }, {
+ key: 'close',
+ value: function close() {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ return Promise.reject(defaultWriterBrandCheckException('close'));
+ }
+
+ var stream = this._ownerWritableStream;
+
+ if (stream === undefined) {
+ return Promise.reject(defaultWriterLockException('close'));
+ }
+
+ if (WritableStreamCloseQueuedOrInFlight(stream) === true) {
+ return Promise.reject(new TypeError('cannot close an already-closing stream'));
+ }
+
+ return WritableStreamDefaultWriterClose(this);
+ }
+ }, {
+ key: 'releaseLock',
+ value: function releaseLock() {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ throw defaultWriterBrandCheckException('releaseLock');
+ }
+
+ var stream = this._ownerWritableStream;
+
+ if (stream === undefined) {
+ return;
+ }
+
+ assert(stream._writer !== undefined);
+ WritableStreamDefaultWriterRelease(this);
+ }
+ }, {
+ key: 'write',
+ value: function write(chunk) {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ return Promise.reject(defaultWriterBrandCheckException('write'));
+ }
+
+ if (this._ownerWritableStream === undefined) {
+ return Promise.reject(defaultWriterLockException('write to'));
+ }
+
+ return WritableStreamDefaultWriterWrite(this, chunk);
+ }
+ }, {
+ key: 'closed',
+ get: function get() {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ return Promise.reject(defaultWriterBrandCheckException('closed'));
+ }
+
+ return this._closedPromise;
+ }
+ }, {
+ key: 'desiredSize',
+ get: function get() {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ throw defaultWriterBrandCheckException('desiredSize');
+ }
+
+ if (this._ownerWritableStream === undefined) {
+ throw defaultWriterLockException('desiredSize');
+ }
+
+ return WritableStreamDefaultWriterGetDesiredSize(this);
+ }
+ }, {
+ key: 'ready',
+ get: function get() {
+ if (IsWritableStreamDefaultWriter(this) === false) {
+ return Promise.reject(defaultWriterBrandCheckException('ready'));
+ }
+
+ return this._readyPromise;
+ }
+ }]);
+
+ return WritableStreamDefaultWriter;
+ }();
+
+ function IsWritableStreamDefaultWriter(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function WritableStreamDefaultWriterAbort(writer, reason) {
+ var stream = writer._ownerWritableStream;
+ assert(stream !== undefined);
+ return WritableStreamAbort(stream, reason);
+ }
+
+ function WritableStreamDefaultWriterClose(writer) {
+ var stream = writer._ownerWritableStream;
+ assert(stream !== undefined);
+ var state = stream._state;
+
+ if (state === 'closed' || state === 'errored') {
+ return Promise.reject(new TypeError('The stream (in ' + state + ' state) is not in the writable state and cannot be closed'));
+ }
+
+ assert(state === 'writable' || state === 'erroring');
+ assert(WritableStreamCloseQueuedOrInFlight(stream) === false);
+ var promise = new Promise(function (resolve, reject) {
+ var closeRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+ stream._closeRequest = closeRequest;
+ });
+
+ if (stream._backpressure === true && state === 'writable') {
+ defaultWriterReadyPromiseResolve(writer);
+ }
+
+ WritableStreamDefaultControllerClose(stream._writableStreamController);
+ return promise;
+ }
+
+ function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
+ var stream = writer._ownerWritableStream;
+ assert(stream !== undefined);
+ var state = stream._state;
+
+ if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {
+ return Promise.resolve();
+ }
+
+ if (state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ assert(state === 'writable' || state === 'erroring');
+ return WritableStreamDefaultWriterClose(writer);
+ }
+
+ function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
+ if (writer._closedPromiseState === 'pending') {
+ defaultWriterClosedPromiseReject(writer, error);
+ } else {
+ defaultWriterClosedPromiseResetToRejected(writer, error);
+ }
+
+ writer._closedPromise["catch"](function () {});
+ }
+
+ function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
+ if (writer._readyPromiseState === 'pending') {
+ defaultWriterReadyPromiseReject(writer, error);
+ } else {
+ defaultWriterReadyPromiseResetToRejected(writer, error);
+ }
+
+ writer._readyPromise["catch"](function () {});
+ }
+
+ function WritableStreamDefaultWriterGetDesiredSize(writer) {
+ var stream = writer._ownerWritableStream;
+ var state = stream._state;
+
+ if (state === 'errored' || state === 'erroring') {
+ return null;
+ }
+
+ if (state === 'closed') {
+ return 0;
+ }
+
+ return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
+ }
+
+ function WritableStreamDefaultWriterRelease(writer) {
+ var stream = writer._ownerWritableStream;
+ assert(stream !== undefined);
+ assert(stream._writer === writer);
+ var releasedError = new TypeError('Writer was released and can no longer be used to monitor the stream\'s closedness');
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
+ WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
+ stream._writer = undefined;
+ writer._ownerWritableStream = undefined;
+ }
+
+ function WritableStreamDefaultWriterWrite(writer, chunk) {
+ var stream = writer._ownerWritableStream;
+ assert(stream !== undefined);
+ var controller = stream._writableStreamController;
+ var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
+
+ if (stream !== writer._ownerWritableStream) {
+ return Promise.reject(defaultWriterLockException('write to'));
+ }
+
+ var state = stream._state;
+
+ if (state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {
+ return Promise.reject(new TypeError('The stream is closing or closed and cannot be written to'));
+ }
+
+ if (state === 'erroring') {
+ return Promise.reject(stream._storedError);
+ }
+
+ assert(state === 'writable');
+ var promise = WritableStreamAddWriteRequest(stream);
+ WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
+ return promise;
+ }
+
+ var WritableStreamDefaultController = function () {
+ function WritableStreamDefaultController(stream, underlyingSink, size, highWaterMark) {
+ _classCallCheck(this, WritableStreamDefaultController);
+
+ if (IsWritableStream(stream) === false) {
+ throw new TypeError('WritableStreamDefaultController can only be constructed with a WritableStream instance');
+ }
+
+ if (stream._writableStreamController !== undefined) {
+ throw new TypeError('WritableStreamDefaultController instances can only be created by the WritableStream constructor');
+ }
+
+ this._controlledWritableStream = stream;
+ this._underlyingSink = underlyingSink;
+ this._queue = undefined;
+ this._queueTotalSize = undefined;
+ ResetQueue(this);
+ this._started = false;
+ var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);
+ this._strategySize = normalizedStrategy.size;
+ this._strategyHWM = normalizedStrategy.highWaterMark;
+ var backpressure = WritableStreamDefaultControllerGetBackpressure(this);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ }
+
+ _createClass(WritableStreamDefaultController, [{
+ key: 'error',
+ value: function error(e) {
+ if (IsWritableStreamDefaultController(this) === false) {
+ throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
+ }
+
+ var state = this._controlledWritableStream._state;
+
+ if (state !== 'writable') {
+ return;
+ }
+
+ WritableStreamDefaultControllerError(this, e);
+ }
+ }, {
+ key: '__abortSteps',
+ value: function __abortSteps(reason) {
+ return PromiseInvokeOrNoop(this._underlyingSink, 'abort', [reason]);
+ }
+ }, {
+ key: '__errorSteps',
+ value: function __errorSteps() {
+ ResetQueue(this);
+ }
+ }, {
+ key: '__startSteps',
+ value: function __startSteps() {
+ var _this = this;
+
+ var startResult = InvokeOrNoop(this._underlyingSink, 'start', [this]);
+ var stream = this._controlledWritableStream;
+ Promise.resolve(startResult).then(function () {
+ assert(stream._state === 'writable' || stream._state === 'erroring');
+ _this._started = true;
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(_this);
+ }, function (r) {
+ assert(stream._state === 'writable' || stream._state === 'erroring');
+ _this._started = true;
+ WritableStreamDealWithRejection(stream, r);
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+ }]);
+
+ return WritableStreamDefaultController;
+ }();
+
+ function WritableStreamDefaultControllerClose(controller) {
+ EnqueueValueWithSize(controller, 'close', 0);
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }
+
+ function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
+ var strategySize = controller._strategySize;
+
+ if (strategySize === undefined) {
+ return 1;
+ }
+
+ try {
+ return strategySize(chunk);
+ } catch (chunkSizeE) {
+ WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
+ return 1;
+ }
+ }
+
+ function WritableStreamDefaultControllerGetDesiredSize(controller) {
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+
+ function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
+ var writeRecord = {
+ chunk: chunk
+ };
+
+ try {
+ EnqueueValueWithSize(controller, writeRecord, chunkSize);
+ } catch (enqueueE) {
+ WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
+ return;
+ }
+
+ var stream = controller._controlledWritableStream;
+
+ if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') {
+ var backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ }
+
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }
+
+ function IsWritableStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSink')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
+ var stream = controller._controlledWritableStream;
+
+ if (controller._started === false) {
+ return;
+ }
+
+ if (stream._inFlightWriteRequest !== undefined) {
+ return;
+ }
+
+ var state = stream._state;
+
+ if (state === 'closed' || state === 'errored') {
+ return;
+ }
+
+ if (state === 'erroring') {
+ WritableStreamFinishErroring(stream);
+ return;
+ }
+
+ if (controller._queue.length === 0) {
+ return;
+ }
+
+ var writeRecord = PeekQueueValue(controller);
+
+ if (writeRecord === 'close') {
+ WritableStreamDefaultControllerProcessClose(controller);
+ } else {
+ WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);
+ }
+ }
+
+ function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
+ if (controller._controlledWritableStream._state === 'writable') {
+ WritableStreamDefaultControllerError(controller, error);
+ }
+ }
+
+ function WritableStreamDefaultControllerProcessClose(controller) {
+ var stream = controller._controlledWritableStream;
+ WritableStreamMarkCloseRequestInFlight(stream);
+ DequeueValue(controller);
+ assert(controller._queue.length === 0, 'queue must be empty once the final write record is dequeued');
+ var sinkClosePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'close', []);
+ sinkClosePromise.then(function () {
+ WritableStreamFinishInFlightClose(stream);
+ }, function (reason) {
+ WritableStreamFinishInFlightCloseWithError(stream, reason);
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+
+ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
+ var stream = controller._controlledWritableStream;
+ WritableStreamMarkFirstWriteRequestInFlight(stream);
+ var sinkWritePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'write', [chunk, controller]);
+ sinkWritePromise.then(function () {
+ WritableStreamFinishInFlightWrite(stream);
+ var state = stream._state;
+ assert(state === 'writable' || state === 'erroring');
+ DequeueValue(controller);
+
+ if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') {
+ var backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ }
+
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }, function (reason) {
+ WritableStreamFinishInFlightWriteWithError(stream, reason);
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+
+ function WritableStreamDefaultControllerGetBackpressure(controller) {
+ var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
+ return desiredSize <= 0;
+ }
+
+ function WritableStreamDefaultControllerError(controller, error) {
+ var stream = controller._controlledWritableStream;
+ assert(stream._state === 'writable');
+ WritableStreamStartErroring(stream, error);
+ }
+
+ function streamBrandCheckException(name) {
+ return new TypeError('WritableStream.prototype.' + name + ' can only be used on a WritableStream');
+ }
+
+ function defaultWriterBrandCheckException(name) {
+ return new TypeError('WritableStreamDefaultWriter.prototype.' + name + ' can only be used on a WritableStreamDefaultWriter');
+ }
+
+ function defaultWriterLockException(name) {
+ return new TypeError('Cannot ' + name + ' a stream using a released writer');
+ }
+
+ function defaultWriterClosedPromiseInitialize(writer) {
+ writer._closedPromise = new Promise(function (resolve, reject) {
+ writer._closedPromise_resolve = resolve;
+ writer._closedPromise_reject = reject;
+ writer._closedPromiseState = 'pending';
+ });
+ }
+
+ function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
+ writer._closedPromise = Promise.reject(reason);
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'rejected';
+ }
+
+ function defaultWriterClosedPromiseInitializeAsResolved(writer) {
+ writer._closedPromise = Promise.resolve(undefined);
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'resolved';
+ }
+
+ function defaultWriterClosedPromiseReject(writer, reason) {
+ assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined');
+ assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined');
+ assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending');
+
+ writer._closedPromise_reject(reason);
+
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'rejected';
+ }
+
+ function defaultWriterClosedPromiseResetToRejected(writer, reason) {
+ assert(writer._closedPromise_resolve === undefined, 'writer._closedPromise_resolve === undefined');
+ assert(writer._closedPromise_reject === undefined, 'writer._closedPromise_reject === undefined');
+ assert(writer._closedPromiseState !== 'pending', 'writer._closedPromiseState is not pending');
+ writer._closedPromise = Promise.reject(reason);
+ writer._closedPromiseState = 'rejected';
+ }
+
+ function defaultWriterClosedPromiseResolve(writer) {
+ assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined');
+ assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined');
+ assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending');
+
+ writer._closedPromise_resolve(undefined);
+
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'resolved';
+ }
+
+ function defaultWriterReadyPromiseInitialize(writer) {
+ writer._readyPromise = new Promise(function (resolve, reject) {
+ writer._readyPromise_resolve = resolve;
+ writer._readyPromise_reject = reject;
+ });
+ writer._readyPromiseState = 'pending';
+ }
+
+ function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
+ writer._readyPromise = Promise.reject(reason);
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'rejected';
+ }
+
+ function defaultWriterReadyPromiseInitializeAsResolved(writer) {
+ writer._readyPromise = Promise.resolve(undefined);
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'fulfilled';
+ }
+
+ function defaultWriterReadyPromiseReject(writer, reason) {
+ assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined');
+ assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined');
+
+ writer._readyPromise_reject(reason);
+
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'rejected';
+ }
+
+ function defaultWriterReadyPromiseReset(writer) {
+ assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined');
+ assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined');
+ writer._readyPromise = new Promise(function (resolve, reject) {
+ writer._readyPromise_resolve = resolve;
+ writer._readyPromise_reject = reject;
+ });
+ writer._readyPromiseState = 'pending';
+ }
+
+ function defaultWriterReadyPromiseResetToRejected(writer, reason) {
+ assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined');
+ assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined');
+ writer._readyPromise = Promise.reject(reason);
+ writer._readyPromiseState = 'rejected';
+ }
+
+ function defaultWriterReadyPromiseResolve(writer) {
+ assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined');
+ assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined');
+
+ writer._readyPromise_resolve(undefined);
+
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'fulfilled';
+ }
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var _require = __w_pdfjs_require__(0),
+ IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber;
+
+ var _require2 = __w_pdfjs_require__(1),
+ assert = _require2.assert;
+
+ exports.DequeueValue = function (container) {
+ assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]].');
+ assert(container._queue.length > 0, 'Spec-level failure: should never dequeue from an empty queue.');
+
+ var pair = container._queue.shift();
+
+ container._queueTotalSize -= pair.size;
+
+ if (container._queueTotalSize < 0) {
+ container._queueTotalSize = 0;
+ }
+
+ return pair.value;
+ };
+
+ exports.EnqueueValueWithSize = function (container, value, size) {
+ assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and ' + '[[queueTotalSize]].');
+ size = Number(size);
+
+ if (!IsFiniteNonNegativeNumber(size)) {
+ throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
+ }
+
+ container._queue.push({
+ value: value,
+ size: size
+ });
+
+ container._queueTotalSize += size;
+ };
+
+ exports.PeekQueueValue = function (container) {
+ assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]].');
+ assert(container._queue.length > 0, 'Spec-level failure: should never peek at an empty queue.');
+ var pair = container._queue[0];
+ return pair.value;
+ };
+
+ exports.ResetQueue = function (container) {
+ assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]].');
+ container._queue = [];
+ container._queueTotalSize = 0;
+ };
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var _createClass = function () {
+ function defineProperties(target, props) {
+ for (var i = 0; i < props.length; i++) {
+ var descriptor = props[i];
+ descriptor.enumerable = descriptor.enumerable || false;
+ descriptor.configurable = true;
+ if ("value" in descriptor) descriptor.writable = true;
+ Object.defineProperty(target, descriptor.key, descriptor);
+ }
+ }
+
+ return function (Constructor, protoProps, staticProps) {
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
+ if (staticProps) defineProperties(Constructor, staticProps);
+ return Constructor;
+ };
+ }();
+
+ function _classCallCheck(instance, Constructor) {
+ if (!(instance instanceof Constructor)) {
+ throw new TypeError("Cannot call a class as a function");
+ }
+ }
+
+ var _require = __w_pdfjs_require__(0),
+ ArrayBufferCopy = _require.ArrayBufferCopy,
+ CreateIterResultObject = _require.CreateIterResultObject,
+ IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber,
+ InvokeOrNoop = _require.InvokeOrNoop,
+ PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop,
+ TransferArrayBuffer = _require.TransferArrayBuffer,
+ ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy,
+ ValidateAndNormalizeHighWaterMark = _require.ValidateAndNormalizeHighWaterMark;
+
+ var _require2 = __w_pdfjs_require__(0),
+ createArrayFromList = _require2.createArrayFromList,
+ createDataProperty = _require2.createDataProperty,
+ typeIsObject = _require2.typeIsObject;
+
+ var _require3 = __w_pdfjs_require__(1),
+ assert = _require3.assert,
+ rethrowAssertionErrorRejection = _require3.rethrowAssertionErrorRejection;
+
+ var _require4 = __w_pdfjs_require__(3),
+ DequeueValue = _require4.DequeueValue,
+ EnqueueValueWithSize = _require4.EnqueueValueWithSize,
+ ResetQueue = _require4.ResetQueue;
+
+ var _require5 = __w_pdfjs_require__(2),
+ AcquireWritableStreamDefaultWriter = _require5.AcquireWritableStreamDefaultWriter,
+ IsWritableStream = _require5.IsWritableStream,
+ IsWritableStreamLocked = _require5.IsWritableStreamLocked,
+ WritableStreamAbort = _require5.WritableStreamAbort,
+ WritableStreamDefaultWriterCloseWithErrorPropagation = _require5.WritableStreamDefaultWriterCloseWithErrorPropagation,
+ WritableStreamDefaultWriterRelease = _require5.WritableStreamDefaultWriterRelease,
+ WritableStreamDefaultWriterWrite = _require5.WritableStreamDefaultWriterWrite,
+ WritableStreamCloseQueuedOrInFlight = _require5.WritableStreamCloseQueuedOrInFlight;
+
+ var ReadableStream = function () {
+ function ReadableStream() {
+ var underlyingSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ size = _ref.size,
+ highWaterMark = _ref.highWaterMark;
+
+ _classCallCheck(this, ReadableStream);
+
+ this._state = 'readable';
+ this._reader = undefined;
+ this._storedError = undefined;
+ this._disturbed = false;
+ this._readableStreamController = undefined;
+ var type = underlyingSource.type;
+ var typeString = String(type);
+
+ if (typeString === 'bytes') {
+ if (highWaterMark === undefined) {
+ highWaterMark = 0;
+ }
+
+ this._readableStreamController = new ReadableByteStreamController(this, underlyingSource, highWaterMark);
+ } else if (type === undefined) {
+ if (highWaterMark === undefined) {
+ highWaterMark = 1;
+ }
+
+ this._readableStreamController = new ReadableStreamDefaultController(this, underlyingSource, size, highWaterMark);
+ } else {
+ throw new RangeError('Invalid type is specified');
+ }
+ }
+
+ _createClass(ReadableStream, [{
+ key: 'cancel',
+ value: function cancel(reason) {
+ if (IsReadableStream(this) === false) {
+ return Promise.reject(streamBrandCheckException('cancel'));
+ }
+
+ if (IsReadableStreamLocked(this) === true) {
+ return Promise.reject(new TypeError('Cannot cancel a stream that already has a reader'));
+ }
+
+ return ReadableStreamCancel(this, reason);
+ }
+ }, {
+ key: 'getReader',
+ value: function getReader() {
+ var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ mode = _ref2.mode;
+
+ if (IsReadableStream(this) === false) {
+ throw streamBrandCheckException('getReader');
+ }
+
+ if (mode === undefined) {
+ return AcquireReadableStreamDefaultReader(this);
+ }
+
+ mode = String(mode);
+
+ if (mode === 'byob') {
+ return AcquireReadableStreamBYOBReader(this);
+ }
+
+ throw new RangeError('Invalid mode is specified');
+ }
+ }, {
+ key: 'pipeThrough',
+ value: function pipeThrough(_ref3, options) {
+ var writable = _ref3.writable,
+ readable = _ref3.readable;
+ var promise = this.pipeTo(writable, options);
+ ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);
+ return readable;
+ }
+ }, {
+ key: 'pipeTo',
+ value: function pipeTo(dest) {
+ var _this = this;
+
+ var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ preventClose = _ref4.preventClose,
+ preventAbort = _ref4.preventAbort,
+ preventCancel = _ref4.preventCancel;
+
+ if (IsReadableStream(this) === false) {
+ return Promise.reject(streamBrandCheckException('pipeTo'));
+ }
+
+ if (IsWritableStream(dest) === false) {
+ return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo\'s first argument must be a WritableStream'));
+ }
+
+ preventClose = Boolean(preventClose);
+ preventAbort = Boolean(preventAbort);
+ preventCancel = Boolean(preventCancel);
+
+ if (IsReadableStreamLocked(this) === true) {
+ return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
+ }
+
+ if (IsWritableStreamLocked(dest) === true) {
+ return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
+ }
+
+ var reader = AcquireReadableStreamDefaultReader(this);
+ var writer = AcquireWritableStreamDefaultWriter(dest);
+ var shuttingDown = false;
+ var currentWrite = Promise.resolve();
+ return new Promise(function (resolve, reject) {
+ function pipeLoop() {
+ currentWrite = Promise.resolve();
+
+ if (shuttingDown === true) {
+ return Promise.resolve();
+ }
+
+ return writer._readyPromise.then(function () {
+ return ReadableStreamDefaultReaderRead(reader).then(function (_ref5) {
+ var value = _ref5.value,
+ done = _ref5.done;
+
+ if (done === true) {
+ return;
+ }
+
+ currentWrite = WritableStreamDefaultWriterWrite(writer, value)["catch"](function () {});
+ });
+ }).then(pipeLoop);
+ }
+
+ isOrBecomesErrored(_this, reader._closedPromise, function (storedError) {
+ if (preventAbort === false) {
+ shutdownWithAction(function () {
+ return WritableStreamAbort(dest, storedError);
+ }, true, storedError);
+ } else {
+ shutdown(true, storedError);
+ }
+ });
+ isOrBecomesErrored(dest, writer._closedPromise, function (storedError) {
+ if (preventCancel === false) {
+ shutdownWithAction(function () {
+ return ReadableStreamCancel(_this, storedError);
+ }, true, storedError);
+ } else {
+ shutdown(true, storedError);
+ }
+ });
+ isOrBecomesClosed(_this, reader._closedPromise, function () {
+ if (preventClose === false) {
+ shutdownWithAction(function () {
+ return WritableStreamDefaultWriterCloseWithErrorPropagation(writer);
+ });
+ } else {
+ shutdown();
+ }
+ });
+
+ if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') {
+ var destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
+
+ if (preventCancel === false) {
+ shutdownWithAction(function () {
+ return ReadableStreamCancel(_this, destClosed);
+ }, true, destClosed);
+ } else {
+ shutdown(true, destClosed);
+ }
+ }
+
+ pipeLoop()["catch"](function (err) {
+ currentWrite = Promise.resolve();
+ rethrowAssertionErrorRejection(err);
+ });
+
+ function waitForWritesToFinish() {
+ var oldCurrentWrite = currentWrite;
+ return currentWrite.then(function () {
+ return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined;
+ });
+ }
+
+ function isOrBecomesErrored(stream, promise, action) {
+ if (stream._state === 'errored') {
+ action(stream._storedError);
+ } else {
+ promise["catch"](action)["catch"](rethrowAssertionErrorRejection);
+ }
+ }
+
+ function isOrBecomesClosed(stream, promise, action) {
+ if (stream._state === 'closed') {
+ action();
+ } else {
+ promise.then(action)["catch"](rethrowAssertionErrorRejection);
+ }
+ }
+
+ function shutdownWithAction(action, originalIsError, originalError) {
+ if (shuttingDown === true) {
+ return;
+ }
+
+ shuttingDown = true;
+
+ if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
+ waitForWritesToFinish().then(doTheRest);
+ } else {
+ doTheRest();
+ }
+
+ function doTheRest() {
+ action().then(function () {
+ return finalize(originalIsError, originalError);
+ }, function (newError) {
+ return finalize(true, newError);
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+ }
+
+ function shutdown(isError, error) {
+ if (shuttingDown === true) {
+ return;
+ }
+
+ shuttingDown = true;
+
+ if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
+ waitForWritesToFinish().then(function () {
+ return finalize(isError, error);
+ })["catch"](rethrowAssertionErrorRejection);
+ } else {
+ finalize(isError, error);
+ }
+ }
+
+ function finalize(isError, error) {
+ WritableStreamDefaultWriterRelease(writer);
+ ReadableStreamReaderGenericRelease(reader);
+
+ if (isError) {
+ reject(error);
+ } else {
+ resolve(undefined);
+ }
+ }
+ });
+ }
+ }, {
+ key: 'tee',
+ value: function tee() {
+ if (IsReadableStream(this) === false) {
+ throw streamBrandCheckException('tee');
+ }
+
+ var branches = ReadableStreamTee(this, false);
+ return createArrayFromList(branches);
+ }
+ }, {
+ key: 'locked',
+ get: function get() {
+ if (IsReadableStream(this) === false) {
+ throw streamBrandCheckException('locked');
+ }
+
+ return IsReadableStreamLocked(this);
+ }
+ }]);
+
+ return ReadableStream;
+ }();
+
+ module.exports = {
+ ReadableStream: ReadableStream,
+ IsReadableStreamDisturbed: IsReadableStreamDisturbed,
+ ReadableStreamDefaultControllerClose: ReadableStreamDefaultControllerClose,
+ ReadableStreamDefaultControllerEnqueue: ReadableStreamDefaultControllerEnqueue,
+ ReadableStreamDefaultControllerError: ReadableStreamDefaultControllerError,
+ ReadableStreamDefaultControllerGetDesiredSize: ReadableStreamDefaultControllerGetDesiredSize
+ };
+
+ function AcquireReadableStreamBYOBReader(stream) {
+ return new ReadableStreamBYOBReader(stream);
+ }
+
+ function AcquireReadableStreamDefaultReader(stream) {
+ return new ReadableStreamDefaultReader(stream);
+ }
+
+ function IsReadableStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function IsReadableStreamDisturbed(stream) {
+ assert(IsReadableStream(stream) === true, 'IsReadableStreamDisturbed should only be used on known readable streams');
+ return stream._disturbed;
+ }
+
+ function IsReadableStreamLocked(stream) {
+ assert(IsReadableStream(stream) === true, 'IsReadableStreamLocked should only be used on known readable streams');
+
+ if (stream._reader === undefined) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function ReadableStreamTee(stream, cloneForBranch2) {
+ assert(IsReadableStream(stream) === true);
+ assert(typeof cloneForBranch2 === 'boolean');
+ var reader = AcquireReadableStreamDefaultReader(stream);
+ var teeState = {
+ closedOrErrored: false,
+ canceled1: false,
+ canceled2: false,
+ reason1: undefined,
+ reason2: undefined
+ };
+ teeState.promise = new Promise(function (resolve) {
+ teeState._resolve = resolve;
+ });
+ var pull = create_ReadableStreamTeePullFunction();
+ pull._reader = reader;
+ pull._teeState = teeState;
+ pull._cloneForBranch2 = cloneForBranch2;
+ var cancel1 = create_ReadableStreamTeeBranch1CancelFunction();
+ cancel1._stream = stream;
+ cancel1._teeState = teeState;
+ var cancel2 = create_ReadableStreamTeeBranch2CancelFunction();
+ cancel2._stream = stream;
+ cancel2._teeState = teeState;
+ var underlyingSource1 = Object.create(Object.prototype);
+ createDataProperty(underlyingSource1, 'pull', pull);
+ createDataProperty(underlyingSource1, 'cancel', cancel1);
+ var branch1Stream = new ReadableStream(underlyingSource1);
+ var underlyingSource2 = Object.create(Object.prototype);
+ createDataProperty(underlyingSource2, 'pull', pull);
+ createDataProperty(underlyingSource2, 'cancel', cancel2);
+ var branch2Stream = new ReadableStream(underlyingSource2);
+ pull._branch1 = branch1Stream._readableStreamController;
+ pull._branch2 = branch2Stream._readableStreamController;
+
+ reader._closedPromise["catch"](function (r) {
+ if (teeState.closedOrErrored === true) {
+ return;
+ }
+
+ ReadableStreamDefaultControllerError(pull._branch1, r);
+ ReadableStreamDefaultControllerError(pull._branch2, r);
+ teeState.closedOrErrored = true;
+ });
+
+ return [branch1Stream, branch2Stream];
+ }
+
+ function create_ReadableStreamTeePullFunction() {
+ function f() {
+ var reader = f._reader,
+ branch1 = f._branch1,
+ branch2 = f._branch2,
+ teeState = f._teeState;
+ return ReadableStreamDefaultReaderRead(reader).then(function (result) {
+ assert(typeIsObject(result));
+ var value = result.value;
+ var done = result.done;
+ assert(typeof done === 'boolean');
+
+ if (done === true && teeState.closedOrErrored === false) {
+ if (teeState.canceled1 === false) {
+ ReadableStreamDefaultControllerClose(branch1);
+ }
+
+ if (teeState.canceled2 === false) {
+ ReadableStreamDefaultControllerClose(branch2);
+ }
+
+ teeState.closedOrErrored = true;
+ }
+
+ if (teeState.closedOrErrored === true) {
+ return;
+ }
+
+ var value1 = value;
+ var value2 = value;
+
+ if (teeState.canceled1 === false) {
+ ReadableStreamDefaultControllerEnqueue(branch1, value1);
+ }
+
+ if (teeState.canceled2 === false) {
+ ReadableStreamDefaultControllerEnqueue(branch2, value2);
+ }
+ });
+ }
+
+ return f;
+ }
+
+ function create_ReadableStreamTeeBranch1CancelFunction() {
+ function f(reason) {
+ var stream = f._stream,
+ teeState = f._teeState;
+ teeState.canceled1 = true;
+ teeState.reason1 = reason;
+
+ if (teeState.canceled2 === true) {
+ var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);
+ var cancelResult = ReadableStreamCancel(stream, compositeReason);
+
+ teeState._resolve(cancelResult);
+ }
+
+ return teeState.promise;
+ }
+
+ return f;
+ }
+
+ function create_ReadableStreamTeeBranch2CancelFunction() {
+ function f(reason) {
+ var stream = f._stream,
+ teeState = f._teeState;
+ teeState.canceled2 = true;
+ teeState.reason2 = reason;
+
+ if (teeState.canceled1 === true) {
+ var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);
+ var cancelResult = ReadableStreamCancel(stream, compositeReason);
+
+ teeState._resolve(cancelResult);
+ }
+
+ return teeState.promise;
+ }
+
+ return f;
+ }
+
+ function ReadableStreamAddReadIntoRequest(stream) {
+ assert(IsReadableStreamBYOBReader(stream._reader) === true);
+ assert(stream._state === 'readable' || stream._state === 'closed');
+ var promise = new Promise(function (resolve, reject) {
+ var readIntoRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+
+ stream._reader._readIntoRequests.push(readIntoRequest);
+ });
+ return promise;
+ }
+
+ function ReadableStreamAddReadRequest(stream) {
+ assert(IsReadableStreamDefaultReader(stream._reader) === true);
+ assert(stream._state === 'readable');
+ var promise = new Promise(function (resolve, reject) {
+ var readRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+
+ stream._reader._readRequests.push(readRequest);
+ });
+ return promise;
+ }
+
+ function ReadableStreamCancel(stream, reason) {
+ stream._disturbed = true;
+
+ if (stream._state === 'closed') {
+ return Promise.resolve(undefined);
+ }
+
+ if (stream._state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ ReadableStreamClose(stream);
+
+ var sourceCancelPromise = stream._readableStreamController.__cancelSteps(reason);
+
+ return sourceCancelPromise.then(function () {
+ return undefined;
+ });
+ }
+
+ function ReadableStreamClose(stream) {
+ assert(stream._state === 'readable');
+ stream._state = 'closed';
+ var reader = stream._reader;
+
+ if (reader === undefined) {
+ return undefined;
+ }
+
+ if (IsReadableStreamDefaultReader(reader) === true) {
+ for (var i = 0; i < reader._readRequests.length; i++) {
+ var _resolve = reader._readRequests[i]._resolve;
+
+ _resolve(CreateIterResultObject(undefined, true));
+ }
+
+ reader._readRequests = [];
+ }
+
+ defaultReaderClosedPromiseResolve(reader);
+ return undefined;
+ }
+
+ function ReadableStreamError(stream, e) {
+ assert(IsReadableStream(stream) === true, 'stream must be ReadableStream');
+ assert(stream._state === 'readable', 'state must be readable');
+ stream._state = 'errored';
+ stream._storedError = e;
+ var reader = stream._reader;
+
+ if (reader === undefined) {
+ return undefined;
+ }
+
+ if (IsReadableStreamDefaultReader(reader) === true) {
+ for (var i = 0; i < reader._readRequests.length; i++) {
+ var readRequest = reader._readRequests[i];
+
+ readRequest._reject(e);
+ }
+
+ reader._readRequests = [];
+ } else {
+ assert(IsReadableStreamBYOBReader(reader), 'reader must be ReadableStreamBYOBReader');
+
+ for (var _i = 0; _i < reader._readIntoRequests.length; _i++) {
+ var readIntoRequest = reader._readIntoRequests[_i];
+
+ readIntoRequest._reject(e);
+ }
+
+ reader._readIntoRequests = [];
+ }
+
+ defaultReaderClosedPromiseReject(reader, e);
+
+ reader._closedPromise["catch"](function () {});
+ }
+
+ function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
+ var reader = stream._reader;
+ assert(reader._readIntoRequests.length > 0);
+
+ var readIntoRequest = reader._readIntoRequests.shift();
+
+ readIntoRequest._resolve(CreateIterResultObject(chunk, done));
+ }
+
+ function ReadableStreamFulfillReadRequest(stream, chunk, done) {
+ var reader = stream._reader;
+ assert(reader._readRequests.length > 0);
+
+ var readRequest = reader._readRequests.shift();
+
+ readRequest._resolve(CreateIterResultObject(chunk, done));
+ }
+
+ function ReadableStreamGetNumReadIntoRequests(stream) {
+ return stream._reader._readIntoRequests.length;
+ }
+
+ function ReadableStreamGetNumReadRequests(stream) {
+ return stream._reader._readRequests.length;
+ }
+
+ function ReadableStreamHasBYOBReader(stream) {
+ var reader = stream._reader;
+
+ if (reader === undefined) {
+ return false;
+ }
+
+ if (IsReadableStreamBYOBReader(reader) === false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function ReadableStreamHasDefaultReader(stream) {
+ var reader = stream._reader;
+
+ if (reader === undefined) {
+ return false;
+ }
+
+ if (IsReadableStreamDefaultReader(reader) === false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ var ReadableStreamDefaultReader = function () {
+ function ReadableStreamDefaultReader(stream) {
+ _classCallCheck(this, ReadableStreamDefaultReader);
+
+ if (IsReadableStream(stream) === false) {
+ throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance');
+ }
+
+ if (IsReadableStreamLocked(stream) === true) {
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
+ }
+
+ ReadableStreamReaderGenericInitialize(this, stream);
+ this._readRequests = [];
+ }
+
+ _createClass(ReadableStreamDefaultReader, [{
+ key: 'cancel',
+ value: function cancel(reason) {
+ if (IsReadableStreamDefaultReader(this) === false) {
+ return Promise.reject(defaultReaderBrandCheckException('cancel'));
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return Promise.reject(readerLockException('cancel'));
+ }
+
+ return ReadableStreamReaderGenericCancel(this, reason);
+ }
+ }, {
+ key: 'read',
+ value: function read() {
+ if (IsReadableStreamDefaultReader(this) === false) {
+ return Promise.reject(defaultReaderBrandCheckException('read'));
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return Promise.reject(readerLockException('read from'));
+ }
+
+ return ReadableStreamDefaultReaderRead(this);
+ }
+ }, {
+ key: 'releaseLock',
+ value: function releaseLock() {
+ if (IsReadableStreamDefaultReader(this) === false) {
+ throw defaultReaderBrandCheckException('releaseLock');
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return;
+ }
+
+ if (this._readRequests.length > 0) {
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
+ }
+
+ ReadableStreamReaderGenericRelease(this);
+ }
+ }, {
+ key: 'closed',
+ get: function get() {
+ if (IsReadableStreamDefaultReader(this) === false) {
+ return Promise.reject(defaultReaderBrandCheckException('closed'));
+ }
+
+ return this._closedPromise;
+ }
+ }]);
+
+ return ReadableStreamDefaultReader;
+ }();
+
+ var ReadableStreamBYOBReader = function () {
+ function ReadableStreamBYOBReader(stream) {
+ _classCallCheck(this, ReadableStreamBYOBReader);
+
+ if (!IsReadableStream(stream)) {
+ throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' + 'byte source');
+ }
+
+ if (IsReadableByteStreamController(stream._readableStreamController) === false) {
+ throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + 'source');
+ }
+
+ if (IsReadableStreamLocked(stream)) {
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
+ }
+
+ ReadableStreamReaderGenericInitialize(this, stream);
+ this._readIntoRequests = [];
+ }
+
+ _createClass(ReadableStreamBYOBReader, [{
+ key: 'cancel',
+ value: function cancel(reason) {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return Promise.reject(byobReaderBrandCheckException('cancel'));
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return Promise.reject(readerLockException('cancel'));
+ }
+
+ return ReadableStreamReaderGenericCancel(this, reason);
+ }
+ }, {
+ key: 'read',
+ value: function read(view) {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return Promise.reject(byobReaderBrandCheckException('read'));
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return Promise.reject(readerLockException('read from'));
+ }
+
+ if (!ArrayBuffer.isView(view)) {
+ return Promise.reject(new TypeError('view must be an array buffer view'));
+ }
+
+ if (view.byteLength === 0) {
+ return Promise.reject(new TypeError('view must have non-zero byteLength'));
+ }
+
+ return ReadableStreamBYOBReaderRead(this, view);
+ }
+ }, {
+ key: 'releaseLock',
+ value: function releaseLock() {
+ if (!IsReadableStreamBYOBReader(this)) {
+ throw byobReaderBrandCheckException('releaseLock');
+ }
+
+ if (this._ownerReadableStream === undefined) {
+ return;
+ }
+
+ if (this._readIntoRequests.length > 0) {
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
+ }
+
+ ReadableStreamReaderGenericRelease(this);
+ }
+ }, {
+ key: 'closed',
+ get: function get() {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return Promise.reject(byobReaderBrandCheckException('closed'));
+ }
+
+ return this._closedPromise;
+ }
+ }]);
+
+ return ReadableStreamBYOBReader;
+ }();
+
+ function IsReadableStreamBYOBReader(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function IsReadableStreamDefaultReader(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function ReadableStreamReaderGenericInitialize(reader, stream) {
+ reader._ownerReadableStream = stream;
+ stream._reader = reader;
+
+ if (stream._state === 'readable') {
+ defaultReaderClosedPromiseInitialize(reader);
+ } else if (stream._state === 'closed') {
+ defaultReaderClosedPromiseInitializeAsResolved(reader);
+ } else {
+ assert(stream._state === 'errored', 'state must be errored');
+ defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
+
+ reader._closedPromise["catch"](function () {});
+ }
+ }
+
+ function ReadableStreamReaderGenericCancel(reader, reason) {
+ var stream = reader._ownerReadableStream;
+ assert(stream !== undefined);
+ return ReadableStreamCancel(stream, reason);
+ }
+
+ function ReadableStreamReaderGenericRelease(reader) {
+ assert(reader._ownerReadableStream !== undefined);
+ assert(reader._ownerReadableStream._reader === reader);
+
+ if (reader._ownerReadableStream._state === 'readable') {
+ defaultReaderClosedPromiseReject(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
+ } else {
+ defaultReaderClosedPromiseResetToRejected(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
+ }
+
+ reader._closedPromise["catch"](function () {});
+
+ reader._ownerReadableStream._reader = undefined;
+ reader._ownerReadableStream = undefined;
+ }
+
+ function ReadableStreamBYOBReaderRead(reader, view) {
+ var stream = reader._ownerReadableStream;
+ assert(stream !== undefined);
+ stream._disturbed = true;
+
+ if (stream._state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);
+ }
+
+ function ReadableStreamDefaultReaderRead(reader) {
+ var stream = reader._ownerReadableStream;
+ assert(stream !== undefined);
+ stream._disturbed = true;
+
+ if (stream._state === 'closed') {
+ return Promise.resolve(CreateIterResultObject(undefined, true));
+ }
+
+ if (stream._state === 'errored') {
+ return Promise.reject(stream._storedError);
+ }
+
+ assert(stream._state === 'readable');
+ return stream._readableStreamController.__pullSteps();
+ }
+
+ var ReadableStreamDefaultController = function () {
+ function ReadableStreamDefaultController(stream, underlyingSource, size, highWaterMark) {
+ _classCallCheck(this, ReadableStreamDefaultController);
+
+ if (IsReadableStream(stream) === false) {
+ throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance');
+ }
+
+ if (stream._readableStreamController !== undefined) {
+ throw new TypeError('ReadableStreamDefaultController instances can only be created by the ReadableStream constructor');
+ }
+
+ this._controlledReadableStream = stream;
+ this._underlyingSource = underlyingSource;
+ this._queue = undefined;
+ this._queueTotalSize = undefined;
+ ResetQueue(this);
+ this._started = false;
+ this._closeRequested = false;
+ this._pullAgain = false;
+ this._pulling = false;
+ var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);
+ this._strategySize = normalizedStrategy.size;
+ this._strategyHWM = normalizedStrategy.highWaterMark;
+ var controller = this;
+ var startResult = InvokeOrNoop(underlyingSource, 'start', [this]);
+ Promise.resolve(startResult).then(function () {
+ controller._started = true;
+ assert(controller._pulling === false);
+ assert(controller._pullAgain === false);
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ }, function (r) {
+ ReadableStreamDefaultControllerErrorIfNeeded(controller, r);
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+
+ _createClass(ReadableStreamDefaultController, [{
+ key: 'close',
+ value: function close() {
+ if (IsReadableStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('close');
+ }
+
+ if (this._closeRequested === true) {
+ throw new TypeError('The stream has already been closed; do not close it again!');
+ }
+
+ var state = this._controlledReadableStream._state;
+
+ if (state !== 'readable') {
+ throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed');
+ }
+
+ ReadableStreamDefaultControllerClose(this);
+ }
+ }, {
+ key: 'enqueue',
+ value: function enqueue(chunk) {
+ if (IsReadableStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('enqueue');
+ }
+
+ if (this._closeRequested === true) {
+ throw new TypeError('stream is closed or draining');
+ }
+
+ var state = this._controlledReadableStream._state;
+
+ if (state !== 'readable') {
+ throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to');
+ }
+
+ return ReadableStreamDefaultControllerEnqueue(this, chunk);
+ }
+ }, {
+ key: 'error',
+ value: function error(e) {
+ if (IsReadableStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('error');
+ }
+
+ var stream = this._controlledReadableStream;
+
+ if (stream._state !== 'readable') {
+ throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored');
+ }
+
+ ReadableStreamDefaultControllerError(this, e);
+ }
+ }, {
+ key: '__cancelSteps',
+ value: function __cancelSteps(reason) {
+ ResetQueue(this);
+ return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]);
+ }
+ }, {
+ key: '__pullSteps',
+ value: function __pullSteps() {
+ var stream = this._controlledReadableStream;
+
+ if (this._queue.length > 0) {
+ var chunk = DequeueValue(this);
+
+ if (this._closeRequested === true && this._queue.length === 0) {
+ ReadableStreamClose(stream);
+ } else {
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
+ }
+
+ return Promise.resolve(CreateIterResultObject(chunk, false));
+ }
+
+ var pendingPromise = ReadableStreamAddReadRequest(stream);
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
+ return pendingPromise;
+ }
+ }, {
+ key: 'desiredSize',
+ get: function get() {
+ if (IsReadableStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('desiredSize');
+ }
+
+ return ReadableStreamDefaultControllerGetDesiredSize(this);
+ }
+ }]);
+
+ return ReadableStreamDefaultController;
+ }();
+
+ function IsReadableStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
+ var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
+
+ if (shouldPull === false) {
+ return undefined;
+ }
+
+ if (controller._pulling === true) {
+ controller._pullAgain = true;
+ return undefined;
+ }
+
+ assert(controller._pullAgain === false);
+ controller._pulling = true;
+ var pullPromise = PromiseInvokeOrNoop(controller._underlyingSource, 'pull', [controller]);
+ pullPromise.then(function () {
+ controller._pulling = false;
+
+ if (controller._pullAgain === true) {
+ controller._pullAgain = false;
+ return ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ }
+
+ return undefined;
+ }, function (e) {
+ ReadableStreamDefaultControllerErrorIfNeeded(controller, e);
+ })["catch"](rethrowAssertionErrorRejection);
+ return undefined;
+ }
+
+ function ReadableStreamDefaultControllerShouldCallPull(controller) {
+ var stream = controller._controlledReadableStream;
+
+ if (stream._state === 'closed' || stream._state === 'errored') {
+ return false;
+ }
+
+ if (controller._closeRequested === true) {
+ return false;
+ }
+
+ if (controller._started === false) {
+ return false;
+ }
+
+ if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
+ return true;
+ }
+
+ var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
+
+ if (desiredSize > 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ function ReadableStreamDefaultControllerClose(controller) {
+ var stream = controller._controlledReadableStream;
+ assert(controller._closeRequested === false);
+ assert(stream._state === 'readable');
+ controller._closeRequested = true;
+
+ if (controller._queue.length === 0) {
+ ReadableStreamClose(stream);
+ }
+ }
+
+ function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
+ var stream = controller._controlledReadableStream;
+ assert(controller._closeRequested === false);
+ assert(stream._state === 'readable');
+
+ if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
+ ReadableStreamFulfillReadRequest(stream, chunk, false);
+ } else {
+ var chunkSize = 1;
+
+ if (controller._strategySize !== undefined) {
+ var strategySize = controller._strategySize;
+
+ try {
+ chunkSize = strategySize(chunk);
+ } catch (chunkSizeE) {
+ ReadableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
+ throw chunkSizeE;
+ }
+ }
+
+ try {
+ EnqueueValueWithSize(controller, chunk, chunkSize);
+ } catch (enqueueE) {
+ ReadableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
+ throw enqueueE;
+ }
+ }
+
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ return undefined;
+ }
+
+ function ReadableStreamDefaultControllerError(controller, e) {
+ var stream = controller._controlledReadableStream;
+ assert(stream._state === 'readable');
+ ResetQueue(controller);
+ ReadableStreamError(stream, e);
+ }
+
+ function ReadableStreamDefaultControllerErrorIfNeeded(controller, e) {
+ if (controller._controlledReadableStream._state === 'readable') {
+ ReadableStreamDefaultControllerError(controller, e);
+ }
+ }
+
+ function ReadableStreamDefaultControllerGetDesiredSize(controller) {
+ var stream = controller._controlledReadableStream;
+ var state = stream._state;
+
+ if (state === 'errored') {
+ return null;
+ }
+
+ if (state === 'closed') {
+ return 0;
+ }
+
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+
+ var ReadableStreamBYOBRequest = function () {
+ function ReadableStreamBYOBRequest(controller, view) {
+ _classCallCheck(this, ReadableStreamBYOBRequest);
+
+ this._associatedReadableByteStreamController = controller;
+ this._view = view;
+ }
+
+ _createClass(ReadableStreamBYOBRequest, [{
+ key: 'respond',
+ value: function respond(bytesWritten) {
+ if (IsReadableStreamBYOBRequest(this) === false) {
+ throw byobRequestBrandCheckException('respond');
+ }
+
+ if (this._associatedReadableByteStreamController === undefined) {
+ throw new TypeError('This BYOB request has been invalidated');
+ }
+
+ ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
+ }
+ }, {
+ key: 'respondWithNewView',
+ value: function respondWithNewView(view) {
+ if (IsReadableStreamBYOBRequest(this) === false) {
+ throw byobRequestBrandCheckException('respond');
+ }
+
+ if (this._associatedReadableByteStreamController === undefined) {
+ throw new TypeError('This BYOB request has been invalidated');
+ }
+
+ if (!ArrayBuffer.isView(view)) {
+ throw new TypeError('You can only respond with array buffer views');
+ }
+
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
+ }
+ }, {
+ key: 'view',
+ get: function get() {
+ return this._view;
+ }
+ }]);
+
+ return ReadableStreamBYOBRequest;
+ }();
+
+ var ReadableByteStreamController = function () {
+ function ReadableByteStreamController(stream, underlyingByteSource, highWaterMark) {
+ _classCallCheck(this, ReadableByteStreamController);
+
+ if (IsReadableStream(stream) === false) {
+ throw new TypeError('ReadableByteStreamController can only be constructed with a ReadableStream instance given ' + 'a byte source');
+ }
+
+ if (stream._readableStreamController !== undefined) {
+ throw new TypeError('ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte ' + 'source');
+ }
+
+ this._controlledReadableStream = stream;
+ this._underlyingByteSource = underlyingByteSource;
+ this._pullAgain = false;
+ this._pulling = false;
+ ReadableByteStreamControllerClearPendingPullIntos(this);
+ this._queue = this._queueTotalSize = undefined;
+ ResetQueue(this);
+ this._closeRequested = false;
+ this._started = false;
+ this._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark);
+ var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
+
+ if (autoAllocateChunkSize !== undefined) {
+ if (Number.isInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) {
+ throw new RangeError('autoAllocateChunkSize must be a positive integer');
+ }
+ }
+
+ this._autoAllocateChunkSize = autoAllocateChunkSize;
+ this._pendingPullIntos = [];
+ var controller = this;
+ var startResult = InvokeOrNoop(underlyingByteSource, 'start', [this]);
+ Promise.resolve(startResult).then(function () {
+ controller._started = true;
+ assert(controller._pulling === false);
+ assert(controller._pullAgain === false);
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }, function (r) {
+ if (stream._state === 'readable') {
+ ReadableByteStreamControllerError(controller, r);
+ }
+ })["catch"](rethrowAssertionErrorRejection);
+ }
+
+ _createClass(ReadableByteStreamController, [{
+ key: 'close',
+ value: function close() {
+ if (IsReadableByteStreamController(this) === false) {
+ throw byteStreamControllerBrandCheckException('close');
+ }
+
+ if (this._closeRequested === true) {
+ throw new TypeError('The stream has already been closed; do not close it again!');
+ }
+
+ var state = this._controlledReadableStream._state;
+
+ if (state !== 'readable') {
+ throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed');
+ }
+
+ ReadableByteStreamControllerClose(this);
+ }
+ }, {
+ key: 'enqueue',
+ value: function enqueue(chunk) {
+ if (IsReadableByteStreamController(this) === false) {
+ throw byteStreamControllerBrandCheckException('enqueue');
+ }
+
+ if (this._closeRequested === true) {
+ throw new TypeError('stream is closed or draining');
+ }
+
+ var state = this._controlledReadableStream._state;
+
+ if (state !== 'readable') {
+ throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to');
+ }
+
+ if (!ArrayBuffer.isView(chunk)) {
+ throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');
+ }
+
+ ReadableByteStreamControllerEnqueue(this, chunk);
+ }
+ }, {
+ key: 'error',
+ value: function error(e) {
+ if (IsReadableByteStreamController(this) === false) {
+ throw byteStreamControllerBrandCheckException('error');
+ }
+
+ var stream = this._controlledReadableStream;
+
+ if (stream._state !== 'readable') {
+ throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored');
+ }
+
+ ReadableByteStreamControllerError(this, e);
+ }
+ }, {
+ key: '__cancelSteps',
+ value: function __cancelSteps(reason) {
+ if (this._pendingPullIntos.length > 0) {
+ var firstDescriptor = this._pendingPullIntos[0];
+ firstDescriptor.bytesFilled = 0;
+ }
+
+ ResetQueue(this);
+ return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]);
+ }
+ }, {
+ key: '__pullSteps',
+ value: function __pullSteps() {
+ var stream = this._controlledReadableStream;
+ assert(ReadableStreamHasDefaultReader(stream) === true);
+
+ if (this._queueTotalSize > 0) {
+ assert(ReadableStreamGetNumReadRequests(stream) === 0);
+
+ var entry = this._queue.shift();
+
+ this._queueTotalSize -= entry.byteLength;
+ ReadableByteStreamControllerHandleQueueDrain(this);
+ var view = void 0;
+
+ try {
+ view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
+ } catch (viewE) {
+ return Promise.reject(viewE);
+ }
+
+ return Promise.resolve(CreateIterResultObject(view, false));
+ }
+
+ var autoAllocateChunkSize = this._autoAllocateChunkSize;
+
+ if (autoAllocateChunkSize !== undefined) {
+ var buffer = void 0;
+
+ try {
+ buffer = new ArrayBuffer(autoAllocateChunkSize);
+ } catch (bufferE) {
+ return Promise.reject(bufferE);
+ }
+
+ var pullIntoDescriptor = {
+ buffer: buffer,
+ byteOffset: 0,
+ byteLength: autoAllocateChunkSize,
+ bytesFilled: 0,
+ elementSize: 1,
+ ctor: Uint8Array,
+ readerType: 'default'
+ };
+
+ this._pendingPullIntos.push(pullIntoDescriptor);
+ }
+
+ var promise = ReadableStreamAddReadRequest(stream);
+ ReadableByteStreamControllerCallPullIfNeeded(this);
+ return promise;
+ }
+ }, {
+ key: 'byobRequest',
+ get: function get() {
+ if (IsReadableByteStreamController(this) === false) {
+ throw byteStreamControllerBrandCheckException('byobRequest');
+ }
+
+ if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {
+ var firstDescriptor = this._pendingPullIntos[0];
+ var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
+ this._byobRequest = new ReadableStreamBYOBRequest(this, view);
+ }
+
+ return this._byobRequest;
+ }
+ }, {
+ key: 'desiredSize',
+ get: function get() {
+ if (IsReadableByteStreamController(this) === false) {
+ throw byteStreamControllerBrandCheckException('desiredSize');
+ }
+
+ return ReadableByteStreamControllerGetDesiredSize(this);
+ }
+ }]);
+
+ return ReadableByteStreamController;
+ }();
+
+ function IsReadableByteStreamController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function IsReadableStreamBYOBRequest(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
+ var shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
+
+ if (shouldPull === false) {
+ return undefined;
+ }
+
+ if (controller._pulling === true) {
+ controller._pullAgain = true;
+ return undefined;
+ }
+
+ assert(controller._pullAgain === false);
+ controller._pulling = true;
+ var pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]);
+ pullPromise.then(function () {
+ controller._pulling = false;
+
+ if (controller._pullAgain === true) {
+ controller._pullAgain = false;
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ }, function (e) {
+ if (controller._controlledReadableStream._state === 'readable') {
+ ReadableByteStreamControllerError(controller, e);
+ }
+ })["catch"](rethrowAssertionErrorRejection);
+ return undefined;
+ }
+
+ function ReadableByteStreamControllerClearPendingPullIntos(controller) {
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ controller._pendingPullIntos = [];
+ }
+
+ function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
+ assert(stream._state !== 'errored', 'state must not be errored');
+ var done = false;
+
+ if (stream._state === 'closed') {
+ assert(pullIntoDescriptor.bytesFilled === 0);
+ done = true;
+ }
+
+ var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
+
+ if (pullIntoDescriptor.readerType === 'default') {
+ ReadableStreamFulfillReadRequest(stream, filledView, done);
+ } else {
+ assert(pullIntoDescriptor.readerType === 'byob');
+ ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
+ }
+ }
+
+ function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
+ var bytesFilled = pullIntoDescriptor.bytesFilled;
+ var elementSize = pullIntoDescriptor.elementSize;
+ assert(bytesFilled <= pullIntoDescriptor.byteLength);
+ assert(bytesFilled % elementSize === 0);
+ return new pullIntoDescriptor.ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
+ }
+
+ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
+ controller._queue.push({
+ buffer: buffer,
+ byteOffset: byteOffset,
+ byteLength: byteLength
+ });
+
+ controller._queueTotalSize += byteLength;
+ }
+
+ function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
+ var elementSize = pullIntoDescriptor.elementSize;
+ var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
+ var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
+ var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
+ var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
+ var totalBytesToCopyRemaining = maxBytesToCopy;
+ var ready = false;
+
+ if (maxAlignedBytes > currentAlignedBytes) {
+ totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
+ ready = true;
+ }
+
+ var queue = controller._queue;
+
+ while (totalBytesToCopyRemaining > 0) {
+ var headOfQueue = queue[0];
+ var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
+ var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
+ ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
+
+ if (headOfQueue.byteLength === bytesToCopy) {
+ queue.shift();
+ } else {
+ headOfQueue.byteOffset += bytesToCopy;
+ headOfQueue.byteLength -= bytesToCopy;
+ }
+
+ controller._queueTotalSize -= bytesToCopy;
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
+ totalBytesToCopyRemaining -= bytesToCopy;
+ }
+
+ if (ready === false) {
+ assert(controller._queueTotalSize === 0, 'queue must be empty');
+ assert(pullIntoDescriptor.bytesFilled > 0);
+ assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);
+ }
+
+ return ready;
+ }
+
+ function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
+ assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor);
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ pullIntoDescriptor.bytesFilled += size;
+ }
+
+ function ReadableByteStreamControllerHandleQueueDrain(controller) {
+ assert(controller._controlledReadableStream._state === 'readable');
+
+ if (controller._queueTotalSize === 0 && controller._closeRequested === true) {
+ ReadableStreamClose(controller._controlledReadableStream);
+ } else {
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ }
+
+ function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
+ if (controller._byobRequest === undefined) {
+ return;
+ }
+
+ controller._byobRequest._associatedReadableByteStreamController = undefined;
+ controller._byobRequest._view = undefined;
+ controller._byobRequest = undefined;
+ }
+
+ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
+ assert(controller._closeRequested === false);
+
+ while (controller._pendingPullIntos.length > 0) {
+ if (controller._queueTotalSize === 0) {
+ return;
+ }
+
+ var pullIntoDescriptor = controller._pendingPullIntos[0];
+
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);
+ }
+ }
+ }
+
+ function ReadableByteStreamControllerPullInto(controller, view) {
+ var stream = controller._controlledReadableStream;
+ var elementSize = 1;
+
+ if (view.constructor !== DataView) {
+ elementSize = view.constructor.BYTES_PER_ELEMENT;
+ }
+
+ var ctor = view.constructor;
+ var pullIntoDescriptor = {
+ buffer: view.buffer,
+ byteOffset: view.byteOffset,
+ byteLength: view.byteLength,
+ bytesFilled: 0,
+ elementSize: elementSize,
+ ctor: ctor,
+ readerType: 'byob'
+ };
+
+ if (controller._pendingPullIntos.length > 0) {
+ pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
+
+ controller._pendingPullIntos.push(pullIntoDescriptor);
+
+ return ReadableStreamAddReadIntoRequest(stream);
+ }
+
+ if (stream._state === 'closed') {
+ var emptyView = new view.constructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
+ return Promise.resolve(CreateIterResultObject(emptyView, true));
+ }
+
+ if (controller._queueTotalSize > 0) {
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {
+ var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
+ ReadableByteStreamControllerHandleQueueDrain(controller);
+ return Promise.resolve(CreateIterResultObject(filledView, false));
+ }
+
+ if (controller._closeRequested === true) {
+ var e = new TypeError('Insufficient bytes to fill elements in the given buffer');
+ ReadableByteStreamControllerError(controller, e);
+ return Promise.reject(e);
+ }
+ }
+
+ pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
+
+ controller._pendingPullIntos.push(pullIntoDescriptor);
+
+ var promise = ReadableStreamAddReadIntoRequest(stream);
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ return promise;
+ }
+
+ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
+ firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
+ assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0');
+ var stream = controller._controlledReadableStream;
+
+ if (ReadableStreamHasBYOBReader(stream) === true) {
+ while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
+ var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
+ ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
+ }
+ }
+ }
+
+ function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
+ if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
+ throw new RangeError('bytesWritten out of range');
+ }
+
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
+
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
+ return;
+ }
+
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
+ var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
+
+ if (remainderSize > 0) {
+ var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
+ var remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
+ }
+
+ pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
+ pullIntoDescriptor.bytesFilled -= remainderSize;
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
+ }
+
+ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
+ var firstDescriptor = controller._pendingPullIntos[0];
+ var stream = controller._controlledReadableStream;
+
+ if (stream._state === 'closed') {
+ if (bytesWritten !== 0) {
+ throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
+ }
+
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
+ } else {
+ assert(stream._state === 'readable');
+ ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
+ }
+ }
+
+ function ReadableByteStreamControllerShiftPendingPullInto(controller) {
+ var descriptor = controller._pendingPullIntos.shift();
+
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ return descriptor;
+ }
+
+ function ReadableByteStreamControllerShouldCallPull(controller) {
+ var stream = controller._controlledReadableStream;
+
+ if (stream._state !== 'readable') {
+ return false;
+ }
+
+ if (controller._closeRequested === true) {
+ return false;
+ }
+
+ if (controller._started === false) {
+ return false;
+ }
+
+ if (ReadableStreamHasDefaultReader(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
+ return true;
+ }
+
+ if (ReadableStreamHasBYOBReader(stream) === true && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
+ return true;
+ }
+
+ if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ function ReadableByteStreamControllerClose(controller) {
+ var stream = controller._controlledReadableStream;
+ assert(controller._closeRequested === false);
+ assert(stream._state === 'readable');
+
+ if (controller._queueTotalSize > 0) {
+ controller._closeRequested = true;
+ return;
+ }
+
+ if (controller._pendingPullIntos.length > 0) {
+ var firstPendingPullInto = controller._pendingPullIntos[0];
+
+ if (firstPendingPullInto.bytesFilled > 0) {
+ var e = new TypeError('Insufficient bytes to fill elements in the given buffer');
+ ReadableByteStreamControllerError(controller, e);
+ throw e;
+ }
+ }
+
+ ReadableStreamClose(stream);
+ }
+
+ function ReadableByteStreamControllerEnqueue(controller, chunk) {
+ var stream = controller._controlledReadableStream;
+ assert(controller._closeRequested === false);
+ assert(stream._state === 'readable');
+ var buffer = chunk.buffer;
+ var byteOffset = chunk.byteOffset;
+ var byteLength = chunk.byteLength;
+ var transferredBuffer = TransferArrayBuffer(buffer);
+
+ if (ReadableStreamHasDefaultReader(stream) === true) {
+ if (ReadableStreamGetNumReadRequests(stream) === 0) {
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ } else {
+ assert(controller._queue.length === 0);
+ var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
+ ReadableStreamFulfillReadRequest(stream, transferredView, false);
+ }
+ } else if (ReadableStreamHasBYOBReader(stream) === true) {
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
+ } else {
+ assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked');
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ }
+ }
+
+ function ReadableByteStreamControllerError(controller, e) {
+ var stream = controller._controlledReadableStream;
+ assert(stream._state === 'readable');
+ ReadableByteStreamControllerClearPendingPullIntos(controller);
+ ResetQueue(controller);
+ ReadableStreamError(stream, e);
+ }
+
+ function ReadableByteStreamControllerGetDesiredSize(controller) {
+ var stream = controller._controlledReadableStream;
+ var state = stream._state;
+
+ if (state === 'errored') {
+ return null;
+ }
+
+ if (state === 'closed') {
+ return 0;
+ }
+
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+
+ function ReadableByteStreamControllerRespond(controller, bytesWritten) {
+ bytesWritten = Number(bytesWritten);
+
+ if (IsFiniteNonNegativeNumber(bytesWritten) === false) {
+ throw new RangeError('bytesWritten must be a finite');
+ }
+
+ assert(controller._pendingPullIntos.length > 0);
+ ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
+ }
+
+ function ReadableByteStreamControllerRespondWithNewView(controller, view) {
+ assert(controller._pendingPullIntos.length > 0);
+ var firstDescriptor = controller._pendingPullIntos[0];
+
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
+ throw new RangeError('The region specified by view does not match byobRequest');
+ }
+
+ if (firstDescriptor.byteLength !== view.byteLength) {
+ throw new RangeError('The buffer of view has different capacity than byobRequest');
+ }
+
+ firstDescriptor.buffer = view.buffer;
+ ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
+ }
+
+ function streamBrandCheckException(name) {
+ return new TypeError('ReadableStream.prototype.' + name + ' can only be used on a ReadableStream');
+ }
+
+ function readerLockException(name) {
+ return new TypeError('Cannot ' + name + ' a stream using a released reader');
+ }
+
+ function defaultReaderBrandCheckException(name) {
+ return new TypeError('ReadableStreamDefaultReader.prototype.' + name + ' can only be used on a ReadableStreamDefaultReader');
+ }
+
+ function defaultReaderClosedPromiseInitialize(reader) {
+ reader._closedPromise = new Promise(function (resolve, reject) {
+ reader._closedPromise_resolve = resolve;
+ reader._closedPromise_reject = reject;
+ });
+ }
+
+ function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
+ reader._closedPromise = Promise.reject(reason);
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+
+ function defaultReaderClosedPromiseInitializeAsResolved(reader) {
+ reader._closedPromise = Promise.resolve(undefined);
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+
+ function defaultReaderClosedPromiseReject(reader, reason) {
+ assert(reader._closedPromise_resolve !== undefined);
+ assert(reader._closedPromise_reject !== undefined);
+
+ reader._closedPromise_reject(reason);
+
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+
+ function defaultReaderClosedPromiseResetToRejected(reader, reason) {
+ assert(reader._closedPromise_resolve === undefined);
+ assert(reader._closedPromise_reject === undefined);
+ reader._closedPromise = Promise.reject(reason);
+ }
+
+ function defaultReaderClosedPromiseResolve(reader) {
+ assert(reader._closedPromise_resolve !== undefined);
+ assert(reader._closedPromise_reject !== undefined);
+
+ reader._closedPromise_resolve(undefined);
+
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+
+ function byobReaderBrandCheckException(name) {
+ return new TypeError('ReadableStreamBYOBReader.prototype.' + name + ' can only be used on a ReadableStreamBYOBReader');
+ }
+
+ function defaultControllerBrandCheckException(name) {
+ return new TypeError('ReadableStreamDefaultController.prototype.' + name + ' can only be used on a ReadableStreamDefaultController');
+ }
+
+ function byobRequestBrandCheckException(name) {
+ return new TypeError('ReadableStreamBYOBRequest.prototype.' + name + ' can only be used on a ReadableStreamBYOBRequest');
+ }
+
+ function byteStreamControllerBrandCheckException(name) {
+ return new TypeError('ReadableByteStreamController.prototype.' + name + ' can only be used on a ReadableByteStreamController');
+ }
+
+ function ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise) {
+ try {
+ Promise.prototype.then.call(promise, undefined, function () {});
+ } catch (e) {}
+ }
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var transformStream = __w_pdfjs_require__(6);
+
+ var readableStream = __w_pdfjs_require__(4);
+
+ var writableStream = __w_pdfjs_require__(2);
+
+ exports.TransformStream = transformStream.TransformStream;
+ exports.ReadableStream = readableStream.ReadableStream;
+ exports.IsReadableStreamDisturbed = readableStream.IsReadableStreamDisturbed;
+ exports.ReadableStreamDefaultControllerClose = readableStream.ReadableStreamDefaultControllerClose;
+ exports.ReadableStreamDefaultControllerEnqueue = readableStream.ReadableStreamDefaultControllerEnqueue;
+ exports.ReadableStreamDefaultControllerError = readableStream.ReadableStreamDefaultControllerError;
+ exports.ReadableStreamDefaultControllerGetDesiredSize = readableStream.ReadableStreamDefaultControllerGetDesiredSize;
+ exports.AcquireWritableStreamDefaultWriter = writableStream.AcquireWritableStreamDefaultWriter;
+ exports.IsWritableStream = writableStream.IsWritableStream;
+ exports.IsWritableStreamLocked = writableStream.IsWritableStreamLocked;
+ exports.WritableStream = writableStream.WritableStream;
+ exports.WritableStreamAbort = writableStream.WritableStreamAbort;
+ exports.WritableStreamDefaultControllerError = writableStream.WritableStreamDefaultControllerError;
+ exports.WritableStreamDefaultWriterCloseWithErrorPropagation = writableStream.WritableStreamDefaultWriterCloseWithErrorPropagation;
+ exports.WritableStreamDefaultWriterRelease = writableStream.WritableStreamDefaultWriterRelease;
+ exports.WritableStreamDefaultWriterWrite = writableStream.WritableStreamDefaultWriterWrite;
+}, function (module, exports, __w_pdfjs_require__) {
+ "use strict";
+
+ var _createClass = function () {
+ function defineProperties(target, props) {
+ for (var i = 0; i < props.length; i++) {
+ var descriptor = props[i];
+ descriptor.enumerable = descriptor.enumerable || false;
+ descriptor.configurable = true;
+ if ("value" in descriptor) descriptor.writable = true;
+ Object.defineProperty(target, descriptor.key, descriptor);
+ }
+ }
+
+ return function (Constructor, protoProps, staticProps) {
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
+ if (staticProps) defineProperties(Constructor, staticProps);
+ return Constructor;
+ };
+ }();
+
+ function _classCallCheck(instance, Constructor) {
+ if (!(instance instanceof Constructor)) {
+ throw new TypeError("Cannot call a class as a function");
+ }
+ }
+
+ var _require = __w_pdfjs_require__(1),
+ assert = _require.assert;
+
+ var _require2 = __w_pdfjs_require__(0),
+ InvokeOrNoop = _require2.InvokeOrNoop,
+ PromiseInvokeOrPerformFallback = _require2.PromiseInvokeOrPerformFallback,
+ PromiseInvokeOrNoop = _require2.PromiseInvokeOrNoop,
+ typeIsObject = _require2.typeIsObject;
+
+ var _require3 = __w_pdfjs_require__(4),
+ ReadableStream = _require3.ReadableStream,
+ ReadableStreamDefaultControllerClose = _require3.ReadableStreamDefaultControllerClose,
+ ReadableStreamDefaultControllerEnqueue = _require3.ReadableStreamDefaultControllerEnqueue,
+ ReadableStreamDefaultControllerError = _require3.ReadableStreamDefaultControllerError,
+ ReadableStreamDefaultControllerGetDesiredSize = _require3.ReadableStreamDefaultControllerGetDesiredSize;
+
+ var _require4 = __w_pdfjs_require__(2),
+ WritableStream = _require4.WritableStream,
+ WritableStreamDefaultControllerError = _require4.WritableStreamDefaultControllerError;
+
+ function TransformStreamCloseReadable(transformStream) {
+ if (transformStream._errored === true) {
+ throw new TypeError('TransformStream is already errored');
+ }
+
+ if (transformStream._readableClosed === true) {
+ throw new TypeError('Readable side is already closed');
+ }
+
+ TransformStreamCloseReadableInternal(transformStream);
+ }
+
+ function TransformStreamEnqueueToReadable(transformStream, chunk) {
+ if (transformStream._errored === true) {
+ throw new TypeError('TransformStream is already errored');
+ }
+
+ if (transformStream._readableClosed === true) {
+ throw new TypeError('Readable side is already closed');
+ }
+
+ var controller = transformStream._readableController;
+
+ try {
+ ReadableStreamDefaultControllerEnqueue(controller, chunk);
+ } catch (e) {
+ transformStream._readableClosed = true;
+ TransformStreamErrorIfNeeded(transformStream, e);
+ throw transformStream._storedError;
+ }
+
+ var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
+ var maybeBackpressure = desiredSize <= 0;
+
+ if (maybeBackpressure === true && transformStream._backpressure === false) {
+ TransformStreamSetBackpressure(transformStream, true);
+ }
+ }
+
+ function TransformStreamError(transformStream, e) {
+ if (transformStream._errored === true) {
+ throw new TypeError('TransformStream is already errored');
+ }
+
+ TransformStreamErrorInternal(transformStream, e);
+ }
+
+ function TransformStreamCloseReadableInternal(transformStream) {
+ assert(transformStream._errored === false);
+ assert(transformStream._readableClosed === false);
+
+ try {
+ ReadableStreamDefaultControllerClose(transformStream._readableController);
+ } catch (e) {
+ assert(false);
+ }
+
+ transformStream._readableClosed = true;
+ }
+
+ function TransformStreamErrorIfNeeded(transformStream, e) {
+ if (transformStream._errored === false) {
+ TransformStreamErrorInternal(transformStream, e);
+ }
+ }
+
+ function TransformStreamErrorInternal(transformStream, e) {
+ assert(transformStream._errored === false);
+ transformStream._errored = true;
+ transformStream._storedError = e;
+
+ if (transformStream._writableDone === false) {
+ WritableStreamDefaultControllerError(transformStream._writableController, e);
+ }
+
+ if (transformStream._readableClosed === false) {
+ ReadableStreamDefaultControllerError(transformStream._readableController, e);
+ }
+ }
+
+ function TransformStreamReadableReadyPromise(transformStream) {
+ assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');
+
+ if (transformStream._backpressure === false) {
+ return Promise.resolve();
+ }
+
+ assert(transformStream._backpressure === true, '_backpressure should have been initialized');
+ return transformStream._backpressureChangePromise;
+ }
+
+ function TransformStreamSetBackpressure(transformStream, backpressure) {
+ assert(transformStream._backpressure !== backpressure, 'TransformStreamSetBackpressure() should be called only when backpressure is changed');
+
+ if (transformStream._backpressureChangePromise !== undefined) {
+ transformStream._backpressureChangePromise_resolve(backpressure);
+ }
+
+ transformStream._backpressureChangePromise = new Promise(function (resolve) {
+ transformStream._backpressureChangePromise_resolve = resolve;
+ });
+
+ transformStream._backpressureChangePromise.then(function (resolution) {
+ assert(resolution !== backpressure, '_backpressureChangePromise should be fulfilled only when backpressure is changed');
+ });
+
+ transformStream._backpressure = backpressure;
+ }
+
+ function TransformStreamDefaultTransform(chunk, transformStreamController) {
+ var transformStream = transformStreamController._controlledTransformStream;
+ TransformStreamEnqueueToReadable(transformStream, chunk);
+ return Promise.resolve();
+ }
+
+ function TransformStreamTransform(transformStream, chunk) {
+ assert(transformStream._errored === false);
+ assert(transformStream._transforming === false);
+ assert(transformStream._backpressure === false);
+ transformStream._transforming = true;
+ var transformer = transformStream._transformer;
+ var controller = transformStream._transformStreamController;
+ var transformPromise = PromiseInvokeOrPerformFallback(transformer, 'transform', [chunk, controller], TransformStreamDefaultTransform, [chunk, controller]);
+ return transformPromise.then(function () {
+ transformStream._transforming = false;
+ return TransformStreamReadableReadyPromise(transformStream);
+ }, function (e) {
+ TransformStreamErrorIfNeeded(transformStream, e);
+ return Promise.reject(e);
+ });
+ }
+
+ function IsTransformStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function IsTransformStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+
+ if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ var TransformStreamSink = function () {
+ function TransformStreamSink(transformStream, startPromise) {
+ _classCallCheck(this, TransformStreamSink);
+
+ this._transformStream = transformStream;
+ this._startPromise = startPromise;
+ }
+
+ _createClass(TransformStreamSink, [{
+ key: 'start',
+ value: function start(c) {
+ var transformStream = this._transformStream;
+ transformStream._writableController = c;
+ return this._startPromise.then(function () {
+ return TransformStreamReadableReadyPromise(transformStream);
+ });
+ }
+ }, {
+ key: 'write',
+ value: function write(chunk) {
+ var transformStream = this._transformStream;
+ return TransformStreamTransform(transformStream, chunk);
+ }
+ }, {
+ key: 'abort',
+ value: function abort() {
+ var transformStream = this._transformStream;
+ transformStream._writableDone = true;
+ TransformStreamErrorInternal(transformStream, new TypeError('Writable side aborted'));
+ }
+ }, {
+ key: 'close',
+ value: function close() {
+ var transformStream = this._transformStream;
+ assert(transformStream._transforming === false);
+ transformStream._writableDone = true;
+ var flushPromise = PromiseInvokeOrNoop(transformStream._transformer, 'flush', [transformStream._transformStreamController]);
+ return flushPromise.then(function () {
+ if (transformStream._errored === true) {
+ return Promise.reject(transformStream._storedError);
+ }
+
+ if (transformStream._readableClosed === false) {
+ TransformStreamCloseReadableInternal(transformStream);
+ }
+
+ return Promise.resolve();
+ })["catch"](function (r) {
+ TransformStreamErrorIfNeeded(transformStream, r);
+ return Promise.reject(transformStream._storedError);
+ });
+ }
+ }]);
+
+ return TransformStreamSink;
+ }();
+
+ var TransformStreamSource = function () {
+ function TransformStreamSource(transformStream, startPromise) {
+ _classCallCheck(this, TransformStreamSource);
+
+ this._transformStream = transformStream;
+ this._startPromise = startPromise;
+ }
+
+ _createClass(TransformStreamSource, [{
+ key: 'start',
+ value: function start(c) {
+ var transformStream = this._transformStream;
+ transformStream._readableController = c;
+ return this._startPromise.then(function () {
+ assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');
+
+ if (transformStream._backpressure === true) {
+ return Promise.resolve();
+ }
+
+ assert(transformStream._backpressure === false, '_backpressure should have been initialized');
+ return transformStream._backpressureChangePromise;
+ });
+ }
+ }, {
+ key: 'pull',
+ value: function pull() {
+ var transformStream = this._transformStream;
+ assert(transformStream._backpressure === true, 'pull() should be never called while _backpressure is false');
+ assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');
+ TransformStreamSetBackpressure(transformStream, false);
+ return transformStream._backpressureChangePromise;
+ }
+ }, {
+ key: 'cancel',
+ value: function cancel() {
+ var transformStream = this._transformStream;
+ transformStream._readableClosed = true;
+ TransformStreamErrorInternal(transformStream, new TypeError('Readable side canceled'));
+ }
+ }]);
+
+ return TransformStreamSource;
+ }();
+
+ var TransformStreamDefaultController = function () {
+ function TransformStreamDefaultController(transformStream) {
+ _classCallCheck(this, TransformStreamDefaultController);
+
+ if (IsTransformStream(transformStream) === false) {
+ throw new TypeError('TransformStreamDefaultController can only be ' + 'constructed with a TransformStream instance');
+ }
+
+ if (transformStream._transformStreamController !== undefined) {
+ throw new TypeError('TransformStreamDefaultController instances can ' + 'only be created by the TransformStream constructor');
+ }
+
+ this._controlledTransformStream = transformStream;
+ }
+
+ _createClass(TransformStreamDefaultController, [{
+ key: 'enqueue',
+ value: function enqueue(chunk) {
+ if (IsTransformStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('enqueue');
+ }
+
+ TransformStreamEnqueueToReadable(this._controlledTransformStream, chunk);
+ }
+ }, {
+ key: 'close',
+ value: function close() {
+ if (IsTransformStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('close');
+ }
+
+ TransformStreamCloseReadable(this._controlledTransformStream);
+ }
+ }, {
+ key: 'error',
+ value: function error(reason) {
+ if (IsTransformStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('error');
+ }
+
+ TransformStreamError(this._controlledTransformStream, reason);
+ }
+ }, {
+ key: 'desiredSize',
+ get: function get() {
+ if (IsTransformStreamDefaultController(this) === false) {
+ throw defaultControllerBrandCheckException('desiredSize');
+ }
+
+ var transformStream = this._controlledTransformStream;
+ var readableController = transformStream._readableController;
+ return ReadableStreamDefaultControllerGetDesiredSize(readableController);
+ }
+ }]);
+
+ return TransformStreamDefaultController;
+ }();
+
+ var TransformStream = function () {
+ function TransformStream() {
+ var transformer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+
+ _classCallCheck(this, TransformStream);
+
+ this._transformer = transformer;
+ var readableStrategy = transformer.readableStrategy,
+ writableStrategy = transformer.writableStrategy;
+ this._transforming = false;
+ this._errored = false;
+ this._storedError = undefined;
+ this._writableController = undefined;
+ this._readableController = undefined;
+ this._transformStreamController = undefined;
+ this._writableDone = false;
+ this._readableClosed = false;
+ this._backpressure = undefined;
+ this._backpressureChangePromise = undefined;
+ this._backpressureChangePromise_resolve = undefined;
+ this._transformStreamController = new TransformStreamDefaultController(this);
+ var startPromise_resolve = void 0;
+ var startPromise = new Promise(function (resolve) {
+ startPromise_resolve = resolve;
+ });
+ var source = new TransformStreamSource(this, startPromise);
+ this._readable = new ReadableStream(source, readableStrategy);
+ var sink = new TransformStreamSink(this, startPromise);
+ this._writable = new WritableStream(sink, writableStrategy);
+ assert(this._writableController !== undefined);
+ assert(this._readableController !== undefined);
+ var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(this._readableController);
+ TransformStreamSetBackpressure(this, desiredSize <= 0);
+ var transformStream = this;
+ var startResult = InvokeOrNoop(transformer, 'start', [transformStream._transformStreamController]);
+ startPromise_resolve(startResult);
+ startPromise["catch"](function (e) {
+ if (transformStream._errored === false) {
+ transformStream._errored = true;
+ transformStream._storedError = e;
+ }
+ });
+ }
+
+ _createClass(TransformStream, [{
+ key: 'readable',
+ get: function get() {
+ if (IsTransformStream(this) === false) {
+ throw streamBrandCheckException('readable');
+ }
+
+ return this._readable;
+ }
+ }, {
+ key: 'writable',
+ get: function get() {
+ if (IsTransformStream(this) === false) {
+ throw streamBrandCheckException('writable');
+ }
+
+ return this._writable;
+ }
+ }]);
+
+ return TransformStream;
+ }();
+
+ module.exports = {
+ TransformStream: TransformStream
+ };
+
+ function defaultControllerBrandCheckException(name) {
+ return new TypeError('TransformStreamDefaultController.prototype.' + name + ' can only be used on a TransformStreamDefaultController');
+ }
+
+ function streamBrandCheckException(name) {
+ return new TypeError('TransformStream.prototype.' + name + ' can only be used on a TransformStream');
+ }
+}, function (module, exports, __w_pdfjs_require__) {
+ module.exports = __w_pdfjs_require__(5);
+}]));
+
+/***/ }),
+/* 145 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+function _typeof(obj) { 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); }
+
+{
+ var isURLSupported = false;
+
+ try {
+ if (typeof URL === 'function' && _typeof(URL.prototype) === 'object' && 'origin' in URL.prototype) {
+ var u = new URL('b', 'http://a');
+ u.pathname = 'c%20d';
+ isURLSupported = u.href === 'http://a/c%20d';
+ }
+ } catch (ex) {}
+
+ if (isURLSupported) {
+ exports.URL = URL;
+ } else {
+ var PolyfillURL = __w_pdfjs_require__(146).URL;
+
+ var OriginalURL = __w_pdfjs_require__(3).URL;
+
+ if (OriginalURL) {
+ PolyfillURL.createObjectURL = function (blob) {
+ return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
+ };
+
+ PolyfillURL.revokeObjectURL = function (url) {
+ OriginalURL.revokeObjectURL(url);
+ };
+ }
+
+ exports.URL = PolyfillURL;
+ }
+}
+
+/***/ }),
+/* 146 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+(function URLConstructorClosure() {
+ 'use strict';
+
+ var relative = Object.create(null);
+ relative['ftp'] = 21;
+ relative['file'] = 0;
+ relative['gopher'] = 70;
+ relative['http'] = 80;
+ relative['https'] = 443;
+ relative['ws'] = 80;
+ relative['wss'] = 443;
+ var relativePathDotMapping = Object.create(null);
+ relativePathDotMapping['%2e'] = '.';
+ relativePathDotMapping['.%2e'] = '..';
+ relativePathDotMapping['%2e.'] = '..';
+ relativePathDotMapping['%2e%2e'] = '..';
+
+ function isRelativeScheme(scheme) {
+ return relative[scheme] !== undefined;
+ }
+
+ function invalid() {
+ clear.call(this);
+ this._isInvalid = true;
+ }
+
+ function IDNAToASCII(h) {
+ if (h === '') {
+ invalid.call(this);
+ }
+
+ return h.toLowerCase();
+ }
+
+ function percentEscape(c) {
+ var unicode = c.charCodeAt(0);
+
+ if (unicode > 0x20 && unicode < 0x7F && [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1) {
+ return c;
+ }
+
+ return encodeURIComponent(c);
+ }
+
+ function percentEscapeQuery(c) {
+ var unicode = c.charCodeAt(0);
+
+ if (unicode > 0x20 && unicode < 0x7F && [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1) {
+ return c;
+ }
+
+ return encodeURIComponent(c);
+ }
+
+ var EOF,
+ ALPHA = /[a-zA-Z]/,
+ ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
+
+ function parse(input, stateOverride, base) {
+ function err(message) {
+ errors.push(message);
+ }
+
+ var state = stateOverride || 'scheme start',
+ cursor = 0,
+ buffer = '',
+ seenAt = false,
+ seenBracket = false,
+ errors = [];
+
+ loop: while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
+ var c = input[cursor];
+
+ switch (state) {
+ case 'scheme start':
+ if (c && ALPHA.test(c)) {
+ buffer += c.toLowerCase();
+ state = 'scheme';
+ } else if (!stateOverride) {
+ buffer = '';
+ state = 'no scheme';
+ continue;
+ } else {
+ err('Invalid scheme.');
+ break loop;
+ }
+
+ break;
+
+ case 'scheme':
+ if (c && ALPHANUMERIC.test(c)) {
+ buffer += c.toLowerCase();
+ } else if (c === ':') {
+ this._scheme = buffer;
+ buffer = '';
+
+ if (stateOverride) {
+ break loop;
+ }
+
+ if (isRelativeScheme(this._scheme)) {
+ this._isRelative = true;
+ }
+
+ if (this._scheme === 'file') {
+ state = 'relative';
+ } else if (this._isRelative && base && base._scheme === this._scheme) {
+ state = 'relative or authority';
+ } else if (this._isRelative) {
+ state = 'authority first slash';
+ } else {
+ state = 'scheme data';
+ }
+ } else if (!stateOverride) {
+ buffer = '';
+ cursor = 0;
+ state = 'no scheme';
+ continue;
+ } else if (c === EOF) {
+ break loop;
+ } else {
+ err('Code point not allowed in scheme: ' + c);
+ break loop;
+ }
+
+ break;
+
+ case 'scheme data':
+ if (c === '?') {
+ this._query = '?';
+ state = 'query';
+ } else if (c === '#') {
+ this._fragment = '#';
+ state = 'fragment';
+ } else {
+ if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') {
+ this._schemeData += percentEscape(c);
+ }
+ }
+
+ break;
+
+ case 'no scheme':
+ if (!base || !isRelativeScheme(base._scheme)) {
+ err('Missing scheme.');
+ invalid.call(this);
+ } else {
+ state = 'relative';
+ continue;
+ }
+
+ break;
+
+ case 'relative or authority':
+ if (c === '/' && input[cursor + 1] === '/') {
+ state = 'authority ignore slashes';
+ } else {
+ err('Expected /, got: ' + c);
+ state = 'relative';
+ continue;
+ }
+
+ break;
+
+ case 'relative':
+ this._isRelative = true;
+
+ if (this._scheme !== 'file') {
+ this._scheme = base._scheme;
+ }
+
+ if (c === EOF) {
+ this._host = base._host;
+ this._port = base._port;
+ this._path = base._path.slice();
+ this._query = base._query;
+ this._username = base._username;
+ this._password = base._password;
+ break loop;
+ } else if (c === '/' || c === '\\') {
+ if (c === '\\') {
+ err('\\ is an invalid code point.');
+ }
+
+ state = 'relative slash';
+ } else if (c === '?') {
+ this._host = base._host;
+ this._port = base._port;
+ this._path = base._path.slice();
+ this._query = '?';
+ this._username = base._username;
+ this._password = base._password;
+ state = 'query';
+ } else if (c === '#') {
+ this._host = base._host;
+ this._port = base._port;
+ this._path = base._path.slice();
+ this._query = base._query;
+ this._fragment = '#';
+ this._username = base._username;
+ this._password = base._password;
+ state = 'fragment';
+ } else {
+ var nextC = input[cursor + 1];
+ var nextNextC = input[cursor + 2];
+
+ if (this._scheme !== 'file' || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || nextNextC !== EOF && nextNextC !== '/' && nextNextC !== '\\' && nextNextC !== '?' && nextNextC !== '#') {
+ this._host = base._host;
+ this._port = base._port;
+ this._username = base._username;
+ this._password = base._password;
+ this._path = base._path.slice();
+
+ this._path.pop();
+ }
+
+ state = 'relative path';
+ continue;
+ }
+
+ break;
+
+ case 'relative slash':
+ if (c === '/' || c === '\\') {
+ if (c === '\\') {
+ err('\\ is an invalid code point.');
+ }
+
+ if (this._scheme === 'file') {
+ state = 'file host';
+ } else {
+ state = 'authority ignore slashes';
+ }
+ } else {
+ if (this._scheme !== 'file') {
+ this._host = base._host;
+ this._port = base._port;
+ this._username = base._username;
+ this._password = base._password;
+ }
+
+ state = 'relative path';
+ continue;
+ }
+
+ break;
+
+ case 'authority first slash':
+ if (c === '/') {
+ state = 'authority second slash';
+ } else {
+ err('Expected \'/\', got: ' + c);
+ state = 'authority ignore slashes';
+ continue;
+ }
+
+ break;
+
+ case 'authority second slash':
+ state = 'authority ignore slashes';
+
+ if (c !== '/') {
+ err('Expected \'/\', got: ' + c);
+ continue;
+ }
+
+ break;
+
+ case 'authority ignore slashes':
+ if (c !== '/' && c !== '\\') {
+ state = 'authority';
+ continue;
+ } else {
+ err('Expected authority, got: ' + c);
+ }
+
+ break;
+
+ case 'authority':
+ if (c === '@') {
+ if (seenAt) {
+ err('@ already seen.');
+ buffer += '%40';
+ }
+
+ seenAt = true;
+
+ for (var i = 0; i < buffer.length; i++) {
+ var cp = buffer[i];
+
+ if (cp === '\t' || cp === '\n' || cp === '\r') {
+ err('Invalid whitespace in authority.');
+ continue;
+ }
+
+ if (cp === ':' && this._password === null) {
+ this._password = '';
+ continue;
+ }
+
+ var tempC = percentEscape(cp);
+
+ if (this._password !== null) {
+ this._password += tempC;
+ } else {
+ this._username += tempC;
+ }
+ }
+
+ buffer = '';
+ } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
+ cursor -= buffer.length;
+ buffer = '';
+ state = 'host';
+ continue;
+ } else {
+ buffer += c;
+ }
+
+ break;
+
+ case 'file host':
+ if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
+ if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
+ state = 'relative path';
+ } else if (buffer.length === 0) {
+ state = 'relative path start';
+ } else {
+ this._host = IDNAToASCII.call(this, buffer);
+ buffer = '';
+ state = 'relative path start';
+ }
+
+ continue;
+ } else if (c === '\t' || c === '\n' || c === '\r') {
+ err('Invalid whitespace in file host.');
+ } else {
+ buffer += c;
+ }
+
+ break;
+
+ case 'host':
+ case 'hostname':
+ if (c === ':' && !seenBracket) {
+ this._host = IDNAToASCII.call(this, buffer);
+ buffer = '';
+ state = 'port';
+
+ if (stateOverride === 'hostname') {
+ break loop;
+ }
+ } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
+ this._host = IDNAToASCII.call(this, buffer);
+ buffer = '';
+ state = 'relative path start';
+
+ if (stateOverride) {
+ break loop;
+ }
+
+ continue;
+ } else if (c !== '\t' && c !== '\n' && c !== '\r') {
+ if (c === '[') {
+ seenBracket = true;
+ } else if (c === ']') {
+ seenBracket = false;
+ }
+
+ buffer += c;
+ } else {
+ err('Invalid code point in host/hostname: ' + c);
+ }
+
+ break;
+
+ case 'port':
+ if (/[0-9]/.test(c)) {
+ buffer += c;
+ } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#' || stateOverride) {
+ if (buffer !== '') {
+ var temp = parseInt(buffer, 10);
+
+ if (temp !== relative[this._scheme]) {
+ this._port = temp + '';
+ }
+
+ buffer = '';
+ }
+
+ if (stateOverride) {
+ break loop;
+ }
+
+ state = 'relative path start';
+ continue;
+ } else if (c === '\t' || c === '\n' || c === '\r') {
+ err('Invalid code point in port: ' + c);
+ } else {
+ invalid.call(this);
+ }
+
+ break;
+
+ case 'relative path start':
+ if (c === '\\') {
+ err('\'\\\' not allowed in path.');
+ }
+
+ state = 'relative path';
+
+ if (c !== '/' && c !== '\\') {
+ continue;
+ }
+
+ break;
+
+ case 'relative path':
+ if (c === EOF || c === '/' || c === '\\' || !stateOverride && (c === '?' || c === '#')) {
+ if (c === '\\') {
+ err('\\ not allowed in relative path.');
+ }
+
+ var tmp;
+
+ if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
+ buffer = tmp;
+ }
+
+ if (buffer === '..') {
+ this._path.pop();
+
+ if (c !== '/' && c !== '\\') {
+ this._path.push('');
+ }
+ } else if (buffer === '.' && c !== '/' && c !== '\\') {
+ this._path.push('');
+ } else if (buffer !== '.') {
+ if (this._scheme === 'file' && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
+ buffer = buffer[0] + ':';
+ }
+
+ this._path.push(buffer);
+ }
+
+ buffer = '';
+
+ if (c === '?') {
+ this._query = '?';
+ state = 'query';
+ } else if (c === '#') {
+ this._fragment = '#';
+ state = 'fragment';
+ }
+ } else if (c !== '\t' && c !== '\n' && c !== '\r') {
+ buffer += percentEscape(c);
+ }
+
+ break;
+
+ case 'query':
+ if (!stateOverride && c === '#') {
+ this._fragment = '#';
+ state = 'fragment';
+ } else if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') {
+ this._query += percentEscapeQuery(c);
+ }
+
+ break;
+
+ case 'fragment':
+ if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') {
+ this._fragment += c;
+ }
+
+ break;
+ }
+
+ cursor++;
+ }
+ }
+
+ function clear() {
+ this._scheme = '';
+ this._schemeData = '';
+ this._username = '';
+ this._password = null;
+ this._host = '';
+ this._port = '';
+ this._path = [];
+ this._query = '';
+ this._fragment = '';
+ this._isInvalid = false;
+ this._isRelative = false;
+ }
+
+ function JURL(url, base) {
+ if (base !== undefined && !(base instanceof JURL)) {
+ base = new JURL(String(base));
+ }
+
+ this._url = url;
+ clear.call(this);
+ var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
+ parse.call(this, input, null, base);
+ }
+
+ JURL.prototype = {
+ toString: function toString() {
+ return this.href;
+ },
+
+ get href() {
+ if (this._isInvalid) {
+ return this._url;
+ }
+
+ var authority = '';
+
+ if (this._username !== '' || this._password !== null) {
+ authority = this._username + (this._password !== null ? ':' + this._password : '') + '@';
+ }
+
+ return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
+ },
+
+ set href(value) {
+ clear.call(this);
+ parse.call(this, value);
+ },
+
+ get protocol() {
+ return this._scheme + ':';
+ },
+
+ set protocol(value) {
+ if (this._isInvalid) {
+ return;
+ }
+
+ parse.call(this, value + ':', 'scheme start');
+ },
+
+ get host() {
+ return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
+ },
+
+ set host(value) {
+ if (this._isInvalid || !this._isRelative) {
+ return;
+ }
+
+ parse.call(this, value, 'host');
+ },
+
+ get hostname() {
+ return this._host;
+ },
+
+ set hostname(value) {
+ if (this._isInvalid || !this._isRelative) {
+ return;
+ }
+
+ parse.call(this, value, 'hostname');
+ },
+
+ get port() {
+ return this._port;
+ },
+
+ set port(value) {
+ if (this._isInvalid || !this._isRelative) {
+ return;
+ }
+
+ parse.call(this, value, 'port');
+ },
+
+ get pathname() {
+ return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
+ },
+
+ set pathname(value) {
+ if (this._isInvalid || !this._isRelative) {
+ return;
+ }
+
+ this._path = [];
+ parse.call(this, value, 'relative path start');
+ },
+
+ get search() {
+ return this._isInvalid || !this._query || this._query === '?' ? '' : this._query;
+ },
+
+ set search(value) {
+ if (this._isInvalid || !this._isRelative) {
+ return;
+ }
+
+ this._query = '?';
+
+ if (value[0] === '?') {
+ value = value.slice(1);
+ }
+
+ parse.call(this, value, 'query');
+ },
+
+ get hash() {
+ return this._isInvalid || !this._fragment || this._fragment === '#' ? '' : this._fragment;
+ },
+
+ set hash(value) {
+ if (this._isInvalid) {
+ return;
+ }
+
+ this._fragment = '#';
+
+ if (value[0] === '#') {
+ value = value.slice(1);
+ }
+
+ parse.call(this, value, 'fragment');
+ },
+
+ get origin() {
+ var host;
+
+ if (this._isInvalid || !this._scheme) {
+ return '';
+ }
+
+ switch (this._scheme) {
+ case 'data':
+ case 'file':
+ case 'javascript':
+ case 'mailto':
+ return 'null';
+
+ case 'blob':
+ try {
+ return new JURL(this._schemeData).origin || 'null';
+ } catch (_) {}
+
+ return 'null';
+ }
+
+ host = this.host;
+
+ if (!host) {
+ return '';
+ }
+
+ return this._scheme + '://' + host;
+ }
+
+ };
+ exports.URL = JURL;
+})();
+
+/***/ }),
+/* 147 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.getDocument = getDocument;
+exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
+exports.build = exports.version = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFWorker = exports.PDFDataRangeTransport = exports.LoopbackPort = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+var _display_utils = __w_pdfjs_require__(151);
+
+var _font_loader = __w_pdfjs_require__(152);
+
+var _api_compatibility = __w_pdfjs_require__(153);
+
+var _canvas = __w_pdfjs_require__(154);
+
+var _global_scope = _interopRequireDefault(__w_pdfjs_require__(3));
+
+var _worker_options = __w_pdfjs_require__(156);
+
+var _message_handler = __w_pdfjs_require__(157);
+
+var _metadata = __w_pdfjs_require__(158);
+
+var _transport_stream = __w_pdfjs_require__(160);
+
+var _webgl = __w_pdfjs_require__(161);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
+
+function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
+
+function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
+
+function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
+
+function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
+
+function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+function _typeof(obj) { 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); }
+
+var DEFAULT_RANGE_CHUNK_SIZE = 65536;
+var isWorkerDisabled = false;
+var fallbackWorkerSrc;
+var fakeWorkerFilesLoader = null;
+{
+ var useRequireEnsure = false;
+
+ if (typeof window === 'undefined') {
+ isWorkerDisabled = true;
+
+ if (typeof require.ensure === 'undefined') {
+ require.ensure = require('node-ensure');
+ }
+
+ useRequireEnsure = true;
+ } else if (typeof require !== 'undefined' && typeof require.ensure === 'function') {
+ useRequireEnsure = true;
+ }
+
+ if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
+ fallbackWorkerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
+ }
+
+ var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
+ fakeWorkerFilesLoader = useRequireEnsure ? function () {
+ return new Promise(function (resolve, reject) {
+ require.ensure([], function () {
+ try {
+ var worker;
+ worker = require('./pdf.worker.js');
+ resolve(worker.WorkerMessageHandler);
+ } catch (ex) {
+ reject(ex);
+ }
+ }, reject, 'pdfjsWorker');
+ });
+ } : dynamicLoaderSupported ? function () {
+ return new Promise(function (resolve, reject) {
+ requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
+ try {
+ resolve(worker.WorkerMessageHandler);
+ } catch (ex) {
+ reject(ex);
+ }
+ }, reject);
+ });
+ } : null;
+
+ if (!fallbackWorkerSrc && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && 'currentScript' in document) {
+ var pdfjsFilePath = document.currentScript && document.currentScript.src;
+
+ if (pdfjsFilePath) {
+ fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, '.worker$1$2');
+ }
+ }
+}
+var createPDFNetworkStream;
+
+function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
+ createPDFNetworkStream = pdfNetworkStreamFactory;
+}
+
+function getDocument(src) {
+ var task = new PDFDocumentLoadingTask();
+ var source;
+
+ if (typeof src === 'string') {
+ source = {
+ url: src
+ };
+ } else if ((0, _util.isArrayBuffer)(src)) {
+ source = {
+ data: src
+ };
+ } else if (src instanceof PDFDataRangeTransport) {
+ source = {
+ range: src
+ };
+ } else {
+ if (_typeof(src) !== 'object') {
+ throw new Error('Invalid parameter in getDocument, ' + 'need either Uint8Array, string or a parameter object');
+ }
+
+ if (!src.url && !src.data && !src.range) {
+ throw new Error('Invalid parameter object: need either .data, .range or .url');
+ }
+
+ source = src;
+ }
+
+ var params = Object.create(null);
+ var rangeTransport = null,
+ worker = null;
+
+ for (var key in source) {
+ if (key === 'url' && typeof window !== 'undefined') {
+ params[key] = new _util.URL(source[key], window.location).href;
+ continue;
+ } else if (key === 'range') {
+ rangeTransport = source[key];
+ continue;
+ } else if (key === 'worker') {
+ worker = source[key];
+ continue;
+ } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
+ var pdfBytes = source[key];
+
+ if (typeof pdfBytes === 'string') {
+ params[key] = (0, _util.stringToBytes)(pdfBytes);
+ } else if (_typeof(pdfBytes) === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
+ params[key] = new Uint8Array(pdfBytes);
+ } else if ((0, _util.isArrayBuffer)(pdfBytes)) {
+ params[key] = new Uint8Array(pdfBytes);
+ } else {
+ throw new Error('Invalid PDF binary data: either typed array, ' + 'string or array-like object is expected in the ' + 'data property.');
+ }
+
+ continue;
+ }
+
+ params[key] = source[key];
+ }
+
+ params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
+ params.CMapReaderFactory = params.CMapReaderFactory || _display_utils.DOMCMapReaderFactory;
+ params.ignoreErrors = params.stopAtErrors !== true;
+ params.pdfBug = params.pdfBug === true;
+ var NativeImageDecoderValues = Object.values(_util.NativeImageDecoding);
+
+ if (params.nativeImageDecoderSupport === undefined || !NativeImageDecoderValues.includes(params.nativeImageDecoderSupport)) {
+ params.nativeImageDecoderSupport = _api_compatibility.apiCompatibilityParams.nativeImageDecoderSupport || _util.NativeImageDecoding.DECODE;
+ }
+
+ if (!Number.isInteger(params.maxImageSize)) {
+ params.maxImageSize = -1;
+ }
+
+ if (typeof params.isEvalSupported !== 'boolean') {
+ params.isEvalSupported = true;
+ }
+
+ if (typeof params.disableFontFace !== 'boolean') {
+ params.disableFontFace = _api_compatibility.apiCompatibilityParams.disableFontFace || false;
+ }
+
+ if (typeof params.disableRange !== 'boolean') {
+ params.disableRange = false;
+ }
+
+ if (typeof params.disableStream !== 'boolean') {
+ params.disableStream = false;
+ }
+
+ if (typeof params.disableAutoFetch !== 'boolean') {
+ params.disableAutoFetch = false;
+ }
+
+ if (typeof params.disableCreateObjectURL !== 'boolean') {
+ params.disableCreateObjectURL = _api_compatibility.apiCompatibilityParams.disableCreateObjectURL || false;
+ }
+
+ (0, _util.setVerbosityLevel)(params.verbosity);
+
+ if (!worker) {
+ var workerParams = {
+ postMessageTransfers: params.postMessageTransfers,
+ verbosity: params.verbosity,
+ port: _worker_options.GlobalWorkerOptions.workerPort
+ };
+ worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
+ task._worker = worker;
+ }
+
+ var docId = task.docId;
+ worker.promise.then(function () {
+ if (task.destroyed) {
+ throw new Error('Loading aborted');
+ }
+
+ return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
+ if (task.destroyed) {
+ throw new Error('Loading aborted');
+ }
+
+ var networkStream;
+
+ if (rangeTransport) {
+ networkStream = new _transport_stream.PDFDataTransportStream({
+ length: params.length,
+ initialData: params.initialData,
+ progressiveDone: params.progressiveDone,
+ disableRange: params.disableRange,
+ disableStream: params.disableStream
+ }, rangeTransport);
+ } else if (!params.data) {
+ networkStream = createPDFNetworkStream({
+ url: params.url,
+ length: params.length,
+ httpHeaders: params.httpHeaders,
+ withCredentials: params.withCredentials,
+ rangeChunkSize: params.rangeChunkSize,
+ disableRange: params.disableRange,
+ disableStream: params.disableStream
+ });
+ }
+
+ var messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
+ messageHandler.postMessageTransfers = worker.postMessageTransfers;
+ var transport = new WorkerTransport(messageHandler, task, networkStream, params);
+ task._transport = transport;
+ messageHandler.send('Ready', null);
+ });
+ })["catch"](task._capability.reject);
+ return task;
+}
+
+function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
+ if (worker.destroyed) {
+ return Promise.reject(new Error('Worker was destroyed'));
+ }
+
+ if (pdfDataRangeTransport) {
+ source.length = pdfDataRangeTransport.length;
+ source.initialData = pdfDataRangeTransport.initialData;
+ source.progressiveDone = pdfDataRangeTransport.progressiveDone;
+ }
+
+ return worker.messageHandler.sendWithPromise('GetDocRequest', {
+ docId: docId,
+ apiVersion: '2.2.230',
+ source: {
+ data: source.data,
+ url: source.url,
+ password: source.password,
+ disableAutoFetch: source.disableAutoFetch,
+ rangeChunkSize: source.rangeChunkSize,
+ length: source.length
+ },
+ maxImageSize: source.maxImageSize,
+ disableFontFace: source.disableFontFace,
+ disableCreateObjectURL: source.disableCreateObjectURL,
+ postMessageTransfers: worker.postMessageTransfers,
+ docBaseUrl: source.docBaseUrl,
+ nativeImageDecoderSupport: source.nativeImageDecoderSupport,
+ ignoreErrors: source.ignoreErrors,
+ isEvalSupported: source.isEvalSupported
+ }).then(function (workerId) {
+ if (worker.destroyed) {
+ throw new Error('Worker was destroyed');
+ }
+
+ return workerId;
+ });
+}
+
+var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
+ var nextDocumentId = 0;
+
+ var PDFDocumentLoadingTask =
+ /*#__PURE__*/
+ function () {
+ function PDFDocumentLoadingTask() {
+ _classCallCheck(this, PDFDocumentLoadingTask);
+
+ this._capability = (0, _util.createPromiseCapability)();
+ this._transport = null;
+ this._worker = null;
+ this.docId = 'd' + nextDocumentId++;
+ this.destroyed = false;
+ this.onPassword = null;
+ this.onProgress = null;
+ this.onUnsupportedFeature = null;
+ }
+
+ _createClass(PDFDocumentLoadingTask, [{
+ key: "destroy",
+ value: function destroy() {
+ var _this = this;
+
+ this.destroyed = true;
+ var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
+ return transportDestroyed.then(function () {
+ _this._transport = null;
+
+ if (_this._worker) {
+ _this._worker.destroy();
+
+ _this._worker = null;
+ }
+ });
+ }
+ }, {
+ key: "then",
+ value: function then(onFulfilled, onRejected) {
+ (0, _display_utils.deprecated)('PDFDocumentLoadingTask.then method, ' + 'use the `promise` getter instead.');
+ return this.promise.then.apply(this.promise, arguments);
+ }
+ }, {
+ key: "promise",
+ get: function get() {
+ return this._capability.promise;
+ }
+ }]);
+
+ return PDFDocumentLoadingTask;
+ }();
+
+ return PDFDocumentLoadingTask;
+}();
+
+var PDFDataRangeTransport =
+/*#__PURE__*/
+function () {
+ function PDFDataRangeTransport(length, initialData) {
+ var progressiveDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
+ _classCallCheck(this, PDFDataRangeTransport);
+
+ this.length = length;
+ this.initialData = initialData;
+ this.progressiveDone = progressiveDone;
+ this._rangeListeners = [];
+ this._progressListeners = [];
+ this._progressiveReadListeners = [];
+ this._progressiveDoneListeners = [];
+ this._readyCapability = (0, _util.createPromiseCapability)();
+ }
+
+ _createClass(PDFDataRangeTransport, [{
+ key: "addRangeListener",
+ value: function addRangeListener(listener) {
+ this._rangeListeners.push(listener);
+ }
+ }, {
+ key: "addProgressListener",
+ value: function addProgressListener(listener) {
+ this._progressListeners.push(listener);
+ }
+ }, {
+ key: "addProgressiveReadListener",
+ value: function addProgressiveReadListener(listener) {
+ this._progressiveReadListeners.push(listener);
+ }
+ }, {
+ key: "addProgressiveDoneListener",
+ value: function addProgressiveDoneListener(listener) {
+ this._progressiveDoneListeners.push(listener);
+ }
+ }, {
+ key: "onDataRange",
+ value: function onDataRange(begin, chunk) {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = this._rangeListeners[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var listener = _step.value;
+ listener(begin, chunk);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+ _iterator["return"]();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ }
+ }, {
+ key: "onDataProgress",
+ value: function onDataProgress(loaded, total) {
+ var _this2 = this;
+
+ this._readyCapability.promise.then(function () {
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ for (var _iterator2 = _this2._progressListeners[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var listener = _step2.value;
+ listener(loaded, total);
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+ _iterator2["return"]();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ });
+ }
+ }, {
+ key: "onDataProgressiveRead",
+ value: function onDataProgressiveRead(chunk) {
+ var _this3 = this;
+
+ this._readyCapability.promise.then(function () {
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+
+ try {
+ for (var _iterator3 = _this3._progressiveReadListeners[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
+ var listener = _step3.value;
+ listener(chunk);
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
+ _iterator3["return"]();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+ });
+ }
+ }, {
+ key: "onDataProgressiveDone",
+ value: function onDataProgressiveDone() {
+ var _this4 = this;
+
+ this._readyCapability.promise.then(function () {
+ var _iteratorNormalCompletion4 = true;
+ var _didIteratorError4 = false;
+ var _iteratorError4 = undefined;
+
+ try {
+ for (var _iterator4 = _this4._progressiveDoneListeners[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
+ var listener = _step4.value;
+ listener();
+ }
+ } catch (err) {
+ _didIteratorError4 = true;
+ _iteratorError4 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
+ _iterator4["return"]();
+ }
+ } finally {
+ if (_didIteratorError4) {
+ throw _iteratorError4;
+ }
+ }
+ }
+ });
+ }
+ }, {
+ key: "transportReady",
+ value: function transportReady() {
+ this._readyCapability.resolve();
+ }
+ }, {
+ key: "requestDataRange",
+ value: function requestDataRange(begin, end) {
+ (0, _util.unreachable)('Abstract method PDFDataRangeTransport.requestDataRange');
+ }
+ }, {
+ key: "abort",
+ value: function abort() {}
+ }]);
+
+ return PDFDataRangeTransport;
+}();
+
+exports.PDFDataRangeTransport = PDFDataRangeTransport;
+
+var PDFDocumentProxy =
+/*#__PURE__*/
+function () {
+ function PDFDocumentProxy(pdfInfo, transport) {
+ _classCallCheck(this, PDFDocumentProxy);
+
+ this._pdfInfo = pdfInfo;
+ this._transport = transport;
+ }
+
+ _createClass(PDFDocumentProxy, [{
+ key: "getPage",
+ value: function getPage(pageNumber) {
+ return this._transport.getPage(pageNumber);
+ }
+ }, {
+ key: "getPageIndex",
+ value: function getPageIndex(ref) {
+ return this._transport.getPageIndex(ref);
+ }
+ }, {
+ key: "getDestinations",
+ value: function getDestinations() {
+ return this._transport.getDestinations();
+ }
+ }, {
+ key: "getDestination",
+ value: function getDestination(id) {
+ return this._transport.getDestination(id);
+ }
+ }, {
+ key: "getPageLabels",
+ value: function getPageLabels() {
+ return this._transport.getPageLabels();
+ }
+ }, {
+ key: "getPageLayout",
+ value: function getPageLayout() {
+ return this._transport.getPageLayout();
+ }
+ }, {
+ key: "getPageMode",
+ value: function getPageMode() {
+ return this._transport.getPageMode();
+ }
+ }, {
+ key: "getViewerPreferences",
+ value: function getViewerPreferences() {
+ return this._transport.getViewerPreferences();
+ }
+ }, {
+ key: "getOpenActionDestination",
+ value: function getOpenActionDestination() {
+ return this._transport.getOpenActionDestination();
+ }
+ }, {
+ key: "getAttachments",
+ value: function getAttachments() {
+ return this._transport.getAttachments();
+ }
+ }, {
+ key: "getJavaScript",
+ value: function getJavaScript() {
+ return this._transport.getJavaScript();
+ }
+ }, {
+ key: "getOutline",
+ value: function getOutline() {
+ return this._transport.getOutline();
+ }
+ }, {
+ key: "getPermissions",
+ value: function getPermissions() {
+ return this._transport.getPermissions();
+ }
+ }, {
+ key: "getMetadata",
+ value: function getMetadata() {
+ return this._transport.getMetadata();
+ }
+ }, {
+ key: "getData",
+ value: function getData() {
+ return this._transport.getData();
+ }
+ }, {
+ key: "getDownloadInfo",
+ value: function getDownloadInfo() {
+ return this._transport.downloadInfoCapability.promise;
+ }
+ }, {
+ key: "getStats",
+ value: function getStats() {
+ return this._transport.getStats();
+ }
+ }, {
+ key: "cleanup",
+ value: function cleanup() {
+ this._transport.startCleanup();
+ }
+ }, {
+ key: "destroy",
+ value: function destroy() {
+ return this.loadingTask.destroy();
+ }
+ }, {
+ key: "numPages",
+ get: function get() {
+ return this._pdfInfo.numPages;
+ }
+ }, {
+ key: "fingerprint",
+ get: function get() {
+ return this._pdfInfo.fingerprint;
+ }
+ }, {
+ key: "loadingParams",
+ get: function get() {
+ return this._transport.loadingParams;
+ }
+ }, {
+ key: "loadingTask",
+ get: function get() {
+ return this._transport.loadingTask;
+ }
+ }]);
+
+ return PDFDocumentProxy;
+}();
+
+exports.PDFDocumentProxy = PDFDocumentProxy;
+
+var PDFPageProxy =
+/*#__PURE__*/
+function () {
+ function PDFPageProxy(pageIndex, pageInfo, transport) {
+ var pdfBug = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
+
+ _classCallCheck(this, PDFPageProxy);
+
+ this.pageIndex = pageIndex;
+ this._pageInfo = pageInfo;
+ this._transport = transport;
+ this._stats = pdfBug ? new _display_utils.StatTimer() : _display_utils.DummyStatTimer;
+ this._pdfBug = pdfBug;
+ this.commonObjs = transport.commonObjs;
+ this.objs = new PDFObjects();
+ this.cleanupAfterRender = false;
+ this.pendingCleanup = false;
+ this.intentStates = Object.create(null);
+ this.destroyed = false;
+ }
+
+ _createClass(PDFPageProxy, [{
+ key: "getViewport",
+ value: function getViewport() {
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ scale = _ref.scale,
+ _ref$rotation = _ref.rotation,
+ rotation = _ref$rotation === void 0 ? this.rotate : _ref$rotation,
+ _ref$dontFlip = _ref.dontFlip,
+ dontFlip = _ref$dontFlip === void 0 ? false : _ref$dontFlip;
+
+ if (arguments.length > 1 || typeof arguments[0] === 'number') {
+ (0, _display_utils.deprecated)('getViewport is called with obsolete arguments.');
+ scale = arguments[0];
+ rotation = typeof arguments[1] === 'number' ? arguments[1] : this.rotate;
+ dontFlip = typeof arguments[2] === 'boolean' ? arguments[2] : false;
+ }
+
+ return new _display_utils.PageViewport({
+ viewBox: this.view,
+ scale: scale,
+ rotation: rotation,
+ dontFlip: dontFlip
+ });
+ }
+ }, {
+ key: "getAnnotations",
+ value: function getAnnotations() {
+ var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ _ref2$intent = _ref2.intent,
+ intent = _ref2$intent === void 0 ? null : _ref2$intent;
+
+ if (!this.annotationsPromise || this.annotationsIntent !== intent) {
+ this.annotationsPromise = this._transport.getAnnotations(this.pageIndex, intent);
+ this.annotationsIntent = intent;
+ }
+
+ return this.annotationsPromise;
+ }
+ }, {
+ key: "render",
+ value: function render(_ref3) {
+ var _this5 = this;
+
+ var canvasContext = _ref3.canvasContext,
+ viewport = _ref3.viewport,
+ _ref3$intent = _ref3.intent,
+ intent = _ref3$intent === void 0 ? 'display' : _ref3$intent,
+ _ref3$enableWebGL = _ref3.enableWebGL,
+ enableWebGL = _ref3$enableWebGL === void 0 ? false : _ref3$enableWebGL,
+ _ref3$renderInteracti = _ref3.renderInteractiveForms,
+ renderInteractiveForms = _ref3$renderInteracti === void 0 ? false : _ref3$renderInteracti,
+ _ref3$transform = _ref3.transform,
+ transform = _ref3$transform === void 0 ? null : _ref3$transform,
+ _ref3$imageLayer = _ref3.imageLayer,
+ imageLayer = _ref3$imageLayer === void 0 ? null : _ref3$imageLayer,
+ _ref3$canvasFactory = _ref3.canvasFactory,
+ canvasFactory = _ref3$canvasFactory === void 0 ? null : _ref3$canvasFactory,
+ _ref3$background = _ref3.background,
+ background = _ref3$background === void 0 ? null : _ref3$background;
+ var stats = this._stats;
+ stats.time('Overall');
+ this.pendingCleanup = false;
+ var renderingIntent = intent === 'print' ? 'print' : 'display';
+ var canvasFactoryInstance = canvasFactory || new _display_utils.DOMCanvasFactory();
+ var webGLContext = new _webgl.WebGLContext({
+ enable: enableWebGL
+ });
+
+ if (!this.intentStates[renderingIntent]) {
+ this.intentStates[renderingIntent] = Object.create(null);
+ }
+
+ var intentState = this.intentStates[renderingIntent];
+
+ if (!intentState.displayReadyCapability) {
+ intentState.receivingOperatorList = true;
+ intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
+ intentState.operatorList = {
+ fnArray: [],
+ argsArray: [],
+ lastChunk: false
+ };
+ stats.time('Page Request');
+
+ this._transport.messageHandler.send('RenderPageRequest', {
+ pageIndex: this.pageNumber - 1,
+ intent: renderingIntent,
+ renderInteractiveForms: renderInteractiveForms === true
+ });
+ }
+
+ var complete = function complete(error) {
+ var i = intentState.renderTasks.indexOf(internalRenderTask);
+
+ if (i >= 0) {
+ intentState.renderTasks.splice(i, 1);
+ }
+
+ if (_this5.cleanupAfterRender || renderingIntent === 'print') {
+ _this5.pendingCleanup = true;
+ }
+
+ _this5._tryCleanup();
+
+ if (error) {
+ internalRenderTask.capability.reject(error);
+ } else {
+ internalRenderTask.capability.resolve();
+ }
+
+ stats.timeEnd('Rendering');
+ stats.timeEnd('Overall');
+ };
+
+ var internalRenderTask = new InternalRenderTask({
+ callback: complete,
+ params: {
+ canvasContext: canvasContext,
+ viewport: viewport,
+ transform: transform,
+ imageLayer: imageLayer,
+ background: background
+ },
+ objs: this.objs,
+ commonObjs: this.commonObjs,
+ operatorList: intentState.operatorList,
+ pageNumber: this.pageNumber,
+ canvasFactory: canvasFactoryInstance,
+ webGLContext: webGLContext,
+ useRequestAnimationFrame: renderingIntent !== 'print',
+ pdfBug: this._pdfBug
+ });
+
+ if (!intentState.renderTasks) {
+ intentState.renderTasks = [];
+ }
+
+ intentState.renderTasks.push(internalRenderTask);
+ var renderTask = internalRenderTask.task;
+ intentState.displayReadyCapability.promise.then(function (transparency) {
+ if (_this5.pendingCleanup) {
+ complete();
+ return;
+ }
+
+ stats.time('Rendering');
+ internalRenderTask.initializeGraphics(transparency);
+ internalRenderTask.operatorListChanged();
+ })["catch"](complete);
+ return renderTask;
+ }
+ }, {
+ key: "getOperatorList",
+ value: function getOperatorList() {
+ function operatorListChanged() {
+ if (intentState.operatorList.lastChunk) {
+ intentState.opListReadCapability.resolve(intentState.operatorList);
+ var i = intentState.renderTasks.indexOf(opListTask);
+
+ if (i >= 0) {
+ intentState.renderTasks.splice(i, 1);
+ }
+ }
+ }
+
+ var renderingIntent = 'oplist';
+
+ if (!this.intentStates[renderingIntent]) {
+ this.intentStates[renderingIntent] = Object.create(null);
+ }
+
+ var intentState = this.intentStates[renderingIntent];
+ var opListTask;
+
+ if (!intentState.opListReadCapability) {
+ opListTask = {};
+ opListTask.operatorListChanged = operatorListChanged;
+ intentState.receivingOperatorList = true;
+ intentState.opListReadCapability = (0, _util.createPromiseCapability)();
+ intentState.renderTasks = [];
+ intentState.renderTasks.push(opListTask);
+ intentState.operatorList = {
+ fnArray: [],
+ argsArray: [],
+ lastChunk: false
+ };
+
+ this._stats.time('Page Request');
+
+ this._transport.messageHandler.send('RenderPageRequest', {
+ pageIndex: this.pageIndex,
+ intent: renderingIntent
+ });
+ }
+
+ return intentState.opListReadCapability.promise;
+ }
+ }, {
+ key: "streamTextContent",
+ value: function streamTextContent() {
+ var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ _ref4$normalizeWhites = _ref4.normalizeWhitespace,
+ normalizeWhitespace = _ref4$normalizeWhites === void 0 ? false : _ref4$normalizeWhites,
+ _ref4$disableCombineT = _ref4.disableCombineTextItems,
+ disableCombineTextItems = _ref4$disableCombineT === void 0 ? false : _ref4$disableCombineT;
+
+ var TEXT_CONTENT_CHUNK_SIZE = 100;
+ return this._transport.messageHandler.sendWithStream('GetTextContent', {
+ pageIndex: this.pageNumber - 1,
+ normalizeWhitespace: normalizeWhitespace === true,
+ combineTextItems: disableCombineTextItems !== true
+ }, {
+ highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
+ size: function size(textContent) {
+ return textContent.items.length;
+ }
+ });
+ }
+ }, {
+ key: "getTextContent",
+ value: function getTextContent() {
+ var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var readableStream = this.streamTextContent(params);
+ return new Promise(function (resolve, reject) {
+ function pump() {
+ reader.read().then(function (_ref5) {
+ var _textContent$items;
+
+ var value = _ref5.value,
+ done = _ref5.done;
+
+ if (done) {
+ resolve(textContent);
+ return;
+ }
+
+ Object.assign(textContent.styles, value.styles);
+
+ (_textContent$items = textContent.items).push.apply(_textContent$items, _toConsumableArray(value.items));
+
+ pump();
+ }, reject);
+ }
+
+ var reader = readableStream.getReader();
+ var textContent = {
+ items: [],
+ styles: Object.create(null)
+ };
+ pump();
+ });
+ }
+ }, {
+ key: "_destroy",
+ value: function _destroy() {
+ this.destroyed = true;
+ this._transport.pageCache[this.pageIndex] = null;
+ var waitOn = [];
+ Object.keys(this.intentStates).forEach(function (intent) {
+ if (intent === 'oplist') {
+ return;
+ }
+
+ var intentState = this.intentStates[intent];
+ intentState.renderTasks.forEach(function (renderTask) {
+ var renderCompleted = renderTask.capability.promise["catch"](function () {});
+ waitOn.push(renderCompleted);
+ renderTask.cancel();
+ });
+ }, this);
+ this.objs.clear();
+ this.annotationsPromise = null;
+ this.pendingCleanup = false;
+ return Promise.all(waitOn);
+ }
+ }, {
+ key: "cleanup",
+ value: function cleanup() {
+ var resetStats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
+ this.pendingCleanup = true;
+
+ this._tryCleanup(resetStats);
+ }
+ }, {
+ key: "_tryCleanup",
+ value: function _tryCleanup() {
+ var resetStats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
+
+ if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
+ var intentState = this.intentStates[intent];
+ return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
+ }, this)) {
+ return;
+ }
+
+ Object.keys(this.intentStates).forEach(function (intent) {
+ delete this.intentStates[intent];
+ }, this);
+ this.objs.clear();
+ this.annotationsPromise = null;
+
+ if (resetStats && this._stats instanceof _display_utils.StatTimer) {
+ this._stats = new _display_utils.StatTimer();
+ }
+
+ this.pendingCleanup = false;
+ }
+ }, {
+ key: "_startRenderPage",
+ value: function _startRenderPage(transparency, intent) {
+ var intentState = this.intentStates[intent];
+
+ if (intentState.displayReadyCapability) {
+ intentState.displayReadyCapability.resolve(transparency);
+ }
+ }
+ }, {
+ key: "_renderPageChunk",
+ value: function _renderPageChunk(operatorListChunk, intent) {
+ var intentState = this.intentStates[intent];
+
+ for (var i = 0, ii = operatorListChunk.length; i < ii; i++) {
+ intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
+ intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
+ }
+
+ intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
+
+ for (var _i = 0; _i < intentState.renderTasks.length; _i++) {
+ intentState.renderTasks[_i].operatorListChanged();
+ }
+
+ if (operatorListChunk.lastChunk) {
+ intentState.receivingOperatorList = false;
+
+ this._tryCleanup();
+ }
+ }
+ }, {
+ key: "pageNumber",
+ get: function get() {
+ return this.pageIndex + 1;
+ }
+ }, {
+ key: "rotate",
+ get: function get() {
+ return this._pageInfo.rotate;
+ }
+ }, {
+ key: "ref",
+ get: function get() {
+ return this._pageInfo.ref;
+ }
+ }, {
+ key: "userUnit",
+ get: function get() {
+ return this._pageInfo.userUnit;
+ }
+ }, {
+ key: "view",
+ get: function get() {
+ return this._pageInfo.view;
+ }
+ }, {
+ key: "stats",
+ get: function get() {
+ return this._stats instanceof _display_utils.StatTimer ? this._stats : null;
+ }
+ }]);
+
+ return PDFPageProxy;
+}();
+
+exports.PDFPageProxy = PDFPageProxy;
+
+var LoopbackPort =
+/*#__PURE__*/
+function () {
+ function LoopbackPort() {
+ var defer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+
+ _classCallCheck(this, LoopbackPort);
+
+ this._listeners = [];
+ this._defer = defer;
+ this._deferred = Promise.resolve(undefined);
+ }
+
+ _createClass(LoopbackPort, [{
+ key: "postMessage",
+ value: function postMessage(obj, transfers) {
+ var _this6 = this;
+
+ function cloneValue(value) {
+ if (_typeof(value) !== 'object' || value === null) {
+ return value;
+ }
+
+ if (cloned.has(value)) {
+ return cloned.get(value);
+ }
+
+ var buffer, result;
+
+ if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
+ var transferable = transfers && transfers.includes(buffer);
+
+ if (value === buffer) {
+ result = value;
+ } else if (transferable) {
+ result = new value.constructor(buffer, value.byteOffset, value.byteLength);
+ } else {
+ result = new value.constructor(value);
+ }
+
+ cloned.set(value, result);
+ return result;
+ }
+
+ result = Array.isArray(value) ? [] : {};
+ cloned.set(value, result);
+
+ for (var i in value) {
+ var desc = void 0,
+ p = value;
+
+ while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
+ p = Object.getPrototypeOf(p);
+ }
+
+ if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
+ continue;
+ }
+
+ result[i] = cloneValue(desc.value);
+ }
+
+ return result;
+ }
+
+ if (!this._defer) {
+ this._listeners.forEach(function (listener) {
+ listener.call(this, {
+ data: obj
+ });
+ }, this);
+
+ return;
+ }
+
+ var cloned = new WeakMap();
+ var e = {
+ data: cloneValue(obj)
+ };
+
+ this._deferred.then(function () {
+ _this6._listeners.forEach(function (listener) {
+ listener.call(this, e);
+ }, _this6);
+ });
+ }
+ }, {
+ key: "addEventListener",
+ value: function addEventListener(name, listener) {
+ this._listeners.push(listener);
+ }
+ }, {
+ key: "removeEventListener",
+ value: function removeEventListener(name, listener) {
+ var i = this._listeners.indexOf(listener);
+
+ this._listeners.splice(i, 1);
+ }
+ }, {
+ key: "terminate",
+ value: function terminate() {
+ this._listeners.length = 0;
+ }
+ }]);
+
+ return LoopbackPort;
+}();
+
+exports.LoopbackPort = LoopbackPort;
+
+var PDFWorker = function PDFWorkerClosure() {
+ var pdfWorkerPorts = new WeakMap();
+ var nextFakeWorkerId = 0;
+ var fakeWorkerFilesLoadedCapability;
+
+ function _getWorkerSrc() {
+ if (_worker_options.GlobalWorkerOptions.workerSrc) {
+ return _worker_options.GlobalWorkerOptions.workerSrc;
+ }
+
+ if (typeof fallbackWorkerSrc !== 'undefined') {
+ return fallbackWorkerSrc;
+ }
+
+ throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
+ }
+
+ function getMainThreadWorkerMessageHandler() {
+ try {
+ if (typeof window !== 'undefined') {
+ return window.pdfjsWorker && window.pdfjsWorker.WorkerMessageHandler;
+ }
+ } catch (ex) {}
+
+ return null;
+ }
+
+ function setupFakeWorkerGlobal() {
+ if (fakeWorkerFilesLoadedCapability) {
+ return fakeWorkerFilesLoadedCapability.promise;
+ }
+
+ fakeWorkerFilesLoadedCapability = (0, _util.createPromiseCapability)();
+ var mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
+
+ if (mainWorkerMessageHandler) {
+ fakeWorkerFilesLoadedCapability.resolve(mainWorkerMessageHandler);
+ return fakeWorkerFilesLoadedCapability.promise;
+ }
+
+ var loader = fakeWorkerFilesLoader || function () {
+ return (0, _display_utils.loadScript)(_getWorkerSrc()).then(function () {
+ return window.pdfjsWorker.WorkerMessageHandler;
+ });
+ };
+
+ loader().then(fakeWorkerFilesLoadedCapability.resolve, fakeWorkerFilesLoadedCapability.reject);
+ return fakeWorkerFilesLoadedCapability.promise;
+ }
+
+ function createCDNWrapper(url) {
+ var wrapper = 'importScripts(\'' + url + '\');';
+ return _util.URL.createObjectURL(new Blob([wrapper]));
+ }
+
+ var PDFWorker =
+ /*#__PURE__*/
+ function () {
+ function PDFWorker() {
+ var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ _ref6$name = _ref6.name,
+ name = _ref6$name === void 0 ? null : _ref6$name,
+ _ref6$port = _ref6.port,
+ port = _ref6$port === void 0 ? null : _ref6$port,
+ _ref6$postMessageTran = _ref6.postMessageTransfers,
+ postMessageTransfers = _ref6$postMessageTran === void 0 ? true : _ref6$postMessageTran,
+ _ref6$verbosity = _ref6.verbosity,
+ verbosity = _ref6$verbosity === void 0 ? (0, _util.getVerbosityLevel)() : _ref6$verbosity;
+
+ _classCallCheck(this, PDFWorker);
+
+ if (port && pdfWorkerPorts.has(port)) {
+ throw new Error('Cannot use more than one PDFWorker per port');
+ }
+
+ this.name = name;
+ this.destroyed = false;
+ this.postMessageTransfers = postMessageTransfers !== false;
+ this.verbosity = verbosity;
+ this._readyCapability = (0, _util.createPromiseCapability)();
+ this._port = null;
+ this._webWorker = null;
+ this._messageHandler = null;
+
+ if (port) {
+ pdfWorkerPorts.set(port, this);
+
+ this._initializeFromPort(port);
+
+ return;
+ }
+
+ this._initialize();
+ }
+
+ _createClass(PDFWorker, [{
+ key: "_initializeFromPort",
+ value: function _initializeFromPort(port) {
+ this._port = port;
+ this._messageHandler = new _message_handler.MessageHandler('main', 'worker', port);
+
+ this._messageHandler.on('ready', function () {});
+
+ this._readyCapability.resolve();
+ }
+ }, {
+ key: "_initialize",
+ value: function _initialize() {
+ var _this7 = this;
+
+ if (typeof Worker !== 'undefined' && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) {
+ var workerSrc = _getWorkerSrc();
+
+ try {
+ if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
+ workerSrc = createCDNWrapper(new _util.URL(workerSrc, window.location).href);
+ }
+
+ var worker = new Worker(workerSrc);
+ var messageHandler = new _message_handler.MessageHandler('main', 'worker', worker);
+
+ var terminateEarly = function terminateEarly() {
+ worker.removeEventListener('error', onWorkerError);
+ messageHandler.destroy();
+ worker.terminate();
+
+ if (_this7.destroyed) {
+ _this7._readyCapability.reject(new Error('Worker was destroyed'));
+ } else {
+ _this7._setupFakeWorker();
+ }
+ };
+
+ var onWorkerError = function onWorkerError() {
+ if (!_this7._webWorker) {
+ terminateEarly();
+ }
+ };
+
+ worker.addEventListener('error', onWorkerError);
+ messageHandler.on('test', function (data) {
+ worker.removeEventListener('error', onWorkerError);
+
+ if (_this7.destroyed) {
+ terminateEarly();
+ return;
+ }
+
+ if (data && data.supportTypedArray) {
+ _this7._messageHandler = messageHandler;
+ _this7._port = worker;
+ _this7._webWorker = worker;
+
+ if (!data.supportTransfers) {
+ _this7.postMessageTransfers = false;
+ }
+
+ _this7._readyCapability.resolve();
+
+ messageHandler.send('configure', {
+ verbosity: _this7.verbosity
+ });
+ } else {
+ _this7._setupFakeWorker();
+
+ messageHandler.destroy();
+ worker.terminate();
+ }
+ });
+ messageHandler.on('ready', function (data) {
+ worker.removeEventListener('error', onWorkerError);
+
+ if (_this7.destroyed) {
+ terminateEarly();
+ return;
+ }
+
+ try {
+ sendTest();
+ } catch (e) {
+ _this7._setupFakeWorker();
+ }
+ });
+
+ var sendTest = function sendTest() {
+ var testObj = new Uint8Array([_this7.postMessageTransfers ? 255 : 0]);
+
+ try {
+ messageHandler.send('test', testObj, [testObj.buffer]);
+ } catch (ex) {
+ (0, _util.info)('Cannot use postMessage transfers');
+ testObj[0] = 0;
+ messageHandler.send('test', testObj);
+ }
+ };
+
+ sendTest();
+ return;
+ } catch (e) {
+ (0, _util.info)('The worker has been disabled.');
+ }
+ }
+
+ this._setupFakeWorker();
+ }
+ }, {
+ key: "_setupFakeWorker",
+ value: function _setupFakeWorker() {
+ var _this8 = this;
+
+ if (!isWorkerDisabled) {
+ (0, _util.warn)('Setting up fake worker.');
+ isWorkerDisabled = true;
+ }
+
+ setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
+ if (_this8.destroyed) {
+ _this8._readyCapability.reject(new Error('Worker was destroyed'));
+
+ return;
+ }
+
+ var port = new LoopbackPort();
+ _this8._port = port;
+ var id = 'fake' + nextFakeWorkerId++;
+ var workerHandler = new _message_handler.MessageHandler(id + '_worker', id, port);
+ WorkerMessageHandler.setup(workerHandler, port);
+ var messageHandler = new _message_handler.MessageHandler(id, id + '_worker', port);
+ _this8._messageHandler = messageHandler;
+
+ _this8._readyCapability.resolve();
+ })["catch"](function (reason) {
+ _this8._readyCapability.reject(new Error("Setting up fake worker failed: \"".concat(reason.message, "\".")));
+ });
+ }
+ }, {
+ key: "destroy",
+ value: function destroy() {
+ this.destroyed = true;
+
+ if (this._webWorker) {
+ this._webWorker.terminate();
+
+ this._webWorker = null;
+ }
+
+ pdfWorkerPorts["delete"](this._port);
+ this._port = null;
+
+ if (this._messageHandler) {
+ this._messageHandler.destroy();
+
+ this._messageHandler = null;
+ }
+ }
+ }, {
+ key: "promise",
+ get: function get() {
+ return this._readyCapability.promise;
+ }
+ }, {
+ key: "port",
+ get: function get() {
+ return this._port;
+ }
+ }, {
+ key: "messageHandler",
+ get: function get() {
+ return this._messageHandler;
+ }
+ }], [{
+ key: "fromPort",
+ value: function fromPort(params) {
+ if (!params || !params.port) {
+ throw new Error('PDFWorker.fromPort - invalid method signature.');
+ }
+
+ if (pdfWorkerPorts.has(params.port)) {
+ return pdfWorkerPorts.get(params.port);
+ }
+
+ return new PDFWorker(params);
+ }
+ }, {
+ key: "getWorkerSrc",
+ value: function getWorkerSrc() {
+ return _getWorkerSrc();
+ }
+ }]);
+
+ return PDFWorker;
+ }();
+
+ return PDFWorker;
+}();
+
+exports.PDFWorker = PDFWorker;
+
+var WorkerTransport =
+/*#__PURE__*/
+function () {
+ function WorkerTransport(messageHandler, loadingTask, networkStream, params) {
+ _classCallCheck(this, WorkerTransport);
+
+ this.messageHandler = messageHandler;
+ this.loadingTask = loadingTask;
+ this.commonObjs = new PDFObjects();
+ this.fontLoader = new _font_loader.FontLoader({
+ docId: loadingTask.docId,
+ onUnsupportedFeature: this._onUnsupportedFeature.bind(this)
+ });
+ this._params = params;
+ this.CMapReaderFactory = new params.CMapReaderFactory({
+ baseUrl: params.cMapUrl,
+ isCompressed: params.cMapPacked
+ });
+ this.destroyed = false;
+ this.destroyCapability = null;
+ this._passwordCapability = null;
+ this._networkStream = networkStream;
+ this._fullReader = null;
+ this._lastProgress = null;
+ this.pageCache = [];
+ this.pagePromises = [];
+ this.downloadInfoCapability = (0, _util.createPromiseCapability)();
+ this.setupMessageHandler();
+ }
+
+ _createClass(WorkerTransport, [{
+ key: "destroy",
+ value: function destroy() {
+ var _this9 = this;
+
+ if (this.destroyCapability) {
+ return this.destroyCapability.promise;
+ }
+
+ this.destroyed = true;
+ this.destroyCapability = (0, _util.createPromiseCapability)();
+
+ if (this._passwordCapability) {
+ this._passwordCapability.reject(new Error('Worker was destroyed during onPassword callback'));
+ }
+
+ var waitOn = [];
+ this.pageCache.forEach(function (page) {
+ if (page) {
+ waitOn.push(page._destroy());
+ }
+ });
+ this.pageCache.length = 0;
+ this.pagePromises.length = 0;
+ var terminated = this.messageHandler.sendWithPromise('Terminate', null);
+ waitOn.push(terminated);
+ Promise.all(waitOn).then(function () {
+ _this9.fontLoader.clear();
+
+ if (_this9._networkStream) {
+ _this9._networkStream.cancelAllRequests();
+ }
+
+ if (_this9.messageHandler) {
+ _this9.messageHandler.destroy();
+
+ _this9.messageHandler = null;
+ }
+
+ _this9.destroyCapability.resolve();
+ }, this.destroyCapability.reject);
+ return this.destroyCapability.promise;
+ }
+ }, {
+ key: "setupMessageHandler",
+ value: function setupMessageHandler() {
+ var messageHandler = this.messageHandler,
+ loadingTask = this.loadingTask;
+ messageHandler.on('GetReader', function (data, sink) {
+ var _this10 = this;
+
+ (0, _util.assert)(this._networkStream);
+ this._fullReader = this._networkStream.getFullReader();
+
+ this._fullReader.onProgress = function (evt) {
+ _this10._lastProgress = {
+ loaded: evt.loaded,
+ total: evt.total
+ };
+ };
+
+ sink.onPull = function () {
+ _this10._fullReader.read().then(function (_ref7) {
+ var value = _ref7.value,
+ done = _ref7.done;
+
+ if (done) {
+ sink.close();
+ return;
+ }
+
+ (0, _util.assert)((0, _util.isArrayBuffer)(value));
+ sink.enqueue(new Uint8Array(value), 1, [value]);
+ })["catch"](function (reason) {
+ sink.error(reason);
+ });
+ };
+
+ sink.onCancel = function (reason) {
+ _this10._fullReader.cancel(reason);
+ };
+ }, this);
+ messageHandler.on('ReaderHeadersReady', function (data) {
+ var _this11 = this;
+
+ var headersCapability = (0, _util.createPromiseCapability)();
+ var fullReader = this._fullReader;
+ fullReader.headersReady.then(function () {
+ if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
+ if (_this11._lastProgress && loadingTask.onProgress) {
+ loadingTask.onProgress(_this11._lastProgress);
+ }
+
+ fullReader.onProgress = function (evt) {
+ if (loadingTask.onProgress) {
+ loadingTask.onProgress({
+ loaded: evt.loaded,
+ total: evt.total
+ });
+ }
+ };
+ }
+
+ headersCapability.resolve({
+ isStreamingSupported: fullReader.isStreamingSupported,
+ isRangeSupported: fullReader.isRangeSupported,
+ contentLength: fullReader.contentLength
+ });
+ }, headersCapability.reject);
+ return headersCapability.promise;
+ }, this);
+ messageHandler.on('GetRangeReader', function (data, sink) {
+ (0, _util.assert)(this._networkStream);
+
+ var rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
+
+ if (!rangeReader) {
+ sink.close();
+ return;
+ }
+
+ sink.onPull = function () {
+ rangeReader.read().then(function (_ref8) {
+ var value = _ref8.value,
+ done = _ref8.done;
+
+ if (done) {
+ sink.close();
+ return;
+ }
+
+ (0, _util.assert)((0, _util.isArrayBuffer)(value));
+ sink.enqueue(new Uint8Array(value), 1, [value]);
+ })["catch"](function (reason) {
+ sink.error(reason);
+ });
+ };
+
+ sink.onCancel = function (reason) {
+ rangeReader.cancel(reason);
+ };
+ }, this);
+ messageHandler.on('GetDoc', function (_ref9) {
+ var pdfInfo = _ref9.pdfInfo;
+ this._numPages = pdfInfo.numPages;
+
+ loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
+ }, this);
+ messageHandler.on('PasswordRequest', function (exception) {
+ var _this12 = this;
+
+ this._passwordCapability = (0, _util.createPromiseCapability)();
+
+ if (loadingTask.onPassword) {
+ var updatePassword = function updatePassword(password) {
+ _this12._passwordCapability.resolve({
+ password: password
+ });
+ };
+
+ try {
+ loadingTask.onPassword(updatePassword, exception.code);
+ } catch (ex) {
+ this._passwordCapability.reject(ex);
+ }
+ } else {
+ this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
+ }
+
+ return this._passwordCapability.promise;
+ }, this);
+ messageHandler.on('PasswordException', function (exception) {
+ loadingTask._capability.reject(new _util.PasswordException(exception.message, exception.code));
+ }, this);
+ messageHandler.on('InvalidPDF', function (exception) {
+ loadingTask._capability.reject(new _util.InvalidPDFException(exception.message));
+ }, this);
+ messageHandler.on('MissingPDF', function (exception) {
+ loadingTask._capability.reject(new _util.MissingPDFException(exception.message));
+ }, this);
+ messageHandler.on('UnexpectedResponse', function (exception) {
+ loadingTask._capability.reject(new _util.UnexpectedResponseException(exception.message, exception.status));
+ }, this);
+ messageHandler.on('UnknownError', function (exception) {
+ loadingTask._capability.reject(new _util.UnknownErrorException(exception.message, exception.details));
+ }, this);
+ messageHandler.on('DataLoaded', function (data) {
+ if (loadingTask.onProgress) {
+ loadingTask.onProgress({
+ loaded: data.length,
+ total: data.length
+ });
+ }
+
+ this.downloadInfoCapability.resolve(data);
+ }, this);
+ messageHandler.on('StartRenderPage', function (data) {
+ if (this.destroyed) {
+ return;
+ }
+
+ var page = this.pageCache[data.pageIndex];
+
+ page._stats.timeEnd('Page Request');
+
+ page._startRenderPage(data.transparency, data.intent);
+ }, this);
+ messageHandler.on('RenderPageChunk', function (data) {
+ if (this.destroyed) {
+ return;
+ }
+
+ var page = this.pageCache[data.pageIndex];
+
+ page._renderPageChunk(data.operatorList, data.intent);
+ }, this);
+ messageHandler.on('commonobj', function (data) {
+ var _this13 = this;
+
+ if (this.destroyed) {
+ return;
+ }
+
+ var _data = _slicedToArray(data, 3),
+ id = _data[0],
+ type = _data[1],
+ exportedData = _data[2];
+
+ if (this.commonObjs.has(id)) {
+ return;
+ }
+
+ switch (type) {
+ case 'Font':
+ var params = this._params;
+
+ if ('error' in exportedData) {
+ var exportedError = exportedData.error;
+ (0, _util.warn)("Error during font loading: ".concat(exportedError));
+ this.commonObjs.resolve(id, exportedError);
+ break;
+ }
+
+ var fontRegistry = null;
+
+ if (params.pdfBug && _global_scope["default"].FontInspector && _global_scope["default"].FontInspector.enabled) {
+ fontRegistry = {
+ registerFont: function registerFont(font, url) {
+ _global_scope["default"]['FontInspector'].fontAdded(font, url);
+ }
+ };
+ }
+
+ var font = new _font_loader.FontFaceObject(exportedData, {
+ isEvalSupported: params.isEvalSupported,
+ disableFontFace: params.disableFontFace,
+ ignoreErrors: params.ignoreErrors,
+ onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
+ fontRegistry: fontRegistry
+ });
+ this.fontLoader.bind(font).then(function () {
+ _this13.commonObjs.resolve(id, font);
+ }, function (reason) {
+ messageHandler.sendWithPromise('FontFallback', {
+ id: id
+ })["finally"](function () {
+ _this13.commonObjs.resolve(id, font);
+ });
+ });
+ break;
+
+ case 'FontPath':
+ case 'FontType3Res':
+ this.commonObjs.resolve(id, exportedData);
+ break;
+
+ default:
+ throw new Error("Got unknown common object type ".concat(type));
+ }
+ }, this);
+ messageHandler.on('obj', function (data) {
+ if (this.destroyed) {
+ return undefined;
+ }
+
+ var _data2 = _slicedToArray(data, 4),
+ id = _data2[0],
+ pageIndex = _data2[1],
+ type = _data2[2],
+ imageData = _data2[3];
+
+ var pageProxy = this.pageCache[pageIndex];
+
+ if (pageProxy.objs.has(id)) {
+ return undefined;
+ }
+
+ switch (type) {
+ case 'JpegStream':
+ return new Promise(function (resolve, reject) {
+ var img = new Image();
+
+ img.onload = function () {
+ resolve(img);
+ };
+
+ img.onerror = function () {
+ reject(new Error('Error during JPEG image loading'));
+ (0, _display_utils.releaseImageResources)(img);
+ };
+
+ img.src = imageData;
+ }).then(function (img) {
+ pageProxy.objs.resolve(id, img);
+ });
+
+ case 'Image':
+ pageProxy.objs.resolve(id, imageData);
+ var MAX_IMAGE_SIZE_TO_STORE = 8000000;
+
+ if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
+ pageProxy.cleanupAfterRender = true;
+ }
+
+ break;
+
+ default:
+ throw new Error("Got unknown object type ".concat(type));
+ }
+
+ return undefined;
+ }, this);
+ messageHandler.on('DocProgress', function (data) {
+ if (this.destroyed) {
+ return;
+ }
+
+ if (loadingTask.onProgress) {
+ loadingTask.onProgress({
+ loaded: data.loaded,
+ total: data.total
+ });
+ }
+ }, this);
+ messageHandler.on('PageError', function (data) {
+ if (this.destroyed) {
+ return;
+ }
+
+ var page = this.pageCache[data.pageIndex];
+ var intentState = page.intentStates[data.intent];
+
+ if (intentState.displayReadyCapability) {
+ intentState.displayReadyCapability.reject(new Error(data.error));
+ } else {
+ throw new Error(data.error);
+ }
+
+ if (intentState.operatorList) {
+ intentState.operatorList.lastChunk = true;
+
+ for (var i = 0; i < intentState.renderTasks.length; i++) {
+ intentState.renderTasks[i].operatorListChanged();
+ }
+ }
+ }, this);
+ messageHandler.on('UnsupportedFeature', this._onUnsupportedFeature, this);
+ messageHandler.on('JpegDecode', function (data) {
+ if (this.destroyed) {
+ return Promise.reject(new Error('Worker was destroyed'));
+ }
+
+ if (typeof document === 'undefined') {
+ return Promise.reject(new Error('"document" is not defined.'));
+ }
+
+ var _data3 = _slicedToArray(data, 2),
+ imageUrl = _data3[0],
+ components = _data3[1];
+
+ if (components !== 3 && components !== 1) {
+ return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
+ }
+
+ return new Promise(function (resolve, reject) {
+ var img = new Image();
+
+ img.onload = function () {
+ var width = img.width,
+ height = img.height;
+ var size = width * height;
+ var rgbaLength = size * 4;
+ var buf = new Uint8ClampedArray(size * components);
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = width;
+ tmpCanvas.height = height;
+ var tmpCtx = tmpCanvas.getContext('2d');
+ tmpCtx.drawImage(img, 0, 0);
+ var data = tmpCtx.getImageData(0, 0, width, height).data;
+
+ if (components === 3) {
+ for (var i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
+ buf[j] = data[i];
+ buf[j + 1] = data[i + 1];
+ buf[j + 2] = data[i + 2];
+ }
+ } else if (components === 1) {
+ for (var _i2 = 0, _j = 0; _i2 < rgbaLength; _i2 += 4, _j++) {
+ buf[_j] = data[_i2];
+ }
+ }
+
+ resolve({
+ data: buf,
+ width: width,
+ height: height
+ });
+ (0, _display_utils.releaseImageResources)(img);
+ tmpCanvas.width = 0;
+ tmpCanvas.height = 0;
+ tmpCanvas = null;
+ tmpCtx = null;
+ };
+
+ img.onerror = function () {
+ reject(new Error('JpegDecode failed to load image'));
+ (0, _display_utils.releaseImageResources)(img);
+ };
+
+ img.src = imageUrl;
+ });
+ }, this);
+ messageHandler.on('FetchBuiltInCMap', function (data) {
+ if (this.destroyed) {
+ return Promise.reject(new Error('Worker was destroyed'));
+ }
+
+ return this.CMapReaderFactory.fetch({
+ name: data.name
+ });
+ }, this);
+ }
+ }, {
+ key: "_onUnsupportedFeature",
+ value: function _onUnsupportedFeature(_ref10) {
+ var featureId = _ref10.featureId;
+
+ if (this.destroyed) {
+ return;
+ }
+
+ if (this.loadingTask.onUnsupportedFeature) {
+ this.loadingTask.onUnsupportedFeature(featureId);
+ }
+ }
+ }, {
+ key: "getData",
+ value: function getData() {
+ return this.messageHandler.sendWithPromise('GetData', null);
+ }
+ }, {
+ key: "getPage",
+ value: function getPage(pageNumber) {
+ var _this14 = this;
+
+ if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
+ return Promise.reject(new Error('Invalid page request'));
+ }
+
+ var pageIndex = pageNumber - 1;
+
+ if (pageIndex in this.pagePromises) {
+ return this.pagePromises[pageIndex];
+ }
+
+ var promise = this.messageHandler.sendWithPromise('GetPage', {
+ pageIndex: pageIndex
+ }).then(function (pageInfo) {
+ if (_this14.destroyed) {
+ throw new Error('Transport destroyed');
+ }
+
+ var page = new PDFPageProxy(pageIndex, pageInfo, _this14, _this14._params.pdfBug);
+ _this14.pageCache[pageIndex] = page;
+ return page;
+ });
+ this.pagePromises[pageIndex] = promise;
+ return promise;
+ }
+ }, {
+ key: "getPageIndex",
+ value: function getPageIndex(ref) {
+ return this.messageHandler.sendWithPromise('GetPageIndex', {
+ ref: ref
+ })["catch"](function (reason) {
+ return Promise.reject(new Error(reason));
+ });
+ }
+ }, {
+ key: "getAnnotations",
+ value: function getAnnotations(pageIndex, intent) {
+ return this.messageHandler.sendWithPromise('GetAnnotations', {
+ pageIndex: pageIndex,
+ intent: intent
+ });
+ }
+ }, {
+ key: "getDestinations",
+ value: function getDestinations() {
+ return this.messageHandler.sendWithPromise('GetDestinations', null);
+ }
+ }, {
+ key: "getDestination",
+ value: function getDestination(id) {
+ if (typeof id !== 'string') {
+ return Promise.reject(new Error('Invalid destination request.'));
+ }
+
+ return this.messageHandler.sendWithPromise('GetDestination', {
+ id: id
+ });
+ }
+ }, {
+ key: "getPageLabels",
+ value: function getPageLabels() {
+ return this.messageHandler.sendWithPromise('GetPageLabels', null);
+ }
+ }, {
+ key: "getPageLayout",
+ value: function getPageLayout() {
+ return this.messageHandler.sendWithPromise('GetPageLayout', null);
+ }
+ }, {
+ key: "getPageMode",
+ value: function getPageMode() {
+ return this.messageHandler.sendWithPromise('GetPageMode', null);
+ }
+ }, {
+ key: "getViewerPreferences",
+ value: function getViewerPreferences() {
+ return this.messageHandler.sendWithPromise('GetViewerPreferences', null);
+ }
+ }, {
+ key: "getOpenActionDestination",
+ value: function getOpenActionDestination() {
+ return this.messageHandler.sendWithPromise('GetOpenActionDestination', null);
+ }
+ }, {
+ key: "getAttachments",
+ value: function getAttachments() {
+ return this.messageHandler.sendWithPromise('GetAttachments', null);
+ }
+ }, {
+ key: "getJavaScript",
+ value: function getJavaScript() {
+ return this.messageHandler.sendWithPromise('GetJavaScript', null);
+ }
+ }, {
+ key: "getOutline",
+ value: function getOutline() {
+ return this.messageHandler.sendWithPromise('GetOutline', null);
+ }
+ }, {
+ key: "getPermissions",
+ value: function getPermissions() {
+ return this.messageHandler.sendWithPromise('GetPermissions', null);
+ }
+ }, {
+ key: "getMetadata",
+ value: function getMetadata() {
+ var _this15 = this;
+
+ return this.messageHandler.sendWithPromise('GetMetadata', null).then(function (results) {
+ return {
+ info: results[0],
+ metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
+ contentDispositionFilename: _this15._fullReader ? _this15._fullReader.filename : null
+ };
+ });
+ }
+ }, {
+ key: "getStats",
+ value: function getStats() {
+ return this.messageHandler.sendWithPromise('GetStats', null);
+ }
+ }, {
+ key: "startCleanup",
+ value: function startCleanup() {
+ var _this16 = this;
+
+ this.messageHandler.sendWithPromise('Cleanup', null).then(function () {
+ for (var i = 0, ii = _this16.pageCache.length; i < ii; i++) {
+ var page = _this16.pageCache[i];
+
+ if (page) {
+ page.cleanup();
+ }
+ }
+
+ _this16.commonObjs.clear();
+
+ _this16.fontLoader.clear();
+ });
+ }
+ }, {
+ key: "loadingParams",
+ get: function get() {
+ var params = this._params;
+ return (0, _util.shadow)(this, 'loadingParams', {
+ disableAutoFetch: params.disableAutoFetch,
+ disableCreateObjectURL: params.disableCreateObjectURL,
+ disableFontFace: params.disableFontFace,
+ nativeImageDecoderSupport: params.nativeImageDecoderSupport
+ });
+ }
+ }]);
+
+ return WorkerTransport;
+}();
+
+var PDFObjects =
+/*#__PURE__*/
+function () {
+ function PDFObjects() {
+ _classCallCheck(this, PDFObjects);
+
+ this._objs = Object.create(null);
+ }
+
+ _createClass(PDFObjects, [{
+ key: "_ensureObj",
+ value: function _ensureObj(objId) {
+ if (this._objs[objId]) {
+ return this._objs[objId];
+ }
+
+ return this._objs[objId] = {
+ capability: (0, _util.createPromiseCapability)(),
+ data: null,
+ resolved: false
+ };
+ }
+ }, {
+ key: "get",
+ value: function get(objId) {
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+
+ if (callback) {
+ this._ensureObj(objId).capability.promise.then(callback);
+
+ return null;
+ }
+
+ var obj = this._objs[objId];
+
+ if (!obj || !obj.resolved) {
+ throw new Error("Requesting object that isn't resolved yet ".concat(objId, "."));
+ }
+
+ return obj.data;
+ }
+ }, {
+ key: "has",
+ value: function has(objId) {
+ var obj = this._objs[objId];
+ return obj ? obj.resolved : false;
+ }
+ }, {
+ key: "resolve",
+ value: function resolve(objId, data) {
+ var obj = this._ensureObj(objId);
+
+ obj.resolved = true;
+ obj.data = data;
+ obj.capability.resolve(data);
+ }
+ }, {
+ key: "clear",
+ value: function clear() {
+ for (var objId in this._objs) {
+ var data = this._objs[objId].data;
+
+ if (typeof Image !== 'undefined' && data instanceof Image) {
+ (0, _display_utils.releaseImageResources)(data);
+ }
+ }
+
+ this._objs = Object.create(null);
+ }
+ }]);
+
+ return PDFObjects;
+}();
+
+var RenderTask =
+/*#__PURE__*/
+function () {
+ function RenderTask(internalRenderTask) {
+ _classCallCheck(this, RenderTask);
+
+ this._internalRenderTask = internalRenderTask;
+ this.onContinue = null;
+ }
+
+ _createClass(RenderTask, [{
+ key: "cancel",
+ value: function cancel() {
+ this._internalRenderTask.cancel();
+ }
+ }, {
+ key: "then",
+ value: function then(onFulfilled, onRejected) {
+ (0, _display_utils.deprecated)('RenderTask.then method, use the `promise` getter instead.');
+ return this.promise.then.apply(this.promise, arguments);
+ }
+ }, {
+ key: "promise",
+ get: function get() {
+ return this._internalRenderTask.capability.promise;
+ }
+ }]);
+
+ return RenderTask;
+}();
+
+var InternalRenderTask = function InternalRenderTaskClosure() {
+ var canvasInRendering = new WeakSet();
+
+ var InternalRenderTask =
+ /*#__PURE__*/
+ function () {
+ function InternalRenderTask(_ref11) {
+ var callback = _ref11.callback,
+ params = _ref11.params,
+ objs = _ref11.objs,
+ commonObjs = _ref11.commonObjs,
+ operatorList = _ref11.operatorList,
+ pageNumber = _ref11.pageNumber,
+ canvasFactory = _ref11.canvasFactory,
+ webGLContext = _ref11.webGLContext,
+ _ref11$useRequestAnim = _ref11.useRequestAnimationFrame,
+ useRequestAnimationFrame = _ref11$useRequestAnim === void 0 ? false : _ref11$useRequestAnim,
+ _ref11$pdfBug = _ref11.pdfBug,
+ pdfBug = _ref11$pdfBug === void 0 ? false : _ref11$pdfBug;
+
+ _classCallCheck(this, InternalRenderTask);
+
+ this.callback = callback;
+ this.params = params;
+ this.objs = objs;
+ this.commonObjs = commonObjs;
+ this.operatorListIdx = null;
+ this.operatorList = operatorList;
+ this.pageNumber = pageNumber;
+ this.canvasFactory = canvasFactory;
+ this.webGLContext = webGLContext;
+ this._pdfBug = pdfBug;
+ this.running = false;
+ this.graphicsReadyCallback = null;
+ this.graphicsReady = false;
+ this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== 'undefined';
+ this.cancelled = false;
+ this.capability = (0, _util.createPromiseCapability)();
+ this.task = new RenderTask(this);
+ this._continueBound = this._continue.bind(this);
+ this._scheduleNextBound = this._scheduleNext.bind(this);
+ this._nextBound = this._next.bind(this);
+ this._canvas = params.canvasContext.canvas;
+ }
+
+ _createClass(InternalRenderTask, [{
+ key: "initializeGraphics",
+ value: function initializeGraphics() {
+ var transparency = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
+
+ if (this.cancelled) {
+ return;
+ }
+
+ if (this._canvas) {
+ if (canvasInRendering.has(this._canvas)) {
+ throw new Error('Cannot use the same canvas during multiple render() operations. ' + 'Use different canvas or ensure previous operations were ' + 'cancelled or completed.');
+ }
+
+ canvasInRendering.add(this._canvas);
+ }
+
+ if (this._pdfBug && _global_scope["default"].StepperManager && _global_scope["default"].StepperManager.enabled) {
+ this.stepper = _global_scope["default"].StepperManager.create(this.pageNumber - 1);
+ this.stepper.init(this.operatorList);
+ this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
+ }
+
+ var _this$params = this.params,
+ canvasContext = _this$params.canvasContext,
+ viewport = _this$params.viewport,
+ transform = _this$params.transform,
+ imageLayer = _this$params.imageLayer,
+ background = _this$params.background;
+ this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.webGLContext, imageLayer);
+ this.gfx.beginDrawing({
+ transform: transform,
+ viewport: viewport,
+ transparency: transparency,
+ background: background
+ });
+ this.operatorListIdx = 0;
+ this.graphicsReady = true;
+
+ if (this.graphicsReadyCallback) {
+ this.graphicsReadyCallback();
+ }
+ }
+ }, {
+ key: "cancel",
+ value: function cancel() {
+ var error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ this.running = false;
+ this.cancelled = true;
+
+ if (this.gfx) {
+ this.gfx.endDrawing();
+ }
+
+ if (this._canvas) {
+ canvasInRendering["delete"](this._canvas);
+ }
+
+ this.callback(error || new _display_utils.RenderingCancelledException("Rendering cancelled, page ".concat(this.pageNumber), 'canvas'));
+ }
+ }, {
+ key: "operatorListChanged",
+ value: function operatorListChanged() {
+ if (!this.graphicsReady) {
+ if (!this.graphicsReadyCallback) {
+ this.graphicsReadyCallback = this._continueBound;
+ }
+
+ return;
+ }
+
+ if (this.stepper) {
+ this.stepper.updateOperatorList(this.operatorList);
+ }
+
+ if (this.running) {
+ return;
+ }
+
+ this._continue();
+ }
+ }, {
+ key: "_continue",
+ value: function _continue() {
+ this.running = true;
+
+ if (this.cancelled) {
+ return;
+ }
+
+ if (this.task.onContinue) {
+ this.task.onContinue(this._scheduleNextBound);
+ } else {
+ this._scheduleNext();
+ }
+ }
+ }, {
+ key: "_scheduleNext",
+ value: function _scheduleNext() {
+ var _this17 = this;
+
+ if (this._useRequestAnimationFrame) {
+ window.requestAnimationFrame(function () {
+ _this17._nextBound()["catch"](_this17.cancel.bind(_this17));
+ });
+ } else {
+ Promise.resolve().then(this._nextBound)["catch"](this.cancel.bind(this));
+ }
+ }
+ }, {
+ key: "_next",
+ value: function () {
+ var _next2 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee() {
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (!this.cancelled) {
+ _context.next = 2;
+ break;
+ }
+
+ return _context.abrupt("return");
+
+ case 2:
+ this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
+
+ if (this.operatorListIdx === this.operatorList.argsArray.length) {
+ this.running = false;
+
+ if (this.operatorList.lastChunk) {
+ this.gfx.endDrawing();
+
+ if (this._canvas) {
+ canvasInRendering["delete"](this._canvas);
+ }
+
+ this.callback();
+ }
+ }
+
+ case 4:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee, this);
+ }));
+
+ function _next() {
+ return _next2.apply(this, arguments);
+ }
+
+ return _next;
+ }()
+ }]);
+
+ return InternalRenderTask;
+ }();
+
+ return InternalRenderTask;
+}();
+
+var version = '2.2.230';
+exports.version = version;
+var build = '6d118ec35';
+exports.build = build;
+
+/***/ }),
+/* 148 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = __w_pdfjs_require__(149);
+
+/***/ }),
+/* 149 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+/* WEBPACK VAR INJECTION */(function(module) {
+
+function _typeof(obj) { 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); }
+
+var runtime = function (exports) {
+ "use strict";
+
+ var Op = Object.prototype;
+ var hasOwn = Op.hasOwnProperty;
+ var undefined;
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
+
+ function wrap(innerFn, outerFn, self, tryLocsList) {
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
+ var generator = Object.create(protoGenerator.prototype);
+ var context = new Context(tryLocsList || []);
+ generator._invoke = makeInvokeMethod(innerFn, self, context);
+ return generator;
+ }
+
+ exports.wrap = wrap;
+
+ function tryCatch(fn, obj, arg) {
+ try {
+ return {
+ type: "normal",
+ arg: fn.call(obj, arg)
+ };
+ } catch (err) {
+ return {
+ type: "throw",
+ arg: err
+ };
+ }
+ }
+
+ var GenStateSuspendedStart = "suspendedStart";
+ var GenStateSuspendedYield = "suspendedYield";
+ var GenStateExecuting = "executing";
+ var GenStateCompleted = "completed";
+ var ContinueSentinel = {};
+
+ function Generator() {}
+
+ function GeneratorFunction() {}
+
+ function GeneratorFunctionPrototype() {}
+
+ var IteratorPrototype = {};
+
+ IteratorPrototype[iteratorSymbol] = function () {
+ return this;
+ };
+
+ var getProto = Object.getPrototypeOf;
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
+
+ if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
+ IteratorPrototype = NativeIteratorPrototype;
+ }
+
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
+ GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
+ GeneratorFunctionPrototype.constructor = GeneratorFunction;
+ GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction";
+
+ function defineIteratorMethods(prototype) {
+ ["next", "throw", "return"].forEach(function (method) {
+ prototype[method] = function (arg) {
+ return this._invoke(method, arg);
+ };
+ });
+ }
+
+ exports.isGeneratorFunction = function (genFun) {
+ var ctor = typeof genFun === "function" && genFun.constructor;
+ return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
+ };
+
+ exports.mark = function (genFun) {
+ if (Object.setPrototypeOf) {
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
+ } else {
+ genFun.__proto__ = GeneratorFunctionPrototype;
+
+ if (!(toStringTagSymbol in genFun)) {
+ genFun[toStringTagSymbol] = "GeneratorFunction";
+ }
+ }
+
+ genFun.prototype = Object.create(Gp);
+ return genFun;
+ };
+
+ exports.awrap = function (arg) {
+ return {
+ __await: arg
+ };
+ };
+
+ function AsyncIterator(generator) {
+ function invoke(method, arg, resolve, reject) {
+ var record = tryCatch(generator[method], generator, arg);
+
+ if (record.type === "throw") {
+ reject(record.arg);
+ } else {
+ var result = record.arg;
+ var value = result.value;
+
+ if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) {
+ return Promise.resolve(value.__await).then(function (value) {
+ invoke("next", value, resolve, reject);
+ }, function (err) {
+ invoke("throw", err, resolve, reject);
+ });
+ }
+
+ return Promise.resolve(value).then(function (unwrapped) {
+ result.value = unwrapped;
+ resolve(result);
+ }, function (error) {
+ return invoke("throw", error, resolve, reject);
+ });
+ }
+ }
+
+ var previousPromise;
+
+ function enqueue(method, arg) {
+ function callInvokeWithMethodAndArg() {
+ return new Promise(function (resolve, reject) {
+ invoke(method, arg, resolve, reject);
+ });
+ }
+
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
+ }
+
+ this._invoke = enqueue;
+ }
+
+ defineIteratorMethods(AsyncIterator.prototype);
+
+ AsyncIterator.prototype[asyncIteratorSymbol] = function () {
+ return this;
+ };
+
+ exports.AsyncIterator = AsyncIterator;
+
+ exports.async = function (innerFn, outerFn, self, tryLocsList) {
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList));
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
+ return result.done ? result.value : iter.next();
+ });
+ };
+
+ function makeInvokeMethod(innerFn, self, context) {
+ var state = GenStateSuspendedStart;
+ return function invoke(method, arg) {
+ if (state === GenStateExecuting) {
+ throw new Error("Generator is already running");
+ }
+
+ if (state === GenStateCompleted) {
+ if (method === "throw") {
+ throw arg;
+ }
+
+ return doneResult();
+ }
+
+ context.method = method;
+ context.arg = arg;
+
+ while (true) {
+ var delegate = context.delegate;
+
+ if (delegate) {
+ var delegateResult = maybeInvokeDelegate(delegate, context);
+
+ if (delegateResult) {
+ if (delegateResult === ContinueSentinel) continue;
+ return delegateResult;
+ }
+ }
+
+ if (context.method === "next") {
+ context.sent = context._sent = context.arg;
+ } else if (context.method === "throw") {
+ if (state === GenStateSuspendedStart) {
+ state = GenStateCompleted;
+ throw context.arg;
+ }
+
+ context.dispatchException(context.arg);
+ } else if (context.method === "return") {
+ context.abrupt("return", context.arg);
+ }
+
+ state = GenStateExecuting;
+ var record = tryCatch(innerFn, self, context);
+
+ if (record.type === "normal") {
+ state = context.done ? GenStateCompleted : GenStateSuspendedYield;
+
+ if (record.arg === ContinueSentinel) {
+ continue;
+ }
+
+ return {
+ value: record.arg,
+ done: context.done
+ };
+ } else if (record.type === "throw") {
+ state = GenStateCompleted;
+ context.method = "throw";
+ context.arg = record.arg;
+ }
+ }
+ };
+ }
+
+ function maybeInvokeDelegate(delegate, context) {
+ var method = delegate.iterator[context.method];
+
+ if (method === undefined) {
+ context.delegate = null;
+
+ if (context.method === "throw") {
+ if (delegate.iterator["return"]) {
+ context.method = "return";
+ context.arg = undefined;
+ maybeInvokeDelegate(delegate, context);
+
+ if (context.method === "throw") {
+ return ContinueSentinel;
+ }
+ }
+
+ context.method = "throw";
+ context.arg = new TypeError("The iterator does not provide a 'throw' method");
+ }
+
+ return ContinueSentinel;
+ }
+
+ var record = tryCatch(method, delegate.iterator, context.arg);
+
+ if (record.type === "throw") {
+ context.method = "throw";
+ context.arg = record.arg;
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ var info = record.arg;
+
+ if (!info) {
+ context.method = "throw";
+ context.arg = new TypeError("iterator result is not an object");
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ if (info.done) {
+ context[delegate.resultName] = info.value;
+ context.next = delegate.nextLoc;
+
+ if (context.method !== "return") {
+ context.method = "next";
+ context.arg = undefined;
+ }
+ } else {
+ return info;
+ }
+
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ defineIteratorMethods(Gp);
+ Gp[toStringTagSymbol] = "Generator";
+
+ Gp[iteratorSymbol] = function () {
+ return this;
+ };
+
+ Gp.toString = function () {
+ return "[object Generator]";
+ };
+
+ function pushTryEntry(locs) {
+ var entry = {
+ tryLoc: locs[0]
+ };
+
+ if (1 in locs) {
+ entry.catchLoc = locs[1];
+ }
+
+ if (2 in locs) {
+ entry.finallyLoc = locs[2];
+ entry.afterLoc = locs[3];
+ }
+
+ this.tryEntries.push(entry);
+ }
+
+ function resetTryEntry(entry) {
+ var record = entry.completion || {};
+ record.type = "normal";
+ delete record.arg;
+ entry.completion = record;
+ }
+
+ function Context(tryLocsList) {
+ this.tryEntries = [{
+ tryLoc: "root"
+ }];
+ tryLocsList.forEach(pushTryEntry, this);
+ this.reset(true);
+ }
+
+ exports.keys = function (object) {
+ var keys = [];
+
+ for (var key in object) {
+ keys.push(key);
+ }
+
+ keys.reverse();
+ return function next() {
+ while (keys.length) {
+ var key = keys.pop();
+
+ if (key in object) {
+ next.value = key;
+ next.done = false;
+ return next;
+ }
+ }
+
+ next.done = true;
+ return next;
+ };
+ };
+
+ function values(iterable) {
+ if (iterable) {
+ var iteratorMethod = iterable[iteratorSymbol];
+
+ if (iteratorMethod) {
+ return iteratorMethod.call(iterable);
+ }
+
+ if (typeof iterable.next === "function") {
+ return iterable;
+ }
+
+ if (!isNaN(iterable.length)) {
+ var i = -1,
+ next = function next() {
+ while (++i < iterable.length) {
+ if (hasOwn.call(iterable, i)) {
+ next.value = iterable[i];
+ next.done = false;
+ return next;
+ }
+ }
+
+ next.value = undefined;
+ next.done = true;
+ return next;
+ };
+
+ return next.next = next;
+ }
+ }
+
+ return {
+ next: doneResult
+ };
+ }
+
+ exports.values = values;
+
+ function doneResult() {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
+
+ Context.prototype = {
+ constructor: Context,
+ reset: function reset(skipTempReset) {
+ this.prev = 0;
+ this.next = 0;
+ this.sent = this._sent = undefined;
+ this.done = false;
+ this.delegate = null;
+ this.method = "next";
+ this.arg = undefined;
+ this.tryEntries.forEach(resetTryEntry);
+
+ if (!skipTempReset) {
+ for (var name in this) {
+ if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
+ this[name] = undefined;
+ }
+ }
+ }
+ },
+ stop: function stop() {
+ this.done = true;
+ var rootEntry = this.tryEntries[0];
+ var rootRecord = rootEntry.completion;
+
+ if (rootRecord.type === "throw") {
+ throw rootRecord.arg;
+ }
+
+ return this.rval;
+ },
+ dispatchException: function dispatchException(exception) {
+ if (this.done) {
+ throw exception;
+ }
+
+ var context = this;
+
+ function handle(loc, caught) {
+ record.type = "throw";
+ record.arg = exception;
+ context.next = loc;
+
+ if (caught) {
+ context.method = "next";
+ context.arg = undefined;
+ }
+
+ return !!caught;
+ }
+
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ var record = entry.completion;
+
+ if (entry.tryLoc === "root") {
+ return handle("end");
+ }
+
+ if (entry.tryLoc <= this.prev) {
+ var hasCatch = hasOwn.call(entry, "catchLoc");
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
+
+ if (hasCatch && hasFinally) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ } else if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+ } else if (hasCatch) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ }
+ } else if (hasFinally) {
+ if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+ } else {
+ throw new Error("try statement without catch or finally");
+ }
+ }
+ }
+ },
+ abrupt: function abrupt(type, arg) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
+ var finallyEntry = entry;
+ break;
+ }
+ }
+
+ if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
+ finallyEntry = null;
+ }
+
+ var record = finallyEntry ? finallyEntry.completion : {};
+ record.type = type;
+ record.arg = arg;
+
+ if (finallyEntry) {
+ this.method = "next";
+ this.next = finallyEntry.finallyLoc;
+ return ContinueSentinel;
+ }
+
+ return this.complete(record);
+ },
+ complete: function complete(record, afterLoc) {
+ if (record.type === "throw") {
+ throw record.arg;
+ }
+
+ if (record.type === "break" || record.type === "continue") {
+ this.next = record.arg;
+ } else if (record.type === "return") {
+ this.rval = this.arg = record.arg;
+ this.method = "return";
+ this.next = "end";
+ } else if (record.type === "normal" && afterLoc) {
+ this.next = afterLoc;
+ }
+
+ return ContinueSentinel;
+ },
+ finish: function finish(finallyLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.finallyLoc === finallyLoc) {
+ this.complete(entry.completion, entry.afterLoc);
+ resetTryEntry(entry);
+ return ContinueSentinel;
+ }
+ }
+ },
+ "catch": function _catch(tryLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.tryLoc === tryLoc) {
+ var record = entry.completion;
+
+ if (record.type === "throw") {
+ var thrown = record.arg;
+ resetTryEntry(entry);
+ }
+
+ return thrown;
+ }
+ }
+
+ throw new Error("illegal catch attempt");
+ },
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
+ this.delegate = {
+ iterator: values(iterable),
+ resultName: resultName,
+ nextLoc: nextLoc
+ };
+
+ if (this.method === "next") {
+ this.arg = undefined;
+ }
+
+ return ContinueSentinel;
+ }
+ };
+ return exports;
+}(( false ? undefined : _typeof(module)) === "object" ? module.exports : {});
+
+try {
+ regeneratorRuntime = runtime;
+} catch (accidentalStrictMode) {
+ Function("r", "regeneratorRuntime = r")(runtime);
+}
+/* WEBPACK VAR INJECTION */}.call(this, __w_pdfjs_require__(150)(module)))
+
+/***/ }),
+/* 150 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+module.exports = function (module) {
+ if (!module.webpackPolyfill) {
+ module.deprecate = function () {};
+
+ module.paths = [];
+ if (!module.children) module.children = [];
+ Object.defineProperty(module, "loaded", {
+ enumerable: true,
+ get: function get() {
+ return module.l;
+ }
+ });
+ Object.defineProperty(module, "id", {
+ enumerable: true,
+ get: function get() {
+ return module.i;
+ }
+ });
+ module.webpackPolyfill = 1;
+ }
+
+ return module;
+};
+
+/***/ }),
+/* 151 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.addLinkAttributes = addLinkAttributes;
+exports.getFilenameFromUrl = getFilenameFromUrl;
+exports.isFetchSupported = isFetchSupported;
+exports.isValidFetchUrl = isValidFetchUrl;
+exports.loadScript = loadScript;
+exports.deprecated = deprecated;
+exports.releaseImageResources = releaseImageResources;
+exports.PDFDateString = exports.DummyStatTimer = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
+exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
+var SVG_NS = 'http://www.w3.org/2000/svg';
+
+var DOMCanvasFactory =
+/*#__PURE__*/
+function () {
+ function DOMCanvasFactory() {
+ _classCallCheck(this, DOMCanvasFactory);
+ }
+
+ _createClass(DOMCanvasFactory, [{
+ key: "create",
+ value: function create(width, height) {
+ if (width <= 0 || height <= 0) {
+ throw new Error('Invalid canvas size');
+ }
+
+ var canvas = document.createElement('canvas');
+ var context = canvas.getContext('2d');
+ canvas.width = width;
+ canvas.height = height;
+ return {
+ canvas: canvas,
+ context: context
+ };
+ }
+ }, {
+ key: "reset",
+ value: function reset(canvasAndContext, width, height) {
+ if (!canvasAndContext.canvas) {
+ throw new Error('Canvas is not specified');
+ }
+
+ if (width <= 0 || height <= 0) {
+ throw new Error('Invalid canvas size');
+ }
+
+ canvasAndContext.canvas.width = width;
+ canvasAndContext.canvas.height = height;
+ }
+ }, {
+ key: "destroy",
+ value: function destroy(canvasAndContext) {
+ if (!canvasAndContext.canvas) {
+ throw new Error('Canvas is not specified');
+ }
+
+ canvasAndContext.canvas.width = 0;
+ canvasAndContext.canvas.height = 0;
+ canvasAndContext.canvas = null;
+ canvasAndContext.context = null;
+ }
+ }]);
+
+ return DOMCanvasFactory;
+}();
+
+exports.DOMCanvasFactory = DOMCanvasFactory;
+
+var DOMCMapReaderFactory =
+/*#__PURE__*/
+function () {
+ function DOMCMapReaderFactory(_ref) {
+ var _ref$baseUrl = _ref.baseUrl,
+ baseUrl = _ref$baseUrl === void 0 ? null : _ref$baseUrl,
+ _ref$isCompressed = _ref.isCompressed,
+ isCompressed = _ref$isCompressed === void 0 ? false : _ref$isCompressed;
+
+ _classCallCheck(this, DOMCMapReaderFactory);
+
+ this.baseUrl = baseUrl;
+ this.isCompressed = isCompressed;
+ }
+
+ _createClass(DOMCMapReaderFactory, [{
+ key: "fetch",
+ value: function (_fetch) {
+ function fetch(_x) {
+ return _fetch.apply(this, arguments);
+ }
+
+ fetch.toString = function () {
+ return _fetch.toString();
+ };
+
+ return fetch;
+ }(
+ /*#__PURE__*/
+ function () {
+ var _ref3 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee2(_ref2) {
+ var _this = this;
+
+ var name, url, compressionType;
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
+ while (1) {
+ switch (_context2.prev = _context2.next) {
+ case 0:
+ name = _ref2.name;
+
+ if (this.baseUrl) {
+ _context2.next = 3;
+ break;
+ }
+
+ throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
+
+ case 3:
+ if (name) {
+ _context2.next = 5;
+ break;
+ }
+
+ throw new Error('CMap name must be specified.');
+
+ case 5:
+ url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');
+ compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
+
+ if (!(isFetchSupported() && isValidFetchUrl(url, document.baseURI))) {
+ _context2.next = 9;
+ break;
+ }
+
+ return _context2.abrupt("return", fetch(url).then(
+ /*#__PURE__*/
+ function () {
+ var _ref4 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee(response) {
+ var cMapData;
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (response.ok) {
+ _context.next = 2;
+ break;
+ }
+
+ throw new Error(response.statusText);
+
+ case 2:
+ if (!_this.isCompressed) {
+ _context.next = 10;
+ break;
+ }
+
+ _context.t0 = Uint8Array;
+ _context.next = 6;
+ return response.arrayBuffer();
+
+ case 6:
+ _context.t1 = _context.sent;
+ cMapData = new _context.t0(_context.t1);
+ _context.next = 15;
+ break;
+
+ case 10:
+ _context.t2 = _util.stringToBytes;
+ _context.next = 13;
+ return response.text();
+
+ case 13:
+ _context.t3 = _context.sent;
+ cMapData = (0, _context.t2)(_context.t3);
+
+ case 15:
+ return _context.abrupt("return", {
+ cMapData: cMapData,
+ compressionType: compressionType
+ });
+
+ case 16:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ return function (_x3) {
+ return _ref4.apply(this, arguments);
+ };
+ }())["catch"](function (reason) {
+ throw new Error("Unable to load ".concat(_this.isCompressed ? 'binary ' : '') + "CMap at: ".concat(url));
+ }));
+
+ case 9:
+ return _context2.abrupt("return", new Promise(function (resolve, reject) {
+ var request = new XMLHttpRequest();
+ request.open('GET', url, true);
+
+ if (_this.isCompressed) {
+ request.responseType = 'arraybuffer';
+ }
+
+ request.onreadystatechange = function () {
+ if (request.readyState !== XMLHttpRequest.DONE) {
+ return;
+ }
+
+ if (request.status === 200 || request.status === 0) {
+ var cMapData;
+
+ if (_this.isCompressed && request.response) {
+ cMapData = new Uint8Array(request.response);
+ } else if (!_this.isCompressed && request.responseText) {
+ cMapData = (0, _util.stringToBytes)(request.responseText);
+ }
+
+ if (cMapData) {
+ resolve({
+ cMapData: cMapData,
+ compressionType: compressionType
+ });
+ return;
+ }
+ }
+
+ reject(new Error(request.statusText));
+ };
+
+ request.send(null);
+ })["catch"](function (reason) {
+ throw new Error("Unable to load ".concat(_this.isCompressed ? 'binary ' : '') + "CMap at: ".concat(url));
+ }));
+
+ case 10:
+ case "end":
+ return _context2.stop();
+ }
+ }
+ }, _callee2, this);
+ }));
+
+ return function (_x2) {
+ return _ref3.apply(this, arguments);
+ };
+ }())
+ }]);
+
+ return DOMCMapReaderFactory;
+}();
+
+exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
+
+var DOMSVGFactory =
+/*#__PURE__*/
+function () {
+ function DOMSVGFactory() {
+ _classCallCheck(this, DOMSVGFactory);
+ }
+
+ _createClass(DOMSVGFactory, [{
+ key: "create",
+ value: function create(width, height) {
+ (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions');
+ var svg = document.createElementNS(SVG_NS, 'svg:svg');
+ svg.setAttribute('version', '1.1');
+ svg.setAttribute('width', width + 'px');
+ svg.setAttribute('height', height + 'px');
+ svg.setAttribute('preserveAspectRatio', 'none');
+ svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
+ return svg;
+ }
+ }, {
+ key: "createElement",
+ value: function createElement(type) {
+ (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type');
+ return document.createElementNS(SVG_NS, type);
+ }
+ }]);
+
+ return DOMSVGFactory;
+}();
+
+exports.DOMSVGFactory = DOMSVGFactory;
+
+var PageViewport =
+/*#__PURE__*/
+function () {
+ function PageViewport(_ref5) {
+ var viewBox = _ref5.viewBox,
+ scale = _ref5.scale,
+ rotation = _ref5.rotation,
+ _ref5$offsetX = _ref5.offsetX,
+ offsetX = _ref5$offsetX === void 0 ? 0 : _ref5$offsetX,
+ _ref5$offsetY = _ref5.offsetY,
+ offsetY = _ref5$offsetY === void 0 ? 0 : _ref5$offsetY,
+ _ref5$dontFlip = _ref5.dontFlip,
+ dontFlip = _ref5$dontFlip === void 0 ? false : _ref5$dontFlip;
+
+ _classCallCheck(this, PageViewport);
+
+ this.viewBox = viewBox;
+ this.scale = scale;
+ this.rotation = rotation;
+ this.offsetX = offsetX;
+ this.offsetY = offsetY;
+ var centerX = (viewBox[2] + viewBox[0]) / 2;
+ var centerY = (viewBox[3] + viewBox[1]) / 2;
+ var rotateA, rotateB, rotateC, rotateD;
+ rotation = rotation % 360;
+ rotation = rotation < 0 ? rotation + 360 : rotation;
+
+ switch (rotation) {
+ case 180:
+ rotateA = -1;
+ rotateB = 0;
+ rotateC = 0;
+ rotateD = 1;
+ break;
+
+ case 90:
+ rotateA = 0;
+ rotateB = 1;
+ rotateC = 1;
+ rotateD = 0;
+ break;
+
+ case 270:
+ rotateA = 0;
+ rotateB = -1;
+ rotateC = -1;
+ rotateD = 0;
+ break;
+
+ default:
+ rotateA = 1;
+ rotateB = 0;
+ rotateC = 0;
+ rotateD = -1;
+ break;
+ }
+
+ if (dontFlip) {
+ rotateC = -rotateC;
+ rotateD = -rotateD;
+ }
+
+ var offsetCanvasX, offsetCanvasY;
+ var width, height;
+
+ if (rotateA === 0) {
+ offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
+ width = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ height = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ } else {
+ offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
+ width = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ height = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ }
+
+ this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
+ this.width = width;
+ this.height = height;
+ }
+
+ _createClass(PageViewport, [{
+ key: "clone",
+ value: function clone() {
+ var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ _ref6$scale = _ref6.scale,
+ scale = _ref6$scale === void 0 ? this.scale : _ref6$scale,
+ _ref6$rotation = _ref6.rotation,
+ rotation = _ref6$rotation === void 0 ? this.rotation : _ref6$rotation,
+ _ref6$dontFlip = _ref6.dontFlip,
+ dontFlip = _ref6$dontFlip === void 0 ? false : _ref6$dontFlip;
+
+ return new PageViewport({
+ viewBox: this.viewBox.slice(),
+ scale: scale,
+ rotation: rotation,
+ offsetX: this.offsetX,
+ offsetY: this.offsetY,
+ dontFlip: dontFlip
+ });
+ }
+ }, {
+ key: "convertToViewportPoint",
+ value: function convertToViewportPoint(x, y) {
+ return _util.Util.applyTransform([x, y], this.transform);
+ }
+ }, {
+ key: "convertToViewportRectangle",
+ value: function convertToViewportRectangle(rect) {
+ var topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
+
+ var bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
+
+ return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
+ }
+ }, {
+ key: "convertToPdfPoint",
+ value: function convertToPdfPoint(x, y) {
+ return _util.Util.applyInverseTransform([x, y], this.transform);
+ }
+ }]);
+
+ return PageViewport;
+}();
+
+exports.PageViewport = PageViewport;
+
+var RenderingCancelledException = function RenderingCancelledException() {
+ function RenderingCancelledException(msg, type) {
+ this.message = msg;
+ this.type = type;
+ }
+
+ RenderingCancelledException.prototype = new Error();
+ RenderingCancelledException.prototype.name = 'RenderingCancelledException';
+ RenderingCancelledException.constructor = RenderingCancelledException;
+ return RenderingCancelledException;
+}();
+
+exports.RenderingCancelledException = RenderingCancelledException;
+var LinkTarget = {
+ NONE: 0,
+ SELF: 1,
+ BLANK: 2,
+ PARENT: 3,
+ TOP: 4
+};
+exports.LinkTarget = LinkTarget;
+var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
+
+function addLinkAttributes(link) {
+ var _ref7 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ url = _ref7.url,
+ target = _ref7.target,
+ rel = _ref7.rel;
+
+ link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : '';
+
+ if (url) {
+ var LinkTargetValues = Object.values(LinkTarget);
+ var targetIndex = LinkTargetValues.includes(target) ? target : LinkTarget.NONE;
+ link.target = LinkTargetStringMap[targetIndex];
+ link.rel = typeof rel === 'string' ? rel : DEFAULT_LINK_REL;
+ }
+}
+
+function getFilenameFromUrl(url) {
+ var anchor = url.indexOf('#');
+ var query = url.indexOf('?');
+ var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
+ return url.substring(url.lastIndexOf('/', end) + 1, end);
+}
+
+var StatTimer =
+/*#__PURE__*/
+function () {
+ function StatTimer() {
+ var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+
+ _classCallCheck(this, StatTimer);
+
+ this.enabled = !!enable;
+ this.started = Object.create(null);
+ this.times = [];
+ }
+
+ _createClass(StatTimer, [{
+ key: "time",
+ value: function time(name) {
+ if (!this.enabled) {
+ return;
+ }
+
+ if (name in this.started) {
+ (0, _util.warn)('Timer is already running for ' + name);
+ }
+
+ this.started[name] = Date.now();
+ }
+ }, {
+ key: "timeEnd",
+ value: function timeEnd(name) {
+ if (!this.enabled) {
+ return;
+ }
+
+ if (!(name in this.started)) {
+ (0, _util.warn)('Timer has not been started for ' + name);
+ }
+
+ this.times.push({
+ 'name': name,
+ 'start': this.started[name],
+ 'end': Date.now()
+ });
+ delete this.started[name];
+ }
+ }, {
+ key: "toString",
+ value: function toString() {
+ var out = '',
+ longest = 0;
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = this.times[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var time = _step.value;
+ var name = time.name;
+
+ if (name.length > longest) {
+ longest = name.length;
+ }
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+ _iterator["return"]();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ for (var _iterator2 = this.times[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var _time = _step2.value;
+ var duration = _time.end - _time.start;
+ out += "".concat(_time.name.padEnd(longest), " ").concat(duration, "ms\n");
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+ _iterator2["return"]();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ return out;
+ }
+ }]);
+
+ return StatTimer;
+}();
+
+exports.StatTimer = StatTimer;
+
+var DummyStatTimer =
+/*#__PURE__*/
+function () {
+ function DummyStatTimer() {
+ _classCallCheck(this, DummyStatTimer);
+
+ (0, _util.unreachable)('Cannot initialize DummyStatTimer.');
+ }
+
+ _createClass(DummyStatTimer, null, [{
+ key: "time",
+ value: function time(name) {}
+ }, {
+ key: "timeEnd",
+ value: function timeEnd(name) {}
+ }, {
+ key: "toString",
+ value: function toString() {
+ return '';
+ }
+ }]);
+
+ return DummyStatTimer;
+}();
+
+exports.DummyStatTimer = DummyStatTimer;
+
+function isFetchSupported() {
+ return typeof fetch !== 'undefined' && typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream !== 'undefined';
+}
+
+function isValidFetchUrl(url, baseUrl) {
+ try {
+ var _ref8 = baseUrl ? new _util.URL(url, baseUrl) : new _util.URL(url),
+ protocol = _ref8.protocol;
+
+ return protocol === 'http:' || protocol === 'https:';
+ } catch (ex) {
+ return false;
+ }
+}
+
+function loadScript(src) {
+ return new Promise(function (resolve, reject) {
+ var script = document.createElement('script');
+ script.src = src;
+ script.onload = resolve;
+
+ script.onerror = function () {
+ reject(new Error("Cannot load script at: ".concat(script.src)));
+ };
+
+ (document.head || document.documentElement).appendChild(script);
+ });
+}
+
+function deprecated(details) {
+ console.log('Deprecated API usage: ' + details);
+}
+
+function releaseImageResources(img) {
+ (0, _util.assert)(img instanceof Image, 'Invalid `img` parameter.');
+ var url = img.src;
+
+ if (typeof url === 'string' && url.startsWith('blob:') && _util.URL.revokeObjectURL) {
+ _util.URL.revokeObjectURL(url);
+ }
+
+ img.removeAttribute('src');
+}
+
+var pdfDateStringRegex;
+
+var PDFDateString =
+/*#__PURE__*/
+function () {
+ function PDFDateString() {
+ _classCallCheck(this, PDFDateString);
+ }
+
+ _createClass(PDFDateString, null, [{
+ key: "toDateObject",
+ value: function toDateObject(input) {
+ if (!input || !(0, _util.isString)(input)) {
+ return null;
+ }
+
+ if (!pdfDateStringRegex) {
+ pdfDateStringRegex = new RegExp('^D:' + '(\\d{4})' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '([Z|+|-])?' + '(\\d{2})?' + '\'?' + '(\\d{2})?' + '\'?');
+ }
+
+ var matches = pdfDateStringRegex.exec(input);
+
+ if (!matches) {
+ return null;
+ }
+
+ var year = parseInt(matches[1], 10);
+ var month = parseInt(matches[2], 10);
+ month = month >= 1 && month <= 12 ? month - 1 : 0;
+ var day = parseInt(matches[3], 10);
+ day = day >= 1 && day <= 31 ? day : 1;
+ var hour = parseInt(matches[4], 10);
+ hour = hour >= 0 && hour <= 23 ? hour : 0;
+ var minute = parseInt(matches[5], 10);
+ minute = minute >= 0 && minute <= 59 ? minute : 0;
+ var second = parseInt(matches[6], 10);
+ second = second >= 0 && second <= 59 ? second : 0;
+ var universalTimeRelation = matches[7] || 'Z';
+ var offsetHour = parseInt(matches[8], 10);
+ offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
+ var offsetMinute = parseInt(matches[9], 10) || 0;
+ offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
+
+ if (universalTimeRelation === '-') {
+ hour += offsetHour;
+ minute += offsetMinute;
+ } else if (universalTimeRelation === '+') {
+ hour -= offsetHour;
+ minute -= offsetMinute;
+ }
+
+ return new Date(Date.UTC(year, month, day, hour, minute, second));
+ }
+ }]);
+
+ return PDFDateString;
+}();
+
+exports.PDFDateString = PDFDateString;
+
+/***/ }),
+/* 152 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.FontLoader = exports.FontFaceObject = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
+
+function _typeof(obj) { 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); }
+
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
+
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
+
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var BaseFontLoader =
+/*#__PURE__*/
+function () {
+ function BaseFontLoader(_ref) {
+ var docId = _ref.docId,
+ onUnsupportedFeature = _ref.onUnsupportedFeature;
+
+ _classCallCheck(this, BaseFontLoader);
+
+ if (this.constructor === BaseFontLoader) {
+ (0, _util.unreachable)('Cannot initialize BaseFontLoader.');
+ }
+
+ this.docId = docId;
+ this._onUnsupportedFeature = onUnsupportedFeature;
+ this.nativeFontFaces = [];
+ this.styleElement = null;
+ }
+
+ _createClass(BaseFontLoader, [{
+ key: "addNativeFontFace",
+ value: function addNativeFontFace(nativeFontFace) {
+ this.nativeFontFaces.push(nativeFontFace);
+ document.fonts.add(nativeFontFace);
+ }
+ }, {
+ key: "insertRule",
+ value: function insertRule(rule) {
+ var styleElement = this.styleElement;
+
+ if (!styleElement) {
+ styleElement = this.styleElement = document.createElement('style');
+ styleElement.id = "PDFJS_FONT_STYLE_TAG_".concat(this.docId);
+ document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
+ }
+
+ var styleSheet = styleElement.sheet;
+ styleSheet.insertRule(rule, styleSheet.cssRules.length);
+ }
+ }, {
+ key: "clear",
+ value: function clear() {
+ this.nativeFontFaces.forEach(function (nativeFontFace) {
+ document.fonts["delete"](nativeFontFace);
+ });
+ this.nativeFontFaces.length = 0;
+
+ if (this.styleElement) {
+ this.styleElement.remove();
+ this.styleElement = null;
+ }
+ }
+ }, {
+ key: "bind",
+ value: function () {
+ var _bind = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee(font) {
+ var _this = this;
+
+ var nativeFontFace, rule;
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (!(font.attached || font.missingFile)) {
+ _context.next = 2;
+ break;
+ }
+
+ return _context.abrupt("return", undefined);
+
+ case 2:
+ font.attached = true;
+
+ if (!this.isFontLoadingAPISupported) {
+ _context.next = 19;
+ break;
+ }
+
+ nativeFontFace = font.createNativeFontFace();
+
+ if (!nativeFontFace) {
+ _context.next = 18;
+ break;
+ }
+
+ this.addNativeFontFace(nativeFontFace);
+ _context.prev = 7;
+ _context.next = 10;
+ return nativeFontFace.loaded;
+
+ case 10:
+ _context.next = 18;
+ break;
+
+ case 12:
+ _context.prev = 12;
+ _context.t0 = _context["catch"](7);
+
+ this._onUnsupportedFeature({
+ featureId: _util.UNSUPPORTED_FEATURES.font
+ });
+
+ (0, _util.warn)("Failed to load font '".concat(nativeFontFace.family, "': '").concat(_context.t0, "'."));
+ font.disableFontFace = true;
+ throw _context.t0;
+
+ case 18:
+ return _context.abrupt("return", undefined);
+
+ case 19:
+ rule = font.createFontFaceRule();
+
+ if (!rule) {
+ _context.next = 25;
+ break;
+ }
+
+ this.insertRule(rule);
+
+ if (!this.isSyncFontLoadingSupported) {
+ _context.next = 24;
+ break;
+ }
+
+ return _context.abrupt("return", undefined);
+
+ case 24:
+ return _context.abrupt("return", new Promise(function (resolve) {
+ var request = _this._queueLoadingCallback(resolve);
+
+ _this._prepareFontLoadEvent([rule], [font], request);
+ }));
+
+ case 25:
+ return _context.abrupt("return", undefined);
+
+ case 26:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee, this, [[7, 12]]);
+ }));
+
+ function bind(_x) {
+ return _bind.apply(this, arguments);
+ }
+
+ return bind;
+ }()
+ }, {
+ key: "_queueLoadingCallback",
+ value: function _queueLoadingCallback(callback) {
+ (0, _util.unreachable)('Abstract method `_queueLoadingCallback`.');
+ }
+ }, {
+ key: "_prepareFontLoadEvent",
+ value: function _prepareFontLoadEvent(rules, fontsToLoad, request) {
+ (0, _util.unreachable)('Abstract method `_prepareFontLoadEvent`.');
+ }
+ }, {
+ key: "isFontLoadingAPISupported",
+ get: function get() {
+ (0, _util.unreachable)('Abstract method `isFontLoadingAPISupported`.');
+ }
+ }, {
+ key: "isSyncFontLoadingSupported",
+ get: function get() {
+ (0, _util.unreachable)('Abstract method `isSyncFontLoadingSupported`.');
+ }
+ }, {
+ key: "_loadTestFont",
+ get: function get() {
+ (0, _util.unreachable)('Abstract method `_loadTestFont`.');
+ }
+ }]);
+
+ return BaseFontLoader;
+}();
+
+var FontLoader;
+exports.FontLoader = FontLoader;
+{
+ exports.FontLoader = FontLoader =
+ /*#__PURE__*/
+ function (_BaseFontLoader) {
+ _inherits(GenericFontLoader, _BaseFontLoader);
+
+ function GenericFontLoader(docId) {
+ var _this2;
+
+ _classCallCheck(this, GenericFontLoader);
+
+ _this2 = _possibleConstructorReturn(this, _getPrototypeOf(GenericFontLoader).call(this, docId));
+ _this2.loadingContext = {
+ requests: [],
+ nextRequestId: 0
+ };
+ _this2.loadTestFontId = 0;
+ return _this2;
+ }
+
+ _createClass(GenericFontLoader, [{
+ key: "_queueLoadingCallback",
+ value: function _queueLoadingCallback(callback) {
+ function completeRequest() {
+ (0, _util.assert)(!request.done, 'completeRequest() cannot be called twice.');
+ request.done = true;
+
+ while (context.requests.length > 0 && context.requests[0].done) {
+ var otherRequest = context.requests.shift();
+ setTimeout(otherRequest.callback, 0);
+ }
+ }
+
+ var context = this.loadingContext;
+ var request = {
+ id: "pdfjs-font-loading-".concat(context.nextRequestId++),
+ done: false,
+ complete: completeRequest,
+ callback: callback
+ };
+ context.requests.push(request);
+ return request;
+ }
+ }, {
+ key: "_prepareFontLoadEvent",
+ value: function _prepareFontLoadEvent(rules, fonts, request) {
+ function int32(data, offset) {
+ return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
+ }
+
+ function spliceString(s, offset, remove, insert) {
+ var chunk1 = s.substring(0, offset);
+ var chunk2 = s.substring(offset + remove);
+ return chunk1 + insert + chunk2;
+ }
+
+ var i, ii;
+ var canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ var ctx = canvas.getContext('2d');
+ var called = 0;
+
+ function isFontReady(name, callback) {
+ called++;
+
+ if (called > 30) {
+ (0, _util.warn)('Load test font never loaded.');
+ callback();
+ return;
+ }
+
+ ctx.font = '30px ' + name;
+ ctx.fillText('.', 0, 20);
+ var imageData = ctx.getImageData(0, 0, 1, 1);
+
+ if (imageData.data[3] > 0) {
+ callback();
+ return;
+ }
+
+ setTimeout(isFontReady.bind(null, name, callback));
+ }
+
+ var loadTestFontId = "lt".concat(Date.now()).concat(this.loadTestFontId++);
+ var data = this._loadTestFont;
+ var COMMENT_OFFSET = 976;
+ data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
+ var CFF_CHECKSUM_OFFSET = 16;
+ var XXXX_VALUE = 0x58585858;
+ var checksum = int32(data, CFF_CHECKSUM_OFFSET);
+
+ for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
+ checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
+ }
+
+ if (i < loadTestFontId.length) {
+ checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
+ }
+
+ data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
+ var url = "url(data:font/opentype;base64,".concat(btoa(data), ");");
+ var rule = "@font-face {font-family:\"".concat(loadTestFontId, "\";src:").concat(url, "}");
+ this.insertRule(rule);
+ var names = [];
+
+ for (i = 0, ii = fonts.length; i < ii; i++) {
+ names.push(fonts[i].loadedName);
+ }
+
+ names.push(loadTestFontId);
+ var div = document.createElement('div');
+ div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
+
+ for (i = 0, ii = names.length; i < ii; ++i) {
+ var span = document.createElement('span');
+ span.textContent = 'Hi';
+ span.style.fontFamily = names[i];
+ div.appendChild(span);
+ }
+
+ document.body.appendChild(div);
+ isFontReady(loadTestFontId, function () {
+ document.body.removeChild(div);
+ request.complete();
+ });
+ }
+ }, {
+ key: "isFontLoadingAPISupported",
+ get: function get() {
+ var supported = typeof document !== 'undefined' && !!document.fonts;
+
+ if (supported && typeof navigator !== 'undefined') {
+ var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
+
+ if (m && m[1] < 63) {
+ supported = false;
+ }
+ }
+
+ return (0, _util.shadow)(this, 'isFontLoadingAPISupported', supported);
+ }
+ }, {
+ key: "isSyncFontLoadingSupported",
+ get: function get() {
+ var supported = false;
+
+ if (typeof navigator === 'undefined') {
+ supported = true;
+ } else {
+ var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
+
+ if (m && m[1] >= 14) {
+ supported = true;
+ }
+ }
+
+ return (0, _util.shadow)(this, 'isSyncFontLoadingSupported', supported);
+ }
+ }, {
+ key: "_loadTestFont",
+ get: function get() {
+ var getLoadTestFont = function getLoadTestFont() {
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AAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA' + 'AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC' + 'AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3' + 'Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj' + 'FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==');
+ };
+
+ return (0, _util.shadow)(this, '_loadTestFont', getLoadTestFont());
+ }
+ }]);
+
+ return GenericFontLoader;
+ }(BaseFontLoader);
+}
+var IsEvalSupportedCached = {
+ get value() {
+ return (0, _util.shadow)(this, 'value', (0, _util.isEvalSupported)());
+ }
+
+};
+
+var FontFaceObject =
+/*#__PURE__*/
+function () {
+ function FontFaceObject(translatedData, _ref2) {
+ var _ref2$isEvalSupported = _ref2.isEvalSupported,
+ isEvalSupported = _ref2$isEvalSupported === void 0 ? true : _ref2$isEvalSupported,
+ _ref2$disableFontFace = _ref2.disableFontFace,
+ disableFontFace = _ref2$disableFontFace === void 0 ? false : _ref2$disableFontFace,
+ _ref2$ignoreErrors = _ref2.ignoreErrors,
+ ignoreErrors = _ref2$ignoreErrors === void 0 ? false : _ref2$ignoreErrors,
+ _ref2$onUnsupportedFe = _ref2.onUnsupportedFeature,
+ onUnsupportedFeature = _ref2$onUnsupportedFe === void 0 ? null : _ref2$onUnsupportedFe,
+ _ref2$fontRegistry = _ref2.fontRegistry,
+ fontRegistry = _ref2$fontRegistry === void 0 ? null : _ref2$fontRegistry;
+
+ _classCallCheck(this, FontFaceObject);
+
+ this.compiledGlyphs = Object.create(null);
+
+ for (var i in translatedData) {
+ this[i] = translatedData[i];
+ }
+
+ this.isEvalSupported = isEvalSupported !== false;
+ this.disableFontFace = disableFontFace === true;
+ this.ignoreErrors = ignoreErrors === true;
+ this._onUnsupportedFeature = onUnsupportedFeature;
+ this.fontRegistry = fontRegistry;
+ }
+
+ _createClass(FontFaceObject, [{
+ key: "createNativeFontFace",
+ value: function createNativeFontFace() {
+ if (!this.data || this.disableFontFace) {
+ return null;
+ }
+
+ var nativeFontFace = new FontFace(this.loadedName, this.data, {});
+
+ if (this.fontRegistry) {
+ this.fontRegistry.registerFont(this);
+ }
+
+ return nativeFontFace;
+ }
+ }, {
+ key: "createFontFaceRule",
+ value: function createFontFaceRule() {
+ if (!this.data || this.disableFontFace) {
+ return null;
+ }
+
+ var data = (0, _util.bytesToString)(new Uint8Array(this.data));
+ var url = "url(data:".concat(this.mimetype, ";base64,").concat(btoa(data), ");");
+ var rule = "@font-face {font-family:\"".concat(this.loadedName, "\";src:").concat(url, "}");
+
+ if (this.fontRegistry) {
+ this.fontRegistry.registerFont(this, url);
+ }
+
+ return rule;
+ }
+ }, {
+ key: "getPathGenerator",
+ value: function getPathGenerator(objs, character) {
+ if (this.compiledGlyphs[character] !== undefined) {
+ return this.compiledGlyphs[character];
+ }
+
+ var cmds, current;
+
+ try {
+ cmds = objs.get(this.loadedName + '_path_' + character);
+ } catch (ex) {
+ if (!this.ignoreErrors) {
+ throw ex;
+ }
+
+ if (this._onUnsupportedFeature) {
+ this._onUnsupportedFeature({
+ featureId: _util.UNSUPPORTED_FEATURES.font
+ });
+ }
+
+ (0, _util.warn)("getPathGenerator - ignoring character: \"".concat(ex, "\"."));
+ return this.compiledGlyphs[character] = function (c, size) {};
+ }
+
+ if (this.isEvalSupported && IsEvalSupportedCached.value) {
+ var args,
+ js = '';
+
+ for (var i = 0, ii = cmds.length; i < ii; i++) {
+ current = cmds[i];
+
+ if (current.args !== undefined) {
+ args = current.args.join(',');
+ } else {
+ args = '';
+ }
+
+ js += 'c.' + current.cmd + '(' + args + ');\n';
+ }
+
+ return this.compiledGlyphs[character] = new Function('c', 'size', js);
+ }
+
+ return this.compiledGlyphs[character] = function (c, size) {
+ for (var _i = 0, _ii = cmds.length; _i < _ii; _i++) {
+ current = cmds[_i];
+
+ if (current.cmd === 'scale') {
+ current.args = [size, -size];
+ }
+
+ c[current.cmd].apply(c, current.args);
+ }
+ };
+ }
+ }]);
+
+ return FontFaceObject;
+}();
+
+exports.FontFaceObject = FontFaceObject;
+
+/***/ }),
+/* 153 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+var compatibilityParams = Object.create(null);
+{
+ var isNodeJS = __w_pdfjs_require__(4);
+
+ var userAgent = typeof navigator !== 'undefined' && navigator.userAgent || '';
+ var isIE = /Trident/.test(userAgent);
+ var isIOSChrome = /CriOS/.test(userAgent);
+
+ (function checkOnBlobSupport() {
+ if (isIE || isIOSChrome) {
+ compatibilityParams.disableCreateObjectURL = true;
+ }
+ })();
+
+ (function checkFontFaceAndImage() {
+ if (isNodeJS()) {
+ compatibilityParams.disableFontFace = true;
+ compatibilityParams.nativeImageDecoderSupport = 'none';
+ }
+ })();
+}
+exports.apiCompatibilityParams = Object.freeze(compatibilityParams);
+
+/***/ }),
+/* 154 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.CanvasGraphics = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+var _pattern_helper = __w_pdfjs_require__(155);
+
+var MIN_FONT_SIZE = 16;
+var MAX_FONT_SIZE = 100;
+var MAX_GROUP_SIZE = 4096;
+var MIN_WIDTH_FACTOR = 0.65;
+var COMPILE_TYPE3_GLYPHS = true;
+var MAX_SIZE_TO_COMPILE = 1000;
+var FULL_CHUNK_HEIGHT = 16;
+var IsLittleEndianCached = {
+ get value() {
+ return (0, _util.shadow)(IsLittleEndianCached, 'value', (0, _util.isLittleEndian)());
+ }
+
+};
+
+function addContextCurrentTransform(ctx) {
+ if (!ctx.mozCurrentTransform) {
+ ctx._originalSave = ctx.save;
+ ctx._originalRestore = ctx.restore;
+ ctx._originalRotate = ctx.rotate;
+ ctx._originalScale = ctx.scale;
+ ctx._originalTranslate = ctx.translate;
+ ctx._originalTransform = ctx.transform;
+ ctx._originalSetTransform = ctx.setTransform;
+ ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
+ ctx._transformStack = [];
+ Object.defineProperty(ctx, 'mozCurrentTransform', {
+ get: function getCurrentTransform() {
+ return this._transformMatrix;
+ }
+ });
+ Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
+ get: function getCurrentTransformInverse() {
+ var m = this._transformMatrix;
+ var a = m[0],
+ b = m[1],
+ c = m[2],
+ d = m[3],
+ e = m[4],
+ f = m[5];
+ var ad_bc = a * d - b * c;
+ var bc_ad = b * c - a * d;
+ return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc];
+ }
+ });
+
+ ctx.save = function ctxSave() {
+ var old = this._transformMatrix;
+
+ this._transformStack.push(old);
+
+ this._transformMatrix = old.slice(0, 6);
+
+ this._originalSave();
+ };
+
+ ctx.restore = function ctxRestore() {
+ var prev = this._transformStack.pop();
+
+ if (prev) {
+ this._transformMatrix = prev;
+
+ this._originalRestore();
+ }
+ };
+
+ ctx.translate = function ctxTranslate(x, y) {
+ var m = this._transformMatrix;
+ m[4] = m[0] * x + m[2] * y + m[4];
+ m[5] = m[1] * x + m[3] * y + m[5];
+
+ this._originalTranslate(x, y);
+ };
+
+ ctx.scale = function ctxScale(x, y) {
+ var m = this._transformMatrix;
+ m[0] = m[0] * x;
+ m[1] = m[1] * x;
+ m[2] = m[2] * y;
+ m[3] = m[3] * y;
+
+ this._originalScale(x, y);
+ };
+
+ ctx.transform = function ctxTransform(a, b, c, d, e, f) {
+ var m = this._transformMatrix;
+ this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]];
+
+ ctx._originalTransform(a, b, c, d, e, f);
+ };
+
+ ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
+ this._transformMatrix = [a, b, c, d, e, f];
+
+ ctx._originalSetTransform(a, b, c, d, e, f);
+ };
+
+ ctx.rotate = function ctxRotate(angle) {
+ var cosValue = Math.cos(angle);
+ var sinValue = Math.sin(angle);
+ var m = this._transformMatrix;
+ this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]];
+
+ this._originalRotate(angle);
+ };
+ }
+}
+
+var CachedCanvases = function CachedCanvasesClosure() {
+ function CachedCanvases(canvasFactory) {
+ this.canvasFactory = canvasFactory;
+ this.cache = Object.create(null);
+ }
+
+ CachedCanvases.prototype = {
+ getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
+ var canvasEntry;
+
+ if (this.cache[id] !== undefined) {
+ canvasEntry = this.cache[id];
+ this.canvasFactory.reset(canvasEntry, width, height);
+ canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
+ } else {
+ canvasEntry = this.canvasFactory.create(width, height);
+ this.cache[id] = canvasEntry;
+ }
+
+ if (trackTransform) {
+ addContextCurrentTransform(canvasEntry.context);
+ }
+
+ return canvasEntry;
+ },
+ clear: function clear() {
+ for (var id in this.cache) {
+ var canvasEntry = this.cache[id];
+ this.canvasFactory.destroy(canvasEntry);
+ delete this.cache[id];
+ }
+ }
+ };
+ return CachedCanvases;
+}();
+
+function compileType3Glyph(imgData) {
+ var POINT_TO_PROCESS_LIMIT = 1000;
+ var width = imgData.width,
+ height = imgData.height;
+ var i,
+ j,
+ j0,
+ width1 = width + 1;
+ var points = new Uint8Array(width1 * (height + 1));
+ var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
+ var lineSize = width + 7 & ~7,
+ data0 = imgData.data;
+ var data = new Uint8Array(lineSize * height),
+ pos = 0,
+ ii;
+
+ for (i = 0, ii = data0.length; i < ii; i++) {
+ var mask = 128,
+ elem = data0[i];
+
+ while (mask > 0) {
+ data[pos++] = elem & mask ? 0 : 255;
+ mask >>= 1;
+ }
+ }
+
+ var count = 0;
+ pos = 0;
+
+ if (data[pos] !== 0) {
+ points[0] = 1;
+ ++count;
+ }
+
+ for (j = 1; j < width; j++) {
+ if (data[pos] !== data[pos + 1]) {
+ points[j] = data[pos] ? 2 : 1;
+ ++count;
+ }
+
+ pos++;
+ }
+
+ if (data[pos] !== 0) {
+ points[j] = 2;
+ ++count;
+ }
+
+ for (i = 1; i < height; i++) {
+ pos = i * lineSize;
+ j0 = i * width1;
+
+ if (data[pos - lineSize] !== data[pos]) {
+ points[j0] = data[pos] ? 1 : 8;
+ ++count;
+ }
+
+ var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
+
+ for (j = 1; j < width; j++) {
+ sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
+
+ if (POINT_TYPES[sum]) {
+ points[j0 + j] = POINT_TYPES[sum];
+ ++count;
+ }
+
+ pos++;
+ }
+
+ if (data[pos - lineSize] !== data[pos]) {
+ points[j0 + j] = data[pos] ? 2 : 4;
+ ++count;
+ }
+
+ if (count > POINT_TO_PROCESS_LIMIT) {
+ return null;
+ }
+ }
+
+ pos = lineSize * (height - 1);
+ j0 = i * width1;
+
+ if (data[pos] !== 0) {
+ points[j0] = 8;
+ ++count;
+ }
+
+ for (j = 1; j < width; j++) {
+ if (data[pos] !== data[pos + 1]) {
+ points[j0 + j] = data[pos] ? 4 : 8;
+ ++count;
+ }
+
+ pos++;
+ }
+
+ if (data[pos] !== 0) {
+ points[j0 + j] = 4;
+ ++count;
+ }
+
+ if (count > POINT_TO_PROCESS_LIMIT) {
+ return null;
+ }
+
+ var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
+ var outlines = [];
+
+ for (i = 0; count && i <= height; i++) {
+ var p = i * width1;
+ var end = p + width;
+
+ while (p < end && !points[p]) {
+ p++;
+ }
+
+ if (p === end) {
+ continue;
+ }
+
+ var coords = [p % width1, i];
+ var type = points[p],
+ p0 = p,
+ pp;
+
+ do {
+ var step = steps[type];
+
+ do {
+ p += step;
+ } while (!points[p]);
+
+ pp = points[p];
+
+ if (pp !== 5 && pp !== 10) {
+ type = pp;
+ points[p] = 0;
+ } else {
+ type = pp & 0x33 * type >> 4;
+ points[p] &= type >> 2 | type << 2;
+ }
+
+ coords.push(p % width1);
+ coords.push(p / width1 | 0);
+
+ if (!points[p]) {
+ --count;
+ }
+ } while (p0 !== p);
+
+ outlines.push(coords);
+ --i;
+ }
+
+ var drawOutline = function drawOutline(c) {
+ c.save();
+ c.scale(1 / width, -1 / height);
+ c.translate(0, -height);
+ c.beginPath();
+
+ for (var i = 0, ii = outlines.length; i < ii; i++) {
+ var o = outlines[i];
+ c.moveTo(o[0], o[1]);
+
+ for (var j = 2, jj = o.length; j < jj; j += 2) {
+ c.lineTo(o[j], o[j + 1]);
+ }
+ }
+
+ c.fill();
+ c.beginPath();
+ c.restore();
+ };
+
+ return drawOutline;
+}
+
+var CanvasExtraState = function CanvasExtraStateClosure() {
+ function CanvasExtraState() {
+ this.alphaIsShape = false;
+ this.fontSize = 0;
+ this.fontSizeScale = 1;
+ this.textMatrix = _util.IDENTITY_MATRIX;
+ this.textMatrixScale = 1;
+ this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
+ this.leading = 0;
+ this.x = 0;
+ this.y = 0;
+ this.lineX = 0;
+ this.lineY = 0;
+ this.charSpacing = 0;
+ this.wordSpacing = 0;
+ this.textHScale = 1;
+ this.textRenderingMode = _util.TextRenderingMode.FILL;
+ this.textRise = 0;
+ this.fillColor = '#000000';
+ this.strokeColor = '#000000';
+ this.patternFill = false;
+ this.fillAlpha = 1;
+ this.strokeAlpha = 1;
+ this.lineWidth = 1;
+ this.activeSMask = null;
+ this.resumeSMaskCtx = null;
+ }
+
+ CanvasExtraState.prototype = {
+ clone: function CanvasExtraState_clone() {
+ return Object.create(this);
+ },
+ setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
+ this.x = x;
+ this.y = y;
+ }
+ };
+ return CanvasExtraState;
+}();
+
+var CanvasGraphics = function CanvasGraphicsClosure() {
+ var EXECUTION_TIME = 15;
+ var EXECUTION_STEPS = 10;
+
+ function CanvasGraphics(canvasCtx, commonObjs, objs, canvasFactory, webGLContext, imageLayer) {
+ this.ctx = canvasCtx;
+ this.current = new CanvasExtraState();
+ this.stateStack = [];
+ this.pendingClip = null;
+ this.pendingEOFill = false;
+ this.res = null;
+ this.xobjs = null;
+ this.commonObjs = commonObjs;
+ this.objs = objs;
+ this.canvasFactory = canvasFactory;
+ this.webGLContext = webGLContext;
+ this.imageLayer = imageLayer;
+ this.groupStack = [];
+ this.processingType3 = null;
+ this.baseTransform = null;
+ this.baseTransformStack = [];
+ this.groupLevel = 0;
+ this.smaskStack = [];
+ this.smaskCounter = 0;
+ this.tempSMask = null;
+ this.cachedCanvases = new CachedCanvases(this.canvasFactory);
+
+ if (canvasCtx) {
+ addContextCurrentTransform(canvasCtx);
+ }
+
+ this._cachedGetSinglePixelWidth = null;
+ }
+
+ function putBinaryImageData(ctx, imgData) {
+ if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
+ ctx.putImageData(imgData, 0, 0);
+ return;
+ }
+
+ var height = imgData.height,
+ width = imgData.width;
+ var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
+ var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
+ var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
+ var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
+ var srcPos = 0,
+ destPos;
+ var src = imgData.data;
+ var dest = chunkImgData.data;
+ var i, j, thisChunkHeight, elemsInThisChunk;
+
+ if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
+ var srcLength = src.byteLength;
+ var dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
+ var dest32DataLength = dest32.length;
+ var fullSrcDiff = width + 7 >> 3;
+ var white = 0xFFFFFFFF;
+ var black = IsLittleEndianCached.value ? 0xFF000000 : 0x000000FF;
+
+ for (i = 0; i < totalChunks; i++) {
+ thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
+ destPos = 0;
+
+ for (j = 0; j < thisChunkHeight; j++) {
+ var srcDiff = srcLength - srcPos;
+ var k = 0;
+ var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
+ var kEndUnrolled = kEnd & ~7;
+ var mask = 0;
+ var srcByte = 0;
+
+ for (; k < kEndUnrolled; k += 8) {
+ srcByte = src[srcPos++];
+ dest32[destPos++] = srcByte & 128 ? white : black;
+ dest32[destPos++] = srcByte & 64 ? white : black;
+ dest32[destPos++] = srcByte & 32 ? white : black;
+ dest32[destPos++] = srcByte & 16 ? white : black;
+ dest32[destPos++] = srcByte & 8 ? white : black;
+ dest32[destPos++] = srcByte & 4 ? white : black;
+ dest32[destPos++] = srcByte & 2 ? white : black;
+ dest32[destPos++] = srcByte & 1 ? white : black;
+ }
+
+ for (; k < kEnd; k++) {
+ if (mask === 0) {
+ srcByte = src[srcPos++];
+ mask = 128;
+ }
+
+ dest32[destPos++] = srcByte & mask ? white : black;
+ mask >>= 1;
+ }
+ }
+
+ while (destPos < dest32DataLength) {
+ dest32[destPos++] = 0;
+ }
+
+ ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
+ }
+ } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
+ j = 0;
+ elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
+
+ for (i = 0; i < fullChunks; i++) {
+ dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
+ srcPos += elemsInThisChunk;
+ ctx.putImageData(chunkImgData, 0, j);
+ j += FULL_CHUNK_HEIGHT;
+ }
+
+ if (i < totalChunks) {
+ elemsInThisChunk = width * partialChunkHeight * 4;
+ dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
+ ctx.putImageData(chunkImgData, 0, j);
+ }
+ } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
+ thisChunkHeight = FULL_CHUNK_HEIGHT;
+ elemsInThisChunk = width * thisChunkHeight;
+
+ for (i = 0; i < totalChunks; i++) {
+ if (i >= fullChunks) {
+ thisChunkHeight = partialChunkHeight;
+ elemsInThisChunk = width * thisChunkHeight;
+ }
+
+ destPos = 0;
+
+ for (j = elemsInThisChunk; j--;) {
+ dest[destPos++] = src[srcPos++];
+ dest[destPos++] = src[srcPos++];
+ dest[destPos++] = src[srcPos++];
+ dest[destPos++] = 255;
+ }
+
+ ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
+ }
+ } else {
+ throw new Error("bad image kind: ".concat(imgData.kind));
+ }
+ }
+
+ function putBinaryImageMask(ctx, imgData) {
+ var height = imgData.height,
+ width = imgData.width;
+ var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
+ var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
+ var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
+ var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
+ var srcPos = 0;
+ var src = imgData.data;
+ var dest = chunkImgData.data;
+
+ for (var i = 0; i < totalChunks; i++) {
+ var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
+ var destPos = 3;
+
+ for (var j = 0; j < thisChunkHeight; j++) {
+ var mask = 0;
+
+ for (var k = 0; k < width; k++) {
+ if (!mask) {
+ var elem = src[srcPos++];
+ mask = 128;
+ }
+
+ dest[destPos] = elem & mask ? 0 : 255;
+ destPos += 4;
+ mask >>= 1;
+ }
+ }
+
+ ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
+ }
+ }
+
+ function copyCtxState(sourceCtx, destCtx) {
+ var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font'];
+
+ for (var i = 0, ii = properties.length; i < ii; i++) {
+ var property = properties[i];
+
+ if (sourceCtx[property] !== undefined) {
+ destCtx[property] = sourceCtx[property];
+ }
+ }
+
+ if (sourceCtx.setLineDash !== undefined) {
+ destCtx.setLineDash(sourceCtx.getLineDash());
+ destCtx.lineDashOffset = sourceCtx.lineDashOffset;
+ }
+ }
+
+ function resetCtxToDefault(ctx) {
+ ctx.strokeStyle = '#000000';
+ ctx.fillStyle = '#000000';
+ ctx.fillRule = 'nonzero';
+ ctx.globalAlpha = 1;
+ ctx.lineWidth = 1;
+ ctx.lineCap = 'butt';
+ ctx.lineJoin = 'miter';
+ ctx.miterLimit = 10;
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.font = '10px sans-serif';
+
+ if (ctx.setLineDash !== undefined) {
+ ctx.setLineDash([]);
+ ctx.lineDashOffset = 0;
+ }
+ }
+
+ function composeSMaskBackdrop(bytes, r0, g0, b0) {
+ var length = bytes.length;
+
+ for (var i = 3; i < length; i += 4) {
+ var alpha = bytes[i];
+
+ if (alpha === 0) {
+ bytes[i - 3] = r0;
+ bytes[i - 2] = g0;
+ bytes[i - 1] = b0;
+ } else if (alpha < 255) {
+ var alpha_ = 255 - alpha;
+ bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
+ bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
+ bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
+ }
+ }
+ }
+
+ function composeSMaskAlpha(maskData, layerData, transferMap) {
+ var length = maskData.length;
+ var scale = 1 / 255;
+
+ for (var i = 3; i < length; i += 4) {
+ var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
+ layerData[i] = layerData[i] * alpha * scale | 0;
+ }
+ }
+
+ function composeSMaskLuminosity(maskData, layerData, transferMap) {
+ var length = maskData.length;
+
+ for (var i = 3; i < length; i += 4) {
+ var y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
+ layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
+ }
+ }
+
+ function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
+ var hasBackdrop = !!backdrop;
+ var r0 = hasBackdrop ? backdrop[0] : 0;
+ var g0 = hasBackdrop ? backdrop[1] : 0;
+ var b0 = hasBackdrop ? backdrop[2] : 0;
+ var composeFn;
+
+ if (subtype === 'Luminosity') {
+ composeFn = composeSMaskLuminosity;
+ } else {
+ composeFn = composeSMaskAlpha;
+ }
+
+ var PIXELS_TO_PROCESS = 1048576;
+ var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
+
+ for (var row = 0; row < height; row += chunkSize) {
+ var chunkHeight = Math.min(chunkSize, height - row);
+ var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
+ var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
+
+ if (hasBackdrop) {
+ composeSMaskBackdrop(maskData.data, r0, g0, b0);
+ }
+
+ composeFn(maskData.data, layerData.data, transferMap);
+ maskCtx.putImageData(layerData, 0, row);
+ }
+ }
+
+ function composeSMask(ctx, smask, layerCtx, webGLContext) {
+ var mask = smask.canvas;
+ var maskCtx = smask.context;
+ ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
+ var backdrop = smask.backdrop || null;
+
+ if (!smask.transferMap && webGLContext.isEnabled) {
+ var composed = webGLContext.composeSMask({
+ layer: layerCtx.canvas,
+ mask: mask,
+ properties: {
+ subtype: smask.subtype,
+ backdrop: backdrop
+ }
+ });
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.drawImage(composed, smask.offsetX, smask.offsetY);
+ return;
+ }
+
+ genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
+ ctx.drawImage(mask, 0, 0);
+ }
+
+ var LINE_CAP_STYLES = ['butt', 'round', 'square'];
+ var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
+ var NORMAL_CLIP = {};
+ var EO_CLIP = {};
+ CanvasGraphics.prototype = {
+ beginDrawing: function beginDrawing(_ref) {
+ var transform = _ref.transform,
+ viewport = _ref.viewport,
+ _ref$transparency = _ref.transparency,
+ transparency = _ref$transparency === void 0 ? false : _ref$transparency,
+ _ref$background = _ref.background,
+ background = _ref$background === void 0 ? null : _ref$background;
+ var width = this.ctx.canvas.width;
+ var height = this.ctx.canvas.height;
+ this.ctx.save();
+ this.ctx.fillStyle = background || 'rgb(255, 255, 255)';
+ this.ctx.fillRect(0, 0, width, height);
+ this.ctx.restore();
+
+ if (transparency) {
+ var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
+ this.compositeCtx = this.ctx;
+ this.transparentCanvas = transparentCanvas.canvas;
+ this.ctx = transparentCanvas.context;
+ this.ctx.save();
+ this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
+ }
+
+ this.ctx.save();
+ resetCtxToDefault(this.ctx);
+
+ if (transform) {
+ this.ctx.transform.apply(this.ctx, transform);
+ }
+
+ this.ctx.transform.apply(this.ctx, viewport.transform);
+ this.baseTransform = this.ctx.mozCurrentTransform.slice();
+
+ if (this.imageLayer) {
+ this.imageLayer.beginLayout();
+ }
+ },
+ executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
+ var argsArray = operatorList.argsArray;
+ var fnArray = operatorList.fnArray;
+ var i = executionStartIdx || 0;
+ var argsArrayLen = argsArray.length;
+
+ if (argsArrayLen === i) {
+ return i;
+ }
+
+ var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
+ var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
+ var steps = 0;
+ var commonObjs = this.commonObjs;
+ var objs = this.objs;
+ var fnId;
+
+ while (true) {
+ if (stepper !== undefined && i === stepper.nextBreakPoint) {
+ stepper.breakIt(i, continueCallback);
+ return i;
+ }
+
+ fnId = fnArray[i];
+
+ if (fnId !== _util.OPS.dependency) {
+ this[fnId].apply(this, argsArray[i]);
+ } else {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = argsArray[i][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var depObjId = _step.value;
+ var objsPool = depObjId.startsWith('g_') ? commonObjs : objs;
+
+ if (!objsPool.has(depObjId)) {
+ objsPool.get(depObjId, continueCallback);
+ return i;
+ }
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+ _iterator["return"]();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ }
+
+ i++;
+
+ if (i === argsArrayLen) {
+ return i;
+ }
+
+ if (chunkOperations && ++steps > EXECUTION_STEPS) {
+ if (Date.now() > endTime) {
+ continueCallback();
+ return i;
+ }
+
+ steps = 0;
+ }
+ }
+ },
+ endDrawing: function CanvasGraphics_endDrawing() {
+ if (this.current.activeSMask !== null) {
+ this.endSMaskGroup();
+ }
+
+ this.ctx.restore();
+
+ if (this.transparentCanvas) {
+ this.ctx = this.compositeCtx;
+ this.ctx.save();
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0);
+ this.ctx.drawImage(this.transparentCanvas, 0, 0);
+ this.ctx.restore();
+ this.transparentCanvas = null;
+ }
+
+ this.cachedCanvases.clear();
+ this.webGLContext.clear();
+
+ if (this.imageLayer) {
+ this.imageLayer.endLayout();
+ }
+ },
+ setLineWidth: function CanvasGraphics_setLineWidth(width) {
+ this.current.lineWidth = width;
+ this.ctx.lineWidth = width;
+ },
+ setLineCap: function CanvasGraphics_setLineCap(style) {
+ this.ctx.lineCap = LINE_CAP_STYLES[style];
+ },
+ setLineJoin: function CanvasGraphics_setLineJoin(style) {
+ this.ctx.lineJoin = LINE_JOIN_STYLES[style];
+ },
+ setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
+ this.ctx.miterLimit = limit;
+ },
+ setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
+ var ctx = this.ctx;
+
+ if (ctx.setLineDash !== undefined) {
+ ctx.setLineDash(dashArray);
+ ctx.lineDashOffset = dashPhase;
+ }
+ },
+ setRenderingIntent: function setRenderingIntent(intent) {},
+ setFlatness: function setFlatness(flatness) {},
+ setGState: function CanvasGraphics_setGState(states) {
+ for (var i = 0, ii = states.length; i < ii; i++) {
+ var state = states[i];
+ var key = state[0];
+ var value = state[1];
+
+ switch (key) {
+ case 'LW':
+ this.setLineWidth(value);
+ break;
+
+ case 'LC':
+ this.setLineCap(value);
+ break;
+
+ case 'LJ':
+ this.setLineJoin(value);
+ break;
+
+ case 'ML':
+ this.setMiterLimit(value);
+ break;
+
+ case 'D':
+ this.setDash(value[0], value[1]);
+ break;
+
+ case 'RI':
+ this.setRenderingIntent(value);
+ break;
+
+ case 'FL':
+ this.setFlatness(value);
+ break;
+
+ case 'Font':
+ this.setFont(value[0], value[1]);
+ break;
+
+ case 'CA':
+ this.current.strokeAlpha = state[1];
+ break;
+
+ case 'ca':
+ this.current.fillAlpha = state[1];
+ this.ctx.globalAlpha = state[1];
+ break;
+
+ case 'BM':
+ this.ctx.globalCompositeOperation = value;
+ break;
+
+ case 'SMask':
+ if (this.current.activeSMask) {
+ if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
+ this.suspendSMaskGroup();
+ } else {
+ this.endSMaskGroup();
+ }
+ }
+
+ this.current.activeSMask = value ? this.tempSMask : null;
+
+ if (this.current.activeSMask) {
+ this.beginSMaskGroup();
+ }
+
+ this.tempSMask = null;
+ break;
+ }
+ }
+ },
+ beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
+ var activeSMask = this.current.activeSMask;
+ var drawnWidth = activeSMask.canvas.width;
+ var drawnHeight = activeSMask.canvas.height;
+ var cacheId = 'smaskGroupAt' + this.groupLevel;
+ var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
+ var currentCtx = this.ctx;
+ var currentTransform = currentCtx.mozCurrentTransform;
+ this.ctx.save();
+ var groupCtx = scratchCanvas.context;
+ groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
+ groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
+ groupCtx.transform.apply(groupCtx, currentTransform);
+ activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
+ copyCtxState(currentCtx, groupCtx);
+ this.ctx = groupCtx;
+ this.setGState([['BM', 'source-over'], ['ca', 1], ['CA', 1]]);
+ this.groupStack.push(currentCtx);
+ this.groupLevel++;
+ },
+ suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
+ var groupCtx = this.ctx;
+ this.groupLevel--;
+ this.ctx = this.groupStack.pop();
+ composeSMask(this.ctx, this.current.activeSMask, groupCtx, this.webGLContext);
+ this.ctx.restore();
+ this.ctx.save();
+ copyCtxState(groupCtx, this.ctx);
+ this.current.resumeSMaskCtx = groupCtx;
+
+ var deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
+
+ this.ctx.transform.apply(this.ctx, deltaTransform);
+ groupCtx.save();
+ groupCtx.setTransform(1, 0, 0, 1, 0, 0);
+ groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
+ groupCtx.restore();
+ },
+ resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
+ var groupCtx = this.current.resumeSMaskCtx;
+ var currentCtx = this.ctx;
+ this.ctx = groupCtx;
+ this.groupStack.push(currentCtx);
+ this.groupLevel++;
+ },
+ endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
+ var groupCtx = this.ctx;
+ this.groupLevel--;
+ this.ctx = this.groupStack.pop();
+ composeSMask(this.ctx, this.current.activeSMask, groupCtx, this.webGLContext);
+ this.ctx.restore();
+ copyCtxState(groupCtx, this.ctx);
+
+ var deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
+
+ this.ctx.transform.apply(this.ctx, deltaTransform);
+ },
+ save: function CanvasGraphics_save() {
+ this.ctx.save();
+ var old = this.current;
+ this.stateStack.push(old);
+ this.current = old.clone();
+ this.current.resumeSMaskCtx = null;
+ },
+ restore: function CanvasGraphics_restore() {
+ if (this.current.resumeSMaskCtx) {
+ this.resumeSMaskGroup();
+ }
+
+ if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
+ this.endSMaskGroup();
+ }
+
+ if (this.stateStack.length !== 0) {
+ this.current = this.stateStack.pop();
+ this.ctx.restore();
+ this.pendingClip = null;
+ this._cachedGetSinglePixelWidth = null;
+ }
+ },
+ transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
+ this.ctx.transform(a, b, c, d, e, f);
+ this._cachedGetSinglePixelWidth = null;
+ },
+ constructPath: function CanvasGraphics_constructPath(ops, args) {
+ var ctx = this.ctx;
+ var current = this.current;
+ var x = current.x,
+ y = current.y;
+
+ for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
+ switch (ops[i] | 0) {
+ case _util.OPS.rectangle:
+ x = args[j++];
+ y = args[j++];
+ var width = args[j++];
+ var height = args[j++];
+
+ if (width === 0) {
+ width = this.getSinglePixelWidth();
+ }
+
+ if (height === 0) {
+ height = this.getSinglePixelWidth();
+ }
+
+ var xw = x + width;
+ var yh = y + height;
+ this.ctx.moveTo(x, y);
+ this.ctx.lineTo(xw, y);
+ this.ctx.lineTo(xw, yh);
+ this.ctx.lineTo(x, yh);
+ this.ctx.lineTo(x, y);
+ this.ctx.closePath();
+ break;
+
+ case _util.OPS.moveTo:
+ x = args[j++];
+ y = args[j++];
+ ctx.moveTo(x, y);
+ break;
+
+ case _util.OPS.lineTo:
+ x = args[j++];
+ y = args[j++];
+ ctx.lineTo(x, y);
+ break;
+
+ case _util.OPS.curveTo:
+ x = args[j + 4];
+ y = args[j + 5];
+ ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
+ j += 6;
+ break;
+
+ case _util.OPS.curveTo2:
+ ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
+ x = args[j + 2];
+ y = args[j + 3];
+ j += 4;
+ break;
+
+ case _util.OPS.curveTo3:
+ x = args[j + 2];
+ y = args[j + 3];
+ ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
+ j += 4;
+ break;
+
+ case _util.OPS.closePath:
+ ctx.closePath();
+ break;
+ }
+ }
+
+ current.setCurrentPoint(x, y);
+ },
+ closePath: function CanvasGraphics_closePath() {
+ this.ctx.closePath();
+ },
+ stroke: function CanvasGraphics_stroke(consumePath) {
+ consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
+ var ctx = this.ctx;
+ var strokeColor = this.current.strokeColor;
+ ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
+ ctx.globalAlpha = this.current.strokeAlpha;
+
+ if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
+ ctx.save();
+ ctx.strokeStyle = strokeColor.getPattern(ctx, this);
+ ctx.stroke();
+ ctx.restore();
+ } else {
+ ctx.stroke();
+ }
+
+ if (consumePath) {
+ this.consumePath();
+ }
+
+ ctx.globalAlpha = this.current.fillAlpha;
+ },
+ closeStroke: function CanvasGraphics_closeStroke() {
+ this.closePath();
+ this.stroke();
+ },
+ fill: function CanvasGraphics_fill(consumePath) {
+ consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
+ var ctx = this.ctx;
+ var fillColor = this.current.fillColor;
+ var isPatternFill = this.current.patternFill;
+ var needRestore = false;
+
+ if (isPatternFill) {
+ ctx.save();
+
+ if (this.baseTransform) {
+ ctx.setTransform.apply(ctx, this.baseTransform);
+ }
+
+ ctx.fillStyle = fillColor.getPattern(ctx, this);
+ needRestore = true;
+ }
+
+ if (this.pendingEOFill) {
+ ctx.fill('evenodd');
+ this.pendingEOFill = false;
+ } else {
+ ctx.fill();
+ }
+
+ if (needRestore) {
+ ctx.restore();
+ }
+
+ if (consumePath) {
+ this.consumePath();
+ }
+ },
+ eoFill: function CanvasGraphics_eoFill() {
+ this.pendingEOFill = true;
+ this.fill();
+ },
+ fillStroke: function CanvasGraphics_fillStroke() {
+ this.fill(false);
+ this.stroke(false);
+ this.consumePath();
+ },
+ eoFillStroke: function CanvasGraphics_eoFillStroke() {
+ this.pendingEOFill = true;
+ this.fillStroke();
+ },
+ closeFillStroke: function CanvasGraphics_closeFillStroke() {
+ this.closePath();
+ this.fillStroke();
+ },
+ closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
+ this.pendingEOFill = true;
+ this.closePath();
+ this.fillStroke();
+ },
+ endPath: function CanvasGraphics_endPath() {
+ this.consumePath();
+ },
+ clip: function CanvasGraphics_clip() {
+ this.pendingClip = NORMAL_CLIP;
+ },
+ eoClip: function CanvasGraphics_eoClip() {
+ this.pendingClip = EO_CLIP;
+ },
+ beginText: function CanvasGraphics_beginText() {
+ this.current.textMatrix = _util.IDENTITY_MATRIX;
+ this.current.textMatrixScale = 1;
+ this.current.x = this.current.lineX = 0;
+ this.current.y = this.current.lineY = 0;
+ },
+ endText: function CanvasGraphics_endText() {
+ var paths = this.pendingTextPaths;
+ var ctx = this.ctx;
+
+ if (paths === undefined) {
+ ctx.beginPath();
+ return;
+ }
+
+ ctx.save();
+ ctx.beginPath();
+
+ for (var i = 0; i < paths.length; i++) {
+ var path = paths[i];
+ ctx.setTransform.apply(ctx, path.transform);
+ ctx.translate(path.x, path.y);
+ path.addToPath(ctx, path.fontSize);
+ }
+
+ ctx.restore();
+ ctx.clip();
+ ctx.beginPath();
+ delete this.pendingTextPaths;
+ },
+ setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
+ this.current.charSpacing = spacing;
+ },
+ setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
+ this.current.wordSpacing = spacing;
+ },
+ setHScale: function CanvasGraphics_setHScale(scale) {
+ this.current.textHScale = scale / 100;
+ },
+ setLeading: function CanvasGraphics_setLeading(leading) {
+ this.current.leading = -leading;
+ },
+ setFont: function CanvasGraphics_setFont(fontRefName, size) {
+ var fontObj = this.commonObjs.get(fontRefName);
+ var current = this.current;
+
+ if (!fontObj) {
+ throw new Error("Can't find font for ".concat(fontRefName));
+ }
+
+ current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX;
+
+ if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
+ (0, _util.warn)('Invalid font matrix for font ' + fontRefName);
+ }
+
+ if (size < 0) {
+ size = -size;
+ current.fontDirection = -1;
+ } else {
+ current.fontDirection = 1;
+ }
+
+ this.current.font = fontObj;
+ this.current.fontSize = size;
+
+ if (fontObj.isType3Font) {
+ return;
+ }
+
+ var name = fontObj.loadedName || 'sans-serif';
+ var bold = fontObj.black ? '900' : fontObj.bold ? 'bold' : 'normal';
+ var italic = fontObj.italic ? 'italic' : 'normal';
+ var typeface = "\"".concat(name, "\", ").concat(fontObj.fallbackName);
+ var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
+ this.current.fontSizeScale = size / browserFontSize;
+ this.ctx.font = "".concat(italic, " ").concat(bold, " ").concat(browserFontSize, "px ").concat(typeface);
+ },
+ setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
+ this.current.textRenderingMode = mode;
+ },
+ setTextRise: function CanvasGraphics_setTextRise(rise) {
+ this.current.textRise = rise;
+ },
+ moveText: function CanvasGraphics_moveText(x, y) {
+ this.current.x = this.current.lineX += x;
+ this.current.y = this.current.lineY += y;
+ },
+ setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
+ this.setLeading(-y);
+ this.moveText(x, y);
+ },
+ setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
+ this.current.textMatrix = [a, b, c, d, e, f];
+ this.current.textMatrixScale = Math.sqrt(a * a + b * b);
+ this.current.x = this.current.lineX = 0;
+ this.current.y = this.current.lineY = 0;
+ },
+ nextLine: function CanvasGraphics_nextLine() {
+ this.moveText(0, this.current.leading);
+ },
+ paintChar: function paintChar(character, x, y, patternTransform) {
+ var ctx = this.ctx;
+ var current = this.current;
+ var font = current.font;
+ var textRenderingMode = current.textRenderingMode;
+ var fontSize = current.fontSize / current.fontSizeScale;
+ var fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
+ var isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
+ var patternFill = current.patternFill && font.data;
+ var addToPath;
+
+ if (font.disableFontFace || isAddToPathSet || patternFill) {
+ addToPath = font.getPathGenerator(this.commonObjs, character);
+ }
+
+ if (font.disableFontFace || patternFill) {
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.beginPath();
+ addToPath(ctx, fontSize);
+
+ if (patternTransform) {
+ ctx.setTransform.apply(ctx, patternTransform);
+ }
+
+ if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ ctx.fill();
+ }
+
+ if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ ctx.stroke();
+ }
+
+ ctx.restore();
+ } else {
+ if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ ctx.fillText(character, x, y);
+ }
+
+ if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ ctx.strokeText(character, x, y);
+ }
+ }
+
+ if (isAddToPathSet) {
+ var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
+ paths.push({
+ transform: ctx.mozCurrentTransform,
+ x: x,
+ y: y,
+ fontSize: fontSize,
+ addToPath: addToPath
+ });
+ }
+ },
+
+ get isFontSubpixelAAEnabled() {
+ var _this$cachedCanvases$ = this.cachedCanvases.getCanvas('isFontSubpixelAAEnabled', 10, 10),
+ ctx = _this$cachedCanvases$.context;
+
+ ctx.scale(1.5, 1);
+ ctx.fillText('I', 0, 10);
+ var data = ctx.getImageData(0, 0, 10, 10).data;
+ var enabled = false;
+
+ for (var i = 3; i < data.length; i += 4) {
+ if (data[i] > 0 && data[i] < 255) {
+ enabled = true;
+ break;
+ }
+ }
+
+ return (0, _util.shadow)(this, 'isFontSubpixelAAEnabled', enabled);
+ },
+
+ showText: function CanvasGraphics_showText(glyphs) {
+ var current = this.current;
+ var font = current.font;
+
+ if (font.isType3Font) {
+ return this.showType3Text(glyphs);
+ }
+
+ var fontSize = current.fontSize;
+
+ if (fontSize === 0) {
+ return undefined;
+ }
+
+ var ctx = this.ctx;
+ var fontSizeScale = current.fontSizeScale;
+ var charSpacing = current.charSpacing;
+ var wordSpacing = current.wordSpacing;
+ var fontDirection = current.fontDirection;
+ var textHScale = current.textHScale * fontDirection;
+ var glyphsLength = glyphs.length;
+ var vertical = font.vertical;
+ var spacingDir = vertical ? 1 : -1;
+ var defaultVMetrics = font.defaultVMetrics;
+ var widthAdvanceScale = fontSize * current.fontMatrix[0];
+ var simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
+ ctx.save();
+ var patternTransform;
+
+ if (current.patternFill) {
+ ctx.save();
+ var pattern = current.fillColor.getPattern(ctx, this);
+ patternTransform = ctx.mozCurrentTransform;
+ ctx.restore();
+ ctx.fillStyle = pattern;
+ }
+
+ ctx.transform.apply(ctx, current.textMatrix);
+ ctx.translate(current.x, current.y + current.textRise);
+
+ if (fontDirection > 0) {
+ ctx.scale(textHScale, -1);
+ } else {
+ ctx.scale(textHScale, 1);
+ }
+
+ var lineWidth = current.lineWidth;
+ var scale = current.textMatrixScale;
+
+ if (scale === 0 || lineWidth === 0) {
+ var fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
+
+ if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ this._cachedGetSinglePixelWidth = null;
+ lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
+ }
+ } else {
+ lineWidth /= scale;
+ }
+
+ if (fontSizeScale !== 1.0) {
+ ctx.scale(fontSizeScale, fontSizeScale);
+ lineWidth /= fontSizeScale;
+ }
+
+ ctx.lineWidth = lineWidth;
+ var x = 0,
+ i;
+
+ for (i = 0; i < glyphsLength; ++i) {
+ var glyph = glyphs[i];
+
+ if ((0, _util.isNum)(glyph)) {
+ x += spacingDir * glyph * fontSize / 1000;
+ continue;
+ }
+
+ var restoreNeeded = false;
+ var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
+ var character = glyph.fontChar;
+ var accent = glyph.accent;
+ var scaledX, scaledY, scaledAccentX, scaledAccentY;
+ var width = glyph.width;
+
+ if (vertical) {
+ var vmetric, vx, vy;
+ vmetric = glyph.vmetric || defaultVMetrics;
+ vx = glyph.vmetric ? vmetric[1] : width * 0.5;
+ vx = -vx * widthAdvanceScale;
+ vy = vmetric[2] * widthAdvanceScale;
+ width = vmetric ? -vmetric[0] : width;
+ scaledX = vx / fontSizeScale;
+ scaledY = (x + vy) / fontSizeScale;
+ } else {
+ scaledX = x / fontSizeScale;
+ scaledY = 0;
+ }
+
+ if (font.remeasure && width > 0) {
+ var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
+
+ if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
+ var characterScaleX = width / measuredWidth;
+ restoreNeeded = true;
+ ctx.save();
+ ctx.scale(characterScaleX, 1);
+ scaledX /= characterScaleX;
+ } else if (width !== measuredWidth) {
+ scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
+ }
+ }
+
+ if (glyph.isInFont || font.missingFile) {
+ if (simpleFillText && !accent) {
+ ctx.fillText(character, scaledX, scaledY);
+ } else {
+ this.paintChar(character, scaledX, scaledY, patternTransform);
+
+ if (accent) {
+ scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
+ scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
+ this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
+ }
+ }
+ }
+
+ var charWidth = width * widthAdvanceScale + spacing * fontDirection;
+ x += charWidth;
+
+ if (restoreNeeded) {
+ ctx.restore();
+ }
+ }
+
+ if (vertical) {
+ current.y -= x * textHScale;
+ } else {
+ current.x += x * textHScale;
+ }
+
+ ctx.restore();
+ },
+ showType3Text: function CanvasGraphics_showType3Text(glyphs) {
+ var ctx = this.ctx;
+ var current = this.current;
+ var font = current.font;
+ var fontSize = current.fontSize;
+ var fontDirection = current.fontDirection;
+ var spacingDir = font.vertical ? 1 : -1;
+ var charSpacing = current.charSpacing;
+ var wordSpacing = current.wordSpacing;
+ var textHScale = current.textHScale * fontDirection;
+ var fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
+ var glyphsLength = glyphs.length;
+ var isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
+ var i, glyph, width, spacingLength;
+
+ if (isTextInvisible || fontSize === 0) {
+ return;
+ }
+
+ this._cachedGetSinglePixelWidth = null;
+ ctx.save();
+ ctx.transform.apply(ctx, current.textMatrix);
+ ctx.translate(current.x, current.y);
+ ctx.scale(textHScale, fontDirection);
+
+ for (i = 0; i < glyphsLength; ++i) {
+ glyph = glyphs[i];
+
+ if ((0, _util.isNum)(glyph)) {
+ spacingLength = spacingDir * glyph * fontSize / 1000;
+ this.ctx.translate(spacingLength, 0);
+ current.x += spacingLength * textHScale;
+ continue;
+ }
+
+ var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
+ var operatorList = font.charProcOperatorList[glyph.operatorListId];
+
+ if (!operatorList) {
+ (0, _util.warn)("Type3 character \"".concat(glyph.operatorListId, "\" is not available."));
+ continue;
+ }
+
+ this.processingType3 = glyph;
+ this.save();
+ ctx.scale(fontSize, fontSize);
+ ctx.transform.apply(ctx, fontMatrix);
+ this.executeOperatorList(operatorList);
+ this.restore();
+
+ var transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
+
+ width = transformed[0] * fontSize + spacing;
+ ctx.translate(width, 0);
+ current.x += width * textHScale;
+ }
+
+ ctx.restore();
+ this.processingType3 = null;
+ },
+ setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {},
+ setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
+ this.ctx.rect(llx, lly, urx - llx, ury - lly);
+ this.clip();
+ this.endPath();
+ },
+ getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
+ var _this = this;
+
+ var pattern;
+
+ if (IR[0] === 'TilingPattern') {
+ var color = IR[1];
+ var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
+ var canvasGraphicsFactory = {
+ createCanvasGraphics: function createCanvasGraphics(ctx) {
+ return new CanvasGraphics(ctx, _this.commonObjs, _this.objs, _this.canvasFactory, _this.webGLContext);
+ }
+ };
+ pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
+ } else {
+ pattern = (0, _pattern_helper.getShadingPatternFromIR)(IR);
+ }
+
+ return pattern;
+ },
+ setStrokeColorN: function CanvasGraphics_setStrokeColorN() {
+ this.current.strokeColor = this.getColorN_Pattern(arguments);
+ },
+ setFillColorN: function CanvasGraphics_setFillColorN() {
+ this.current.fillColor = this.getColorN_Pattern(arguments);
+ this.current.patternFill = true;
+ },
+ setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
+ var color = _util.Util.makeCssRgb(r, g, b);
+
+ this.ctx.strokeStyle = color;
+ this.current.strokeColor = color;
+ },
+ setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
+ var color = _util.Util.makeCssRgb(r, g, b);
+
+ this.ctx.fillStyle = color;
+ this.current.fillColor = color;
+ this.current.patternFill = false;
+ },
+ shadingFill: function CanvasGraphics_shadingFill(patternIR) {
+ var ctx = this.ctx;
+ this.save();
+ var pattern = (0, _pattern_helper.getShadingPatternFromIR)(patternIR);
+ ctx.fillStyle = pattern.getPattern(ctx, this, true);
+ var inv = ctx.mozCurrentTransformInverse;
+
+ if (inv) {
+ var canvas = ctx.canvas;
+ var width = canvas.width;
+ var height = canvas.height;
+
+ var bl = _util.Util.applyTransform([0, 0], inv);
+
+ var br = _util.Util.applyTransform([0, height], inv);
+
+ var ul = _util.Util.applyTransform([width, 0], inv);
+
+ var ur = _util.Util.applyTransform([width, height], inv);
+
+ var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
+ var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
+ var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
+ var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
+ this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
+ } else {
+ this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
+ }
+
+ this.restore();
+ },
+ beginInlineImage: function CanvasGraphics_beginInlineImage() {
+ (0, _util.unreachable)('Should not call beginInlineImage');
+ },
+ beginImageData: function CanvasGraphics_beginImageData() {
+ (0, _util.unreachable)('Should not call beginImageData');
+ },
+ paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
+ this.save();
+ this.baseTransformStack.push(this.baseTransform);
+
+ if (Array.isArray(matrix) && matrix.length === 6) {
+ this.transform.apply(this, matrix);
+ }
+
+ this.baseTransform = this.ctx.mozCurrentTransform;
+
+ if (bbox) {
+ var width = bbox[2] - bbox[0];
+ var height = bbox[3] - bbox[1];
+ this.ctx.rect(bbox[0], bbox[1], width, height);
+ this.clip();
+ this.endPath();
+ }
+ },
+ paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
+ this.restore();
+ this.baseTransform = this.baseTransformStack.pop();
+ },
+ beginGroup: function CanvasGraphics_beginGroup(group) {
+ this.save();
+ var currentCtx = this.ctx;
+
+ if (!group.isolated) {
+ (0, _util.info)('TODO: Support non-isolated groups.');
+ }
+
+ if (group.knockout) {
+ (0, _util.warn)('Knockout groups not supported.');
+ }
+
+ var currentTransform = currentCtx.mozCurrentTransform;
+
+ if (group.matrix) {
+ currentCtx.transform.apply(currentCtx, group.matrix);
+ }
+
+ if (!group.bbox) {
+ throw new Error('Bounding box is required.');
+ }
+
+ var bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
+
+ var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
+ bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
+ var offsetX = Math.floor(bounds[0]);
+ var offsetY = Math.floor(bounds[1]);
+ var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
+ var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
+ var scaleX = 1,
+ scaleY = 1;
+
+ if (drawnWidth > MAX_GROUP_SIZE) {
+ scaleX = drawnWidth / MAX_GROUP_SIZE;
+ drawnWidth = MAX_GROUP_SIZE;
+ }
+
+ if (drawnHeight > MAX_GROUP_SIZE) {
+ scaleY = drawnHeight / MAX_GROUP_SIZE;
+ drawnHeight = MAX_GROUP_SIZE;
+ }
+
+ var cacheId = 'groupAt' + this.groupLevel;
+
+ if (group.smask) {
+ cacheId += '_smask_' + this.smaskCounter++ % 2;
+ }
+
+ var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
+ var groupCtx = scratchCanvas.context;
+ groupCtx.scale(1 / scaleX, 1 / scaleY);
+ groupCtx.translate(-offsetX, -offsetY);
+ groupCtx.transform.apply(groupCtx, currentTransform);
+
+ if (group.smask) {
+ this.smaskStack.push({
+ canvas: scratchCanvas.canvas,
+ context: groupCtx,
+ offsetX: offsetX,
+ offsetY: offsetY,
+ scaleX: scaleX,
+ scaleY: scaleY,
+ subtype: group.smask.subtype,
+ backdrop: group.smask.backdrop,
+ transferMap: group.smask.transferMap || null,
+ startTransformInverse: null
+ });
+ } else {
+ currentCtx.setTransform(1, 0, 0, 1, 0, 0);
+ currentCtx.translate(offsetX, offsetY);
+ currentCtx.scale(scaleX, scaleY);
+ }
+
+ copyCtxState(currentCtx, groupCtx);
+ this.ctx = groupCtx;
+ this.setGState([['BM', 'source-over'], ['ca', 1], ['CA', 1]]);
+ this.groupStack.push(currentCtx);
+ this.groupLevel++;
+ this.current.activeSMask = null;
+ },
+ endGroup: function CanvasGraphics_endGroup(group) {
+ this.groupLevel--;
+ var groupCtx = this.ctx;
+ this.ctx = this.groupStack.pop();
+
+ if (this.ctx.imageSmoothingEnabled !== undefined) {
+ this.ctx.imageSmoothingEnabled = false;
+ } else {
+ this.ctx.mozImageSmoothingEnabled = false;
+ }
+
+ if (group.smask) {
+ this.tempSMask = this.smaskStack.pop();
+ } else {
+ this.ctx.drawImage(groupCtx.canvas, 0, 0);
+ }
+
+ this.restore();
+ },
+ beginAnnotations: function CanvasGraphics_beginAnnotations() {
+ this.save();
+
+ if (this.baseTransform) {
+ this.ctx.setTransform.apply(this.ctx, this.baseTransform);
+ }
+ },
+ endAnnotations: function CanvasGraphics_endAnnotations() {
+ this.restore();
+ },
+ beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
+ this.save();
+ resetCtxToDefault(this.ctx);
+ this.current = new CanvasExtraState();
+
+ if (Array.isArray(rect) && rect.length === 4) {
+ var width = rect[2] - rect[0];
+ var height = rect[3] - rect[1];
+ this.ctx.rect(rect[0], rect[1], width, height);
+ this.clip();
+ this.endPath();
+ }
+
+ this.transform.apply(this, transform);
+ this.transform.apply(this, matrix);
+ },
+ endAnnotation: function CanvasGraphics_endAnnotation() {
+ this.restore();
+ },
+ paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
+ var domImage = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
+
+ if (!domImage) {
+ (0, _util.warn)('Dependent image isn\'t ready yet');
+ return;
+ }
+
+ this.save();
+ var ctx = this.ctx;
+ ctx.scale(1 / w, -1 / h);
+ ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
+
+ if (this.imageLayer) {
+ var currentTransform = ctx.mozCurrentTransformInverse;
+ var position = this.getCanvasPosition(0, 0);
+ this.imageLayer.appendImage({
+ objId: objId,
+ left: position[0],
+ top: position[1],
+ width: w / currentTransform[0],
+ height: h / currentTransform[3]
+ });
+ }
+
+ this.restore();
+ },
+ paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
+ var ctx = this.ctx;
+ var width = img.width,
+ height = img.height;
+ var fillColor = this.current.fillColor;
+ var isPatternFill = this.current.patternFill;
+ var glyph = this.processingType3;
+
+ if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
+ if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
+ glyph.compiled = compileType3Glyph({
+ data: img.data,
+ width: width,
+ height: height
+ });
+ } else {
+ glyph.compiled = null;
+ }
+ }
+
+ if (glyph && glyph.compiled) {
+ glyph.compiled(ctx);
+ return;
+ }
+
+ var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
+ var maskCtx = maskCanvas.context;
+ maskCtx.save();
+ putBinaryImageMask(maskCtx, img);
+ maskCtx.globalCompositeOperation = 'source-in';
+ maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
+ maskCtx.fillRect(0, 0, width, height);
+ maskCtx.restore();
+ this.paintInlineImageXObject(maskCanvas.canvas);
+ },
+ paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
+ var width = imgData.width;
+ var height = imgData.height;
+ var fillColor = this.current.fillColor;
+ var isPatternFill = this.current.patternFill;
+ var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
+ var maskCtx = maskCanvas.context;
+ maskCtx.save();
+ putBinaryImageMask(maskCtx, imgData);
+ maskCtx.globalCompositeOperation = 'source-in';
+ maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
+ maskCtx.fillRect(0, 0, width, height);
+ maskCtx.restore();
+ var ctx = this.ctx;
+
+ for (var i = 0, ii = positions.length; i < ii; i += 2) {
+ ctx.save();
+ ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
+ ctx.scale(1, -1);
+ ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
+ ctx.restore();
+ }
+ },
+ paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
+ var ctx = this.ctx;
+ var fillColor = this.current.fillColor;
+ var isPatternFill = this.current.patternFill;
+
+ for (var i = 0, ii = images.length; i < ii; i++) {
+ var image = images[i];
+ var width = image.width,
+ height = image.height;
+ var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
+ var maskCtx = maskCanvas.context;
+ maskCtx.save();
+ putBinaryImageMask(maskCtx, image);
+ maskCtx.globalCompositeOperation = 'source-in';
+ maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
+ maskCtx.fillRect(0, 0, width, height);
+ maskCtx.restore();
+ ctx.save();
+ ctx.transform.apply(ctx, image.transform);
+ ctx.scale(1, -1);
+ ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
+ ctx.restore();
+ }
+ },
+ paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
+ var imgData = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
+
+ if (!imgData) {
+ (0, _util.warn)('Dependent image isn\'t ready yet');
+ return;
+ }
+
+ this.paintInlineImageXObject(imgData);
+ },
+ paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
+ var imgData = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
+
+ if (!imgData) {
+ (0, _util.warn)('Dependent image isn\'t ready yet');
+ return;
+ }
+
+ var width = imgData.width;
+ var height = imgData.height;
+ var map = [];
+
+ for (var i = 0, ii = positions.length; i < ii; i += 2) {
+ map.push({
+ transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
+ x: 0,
+ y: 0,
+ w: width,
+ h: height
+ });
+ }
+
+ this.paintInlineImageXObjectGroup(imgData, map);
+ },
+ paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
+ var width = imgData.width;
+ var height = imgData.height;
+ var ctx = this.ctx;
+ this.save();
+ ctx.scale(1 / width, -1 / height);
+ var currentTransform = ctx.mozCurrentTransformInverse;
+ var a = currentTransform[0],
+ b = currentTransform[1];
+ var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
+ var c = currentTransform[2],
+ d = currentTransform[3];
+ var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
+ var imgToPaint, tmpCanvas;
+
+ if (typeof HTMLElement === 'function' && imgData instanceof HTMLElement || !imgData.data) {
+ imgToPaint = imgData;
+ } else {
+ tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
+ var tmpCtx = tmpCanvas.context;
+ putBinaryImageData(tmpCtx, imgData);
+ imgToPaint = tmpCanvas.canvas;
+ }
+
+ var paintWidth = width,
+ paintHeight = height;
+ var tmpCanvasId = 'prescale1';
+
+ while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
+ var newWidth = paintWidth,
+ newHeight = paintHeight;
+
+ if (widthScale > 2 && paintWidth > 1) {
+ newWidth = Math.ceil(paintWidth / 2);
+ widthScale /= paintWidth / newWidth;
+ }
+
+ if (heightScale > 2 && paintHeight > 1) {
+ newHeight = Math.ceil(paintHeight / 2);
+ heightScale /= paintHeight / newHeight;
+ }
+
+ tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
+ tmpCtx = tmpCanvas.context;
+ tmpCtx.clearRect(0, 0, newWidth, newHeight);
+ tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
+ imgToPaint = tmpCanvas.canvas;
+ paintWidth = newWidth;
+ paintHeight = newHeight;
+ tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
+ }
+
+ ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
+
+ if (this.imageLayer) {
+ var position = this.getCanvasPosition(0, -height);
+ this.imageLayer.appendImage({
+ imgData: imgData,
+ left: position[0],
+ top: position[1],
+ width: width / currentTransform[0],
+ height: height / currentTransform[3]
+ });
+ }
+
+ this.restore();
+ },
+ paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
+ var ctx = this.ctx;
+ var w = imgData.width;
+ var h = imgData.height;
+ var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
+ var tmpCtx = tmpCanvas.context;
+ putBinaryImageData(tmpCtx, imgData);
+
+ for (var i = 0, ii = map.length; i < ii; i++) {
+ var entry = map[i];
+ ctx.save();
+ ctx.transform.apply(ctx, entry.transform);
+ ctx.scale(1, -1);
+ ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
+
+ if (this.imageLayer) {
+ var position = this.getCanvasPosition(entry.x, entry.y);
+ this.imageLayer.appendImage({
+ imgData: imgData,
+ left: position[0],
+ top: position[1],
+ width: w,
+ height: h
+ });
+ }
+
+ ctx.restore();
+ }
+ },
+ paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
+ this.ctx.fillRect(0, 0, 1, 1);
+ },
+ paintXObject: function CanvasGraphics_paintXObject() {
+ (0, _util.warn)('Unsupported \'paintXObject\' command.');
+ },
+ markPoint: function CanvasGraphics_markPoint(tag) {},
+ markPointProps: function CanvasGraphics_markPointProps(tag, properties) {},
+ beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {},
+ beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {},
+ endMarkedContent: function CanvasGraphics_endMarkedContent() {},
+ beginCompat: function CanvasGraphics_beginCompat() {},
+ endCompat: function CanvasGraphics_endCompat() {},
+ consumePath: function CanvasGraphics_consumePath() {
+ var ctx = this.ctx;
+
+ if (this.pendingClip) {
+ if (this.pendingClip === EO_CLIP) {
+ ctx.clip('evenodd');
+ } else {
+ ctx.clip();
+ }
+
+ this.pendingClip = null;
+ }
+
+ ctx.beginPath();
+ },
+ getSinglePixelWidth: function getSinglePixelWidth(scale) {
+ if (this._cachedGetSinglePixelWidth === null) {
+ var inverse = this.ctx.mozCurrentTransformInverse;
+ this._cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
+ }
+
+ return this._cachedGetSinglePixelWidth;
+ },
+ getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
+ var transform = this.ctx.mozCurrentTransform;
+ return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
+ }
+ };
+
+ for (var op in _util.OPS) {
+ CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
+ }
+
+ return CanvasGraphics;
+}();
+
+exports.CanvasGraphics = CanvasGraphics;
+
+/***/ }),
+/* 155 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.getShadingPatternFromIR = getShadingPatternFromIR;
+exports.TilingPattern = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+var ShadingIRs = {};
+ShadingIRs.RadialAxial = {
+ fromIR: function RadialAxial_fromIR(raw) {
+ var type = raw[1];
+ var colorStops = raw[2];
+ var p0 = raw[3];
+ var p1 = raw[4];
+ var r0 = raw[5];
+ var r1 = raw[6];
+ return {
+ type: 'Pattern',
+ getPattern: function RadialAxial_getPattern(ctx) {
+ var grad;
+
+ if (type === 'axial') {
+ grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
+ } else if (type === 'radial') {
+ grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
+ }
+
+ for (var i = 0, ii = colorStops.length; i < ii; ++i) {
+ var c = colorStops[i];
+ grad.addColorStop(c[0], c[1]);
+ }
+
+ return grad;
+ }
+ };
+ }
+};
+
+var createMeshCanvas = function createMeshCanvasClosure() {
+ function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
+ var coords = context.coords,
+ colors = context.colors;
+ var bytes = data.data,
+ rowSize = data.width * 4;
+ var tmp;
+
+ if (coords[p1 + 1] > coords[p2 + 1]) {
+ tmp = p1;
+ p1 = p2;
+ p2 = tmp;
+ tmp = c1;
+ c1 = c2;
+ c2 = tmp;
+ }
+
+ if (coords[p2 + 1] > coords[p3 + 1]) {
+ tmp = p2;
+ p2 = p3;
+ p3 = tmp;
+ tmp = c2;
+ c2 = c3;
+ c3 = tmp;
+ }
+
+ if (coords[p1 + 1] > coords[p2 + 1]) {
+ tmp = p1;
+ p1 = p2;
+ p2 = tmp;
+ tmp = c1;
+ c1 = c2;
+ c2 = tmp;
+ }
+
+ var x1 = (coords[p1] + context.offsetX) * context.scaleX;
+ var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
+ var x2 = (coords[p2] + context.offsetX) * context.scaleX;
+ var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
+ var x3 = (coords[p3] + context.offsetX) * context.scaleX;
+ var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
+
+ if (y1 >= y3) {
+ return;
+ }
+
+ var c1r = colors[c1],
+ c1g = colors[c1 + 1],
+ c1b = colors[c1 + 2];
+ var c2r = colors[c2],
+ c2g = colors[c2 + 1],
+ c2b = colors[c2 + 2];
+ var c3r = colors[c3],
+ c3g = colors[c3 + 1],
+ c3b = colors[c3 + 2];
+ var minY = Math.round(y1),
+ maxY = Math.round(y3);
+ var xa, car, cag, cab;
+ var xb, cbr, cbg, cbb;
+ var k;
+
+ for (var y = minY; y <= maxY; y++) {
+ if (y < y2) {
+ k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
+ xa = x1 - (x1 - x2) * k;
+ car = c1r - (c1r - c2r) * k;
+ cag = c1g - (c1g - c2g) * k;
+ cab = c1b - (c1b - c2b) * k;
+ } else {
+ k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
+ xa = x2 - (x2 - x3) * k;
+ car = c2r - (c2r - c3r) * k;
+ cag = c2g - (c2g - c3g) * k;
+ cab = c2b - (c2b - c3b) * k;
+ }
+
+ k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
+ xb = x1 - (x1 - x3) * k;
+ cbr = c1r - (c1r - c3r) * k;
+ cbg = c1g - (c1g - c3g) * k;
+ cbb = c1b - (c1b - c3b) * k;
+ var x1_ = Math.round(Math.min(xa, xb));
+ var x2_ = Math.round(Math.max(xa, xb));
+ var j = rowSize * y + x1_ * 4;
+
+ for (var x = x1_; x <= x2_; x++) {
+ k = (xa - x) / (xa - xb);
+ k = k < 0 ? 0 : k > 1 ? 1 : k;
+ bytes[j++] = car - (car - cbr) * k | 0;
+ bytes[j++] = cag - (cag - cbg) * k | 0;
+ bytes[j++] = cab - (cab - cbb) * k | 0;
+ bytes[j++] = 255;
+ }
+ }
+ }
+
+ function drawFigure(data, figure, context) {
+ var ps = figure.coords;
+ var cs = figure.colors;
+ var i, ii;
+
+ switch (figure.type) {
+ case 'lattice':
+ var verticesPerRow = figure.verticesPerRow;
+ var rows = Math.floor(ps.length / verticesPerRow) - 1;
+ var cols = verticesPerRow - 1;
+
+ for (i = 0; i < rows; i++) {
+ var q = i * verticesPerRow;
+
+ for (var j = 0; j < cols; j++, q++) {
+ drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
+ drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
+ }
+ }
+
+ break;
+
+ case 'triangles':
+ for (i = 0, ii = ps.length; i < ii; i += 3) {
+ drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
+ }
+
+ break;
+
+ default:
+ throw new Error('illegal figure');
+ }
+ }
+
+ function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases, webGLContext) {
+ var EXPECTED_SCALE = 1.1;
+ var MAX_PATTERN_SIZE = 3000;
+ var BORDER_SIZE = 2;
+ var offsetX = Math.floor(bounds[0]);
+ var offsetY = Math.floor(bounds[1]);
+ var boundsWidth = Math.ceil(bounds[2]) - offsetX;
+ var boundsHeight = Math.ceil(bounds[3]) - offsetY;
+ var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
+ var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
+ var scaleX = boundsWidth / width;
+ var scaleY = boundsHeight / height;
+ var context = {
+ coords: coords,
+ colors: colors,
+ offsetX: -offsetX,
+ offsetY: -offsetY,
+ scaleX: 1 / scaleX,
+ scaleY: 1 / scaleY
+ };
+ var paddedWidth = width + BORDER_SIZE * 2;
+ var paddedHeight = height + BORDER_SIZE * 2;
+ var canvas, tmpCanvas, i, ii;
+
+ if (webGLContext.isEnabled) {
+ canvas = webGLContext.drawFigures({
+ width: width,
+ height: height,
+ backgroundColor: backgroundColor,
+ figures: figures,
+ context: context
+ });
+ tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
+ tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
+ canvas = tmpCanvas.canvas;
+ } else {
+ tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
+ var tmpCtx = tmpCanvas.context;
+ var data = tmpCtx.createImageData(width, height);
+
+ if (backgroundColor) {
+ var bytes = data.data;
+
+ for (i = 0, ii = bytes.length; i < ii; i += 4) {
+ bytes[i] = backgroundColor[0];
+ bytes[i + 1] = backgroundColor[1];
+ bytes[i + 2] = backgroundColor[2];
+ bytes[i + 3] = 255;
+ }
+ }
+
+ for (i = 0; i < figures.length; i++) {
+ drawFigure(data, figures[i], context);
+ }
+
+ tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
+ canvas = tmpCanvas.canvas;
+ }
+
+ return {
+ canvas: canvas,
+ offsetX: offsetX - BORDER_SIZE * scaleX,
+ offsetY: offsetY - BORDER_SIZE * scaleY,
+ scaleX: scaleX,
+ scaleY: scaleY
+ };
+ }
+
+ return createMeshCanvas;
+}();
+
+ShadingIRs.Mesh = {
+ fromIR: function Mesh_fromIR(raw) {
+ var coords = raw[2];
+ var colors = raw[3];
+ var figures = raw[4];
+ var bounds = raw[5];
+ var matrix = raw[6];
+ var background = raw[8];
+ return {
+ type: 'Pattern',
+ getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
+ var scale;
+
+ if (shadingFill) {
+ scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
+ } else {
+ scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
+
+ if (matrix) {
+ var matrixScale = _util.Util.singularValueDecompose2dScale(matrix);
+
+ scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
+ }
+ }
+
+ var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases, owner.webGLContext);
+
+ if (!shadingFill) {
+ ctx.setTransform.apply(ctx, owner.baseTransform);
+
+ if (matrix) {
+ ctx.transform.apply(ctx, matrix);
+ }
+ }
+
+ ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
+ ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
+ return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
+ }
+ };
+ }
+};
+ShadingIRs.Dummy = {
+ fromIR: function Dummy_fromIR() {
+ return {
+ type: 'Pattern',
+ getPattern: function Dummy_fromIR_getPattern() {
+ return 'hotpink';
+ }
+ };
+ }
+};
+
+function getShadingPatternFromIR(raw) {
+ var shadingIR = ShadingIRs[raw[0]];
+
+ if (!shadingIR) {
+ throw new Error("Unknown IR type: ".concat(raw[0]));
+ }
+
+ return shadingIR.fromIR(raw);
+}
+
+var TilingPattern = function TilingPatternClosure() {
+ var PaintType = {
+ COLORED: 1,
+ UNCOLORED: 2
+ };
+ var MAX_PATTERN_SIZE = 3000;
+
+ function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
+ this.operatorList = IR[2];
+ this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
+ this.bbox = IR[4];
+ this.xstep = IR[5];
+ this.ystep = IR[6];
+ this.paintType = IR[7];
+ this.tilingType = IR[8];
+ this.color = color;
+ this.canvasGraphicsFactory = canvasGraphicsFactory;
+ this.baseTransform = baseTransform;
+ this.type = 'Pattern';
+ this.ctx = ctx;
+ }
+
+ TilingPattern.prototype = {
+ createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
+ var operatorList = this.operatorList;
+ var bbox = this.bbox;
+ var xstep = this.xstep;
+ var ystep = this.ystep;
+ var paintType = this.paintType;
+ var tilingType = this.tilingType;
+ var color = this.color;
+ var canvasGraphicsFactory = this.canvasGraphicsFactory;
+ (0, _util.info)('TilingType: ' + tilingType);
+ var x0 = bbox[0],
+ y0 = bbox[1],
+ x1 = bbox[2],
+ y1 = bbox[3];
+
+ var matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
+
+ var curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
+
+ var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
+ var dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
+ var dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
+ var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', dimx.size, dimy.size, true);
+ var tmpCtx = tmpCanvas.context;
+ var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
+ graphics.groupLevel = owner.groupLevel;
+ this.setFillAndStrokeStyleToContext(graphics, paintType, color);
+ graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
+ graphics.transform(1, 0, 0, 1, -x0, -y0);
+ this.clipBbox(graphics, bbox, x0, y0, x1, y1);
+ graphics.executeOperatorList(operatorList);
+ this.ctx.transform(1, 0, 0, 1, x0, y0);
+ this.ctx.scale(1 / dimx.scale, 1 / dimy.scale);
+ return tmpCanvas.canvas;
+ },
+ getSizeAndScale: function TilingPattern_getSizeAndScale(step, realOutputSize, scale) {
+ step = Math.abs(step);
+ var maxSize = Math.max(MAX_PATTERN_SIZE, realOutputSize);
+ var size = Math.ceil(step * scale);
+
+ if (size >= maxSize) {
+ size = maxSize;
+ } else {
+ scale = size / step;
+ }
+
+ return {
+ scale: scale,
+ size: size
+ };
+ },
+ clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
+ if (Array.isArray(bbox) && bbox.length === 4) {
+ var bboxWidth = x1 - x0;
+ var bboxHeight = y1 - y0;
+ graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
+ graphics.clip();
+ graphics.endPath();
+ }
+ },
+ setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(graphics, paintType, color) {
+ var context = graphics.ctx,
+ current = graphics.current;
+
+ switch (paintType) {
+ case PaintType.COLORED:
+ var ctx = this.ctx;
+ context.fillStyle = ctx.fillStyle;
+ context.strokeStyle = ctx.strokeStyle;
+ current.fillColor = ctx.fillStyle;
+ current.strokeColor = ctx.strokeStyle;
+ break;
+
+ case PaintType.UNCOLORED:
+ var cssColor = _util.Util.makeCssRgb(color[0], color[1], color[2]);
+
+ context.fillStyle = cssColor;
+ context.strokeStyle = cssColor;
+ current.fillColor = cssColor;
+ current.strokeColor = cssColor;
+ break;
+
+ default:
+ throw new _util.FormatError("Unsupported paint type: ".concat(paintType));
+ }
+ },
+ getPattern: function TilingPattern_getPattern(ctx, owner) {
+ ctx = this.ctx;
+ ctx.setTransform.apply(ctx, this.baseTransform);
+ ctx.transform.apply(ctx, this.matrix);
+ var temporaryPatternCanvas = this.createPatternCanvas(owner);
+ return ctx.createPattern(temporaryPatternCanvas, 'repeat');
+ }
+ };
+ return TilingPattern;
+}();
+
+exports.TilingPattern = TilingPattern;
+
+/***/ }),
+/* 156 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.GlobalWorkerOptions = void 0;
+var GlobalWorkerOptions = Object.create(null);
+exports.GlobalWorkerOptions = GlobalWorkerOptions;
+GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
+GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? '' : GlobalWorkerOptions.workerSrc;
+
+/***/ }),
+/* 157 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.MessageHandler = MessageHandler;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
+
+function _typeof(obj) { 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); }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function resolveCall(_x, _x2) {
+ return _resolveCall.apply(this, arguments);
+}
+
+function _resolveCall() {
+ _resolveCall = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee(fn, args) {
+ var thisArg,
+ _args = arguments;
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ thisArg = _args.length > 2 && _args[2] !== undefined ? _args[2] : null;
+
+ if (fn) {
+ _context.next = 3;
+ break;
+ }
+
+ return _context.abrupt("return", undefined);
+
+ case 3:
+ return _context.abrupt("return", fn.apply(thisArg, args));
+
+ case 4:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+ return _resolveCall.apply(this, arguments);
+}
+
+function wrapReason(reason) {
+ if (_typeof(reason) !== 'object') {
+ return reason;
+ }
+
+ switch (reason.name) {
+ case 'AbortException':
+ return new _util.AbortException(reason.message);
+
+ case 'MissingPDFException':
+ return new _util.MissingPDFException(reason.message);
+
+ case 'UnexpectedResponseException':
+ return new _util.UnexpectedResponseException(reason.message, reason.status);
+
+ default:
+ return new _util.UnknownErrorException(reason.message, reason.details);
+ }
+}
+
+function makeReasonSerializable(reason) {
+ if (!(reason instanceof Error) || reason instanceof _util.AbortException || reason instanceof _util.MissingPDFException || reason instanceof _util.UnexpectedResponseException || reason instanceof _util.UnknownErrorException) {
+ return reason;
+ }
+
+ return new _util.UnknownErrorException(reason.message, reason.toString());
+}
+
+function resolveOrReject(capability, success, reason) {
+ if (success) {
+ capability.resolve();
+ } else {
+ capability.reject(reason);
+ }
+}
+
+function finalize(promise) {
+ return Promise.resolve(promise)["catch"](function () {});
+}
+
+function MessageHandler(sourceName, targetName, comObj) {
+ var _this = this;
+
+ this.sourceName = sourceName;
+ this.targetName = targetName;
+ this.comObj = comObj;
+ this.callbackId = 1;
+ this.streamId = 1;
+ this.postMessageTransfers = true;
+ this.streamSinks = Object.create(null);
+ this.streamControllers = Object.create(null);
+ var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
+ var ah = this.actionHandler = Object.create(null);
+
+ this._onComObjOnMessage = function (event) {
+ var data = event.data;
+
+ if (data.targetName !== _this.sourceName) {
+ return;
+ }
+
+ if (data.stream) {
+ _this._processStreamMessage(data);
+ } else if (data.isReply) {
+ var callbackId = data.callbackId;
+
+ if (data.callbackId in callbacksCapabilities) {
+ var callback = callbacksCapabilities[callbackId];
+ delete callbacksCapabilities[callbackId];
+
+ if ('error' in data) {
+ callback.reject(wrapReason(data.error));
+ } else {
+ callback.resolve(data.data);
+ }
+ } else {
+ throw new Error("Cannot resolve callback ".concat(callbackId));
+ }
+ } else if (data.action in ah) {
+ var action = ah[data.action];
+
+ if (data.callbackId) {
+ var _sourceName = _this.sourceName;
+ var _targetName = data.sourceName;
+ Promise.resolve().then(function () {
+ return action[0].call(action[1], data.data);
+ }).then(function (result) {
+ comObj.postMessage({
+ sourceName: _sourceName,
+ targetName: _targetName,
+ isReply: true,
+ callbackId: data.callbackId,
+ data: result
+ });
+ }, function (reason) {
+ comObj.postMessage({
+ sourceName: _sourceName,
+ targetName: _targetName,
+ isReply: true,
+ callbackId: data.callbackId,
+ error: makeReasonSerializable(reason)
+ });
+ });
+ } else if (data.streamId) {
+ _this._createStreamSink(data);
+ } else {
+ action[0].call(action[1], data.data);
+ }
+ } else {
+ throw new Error("Unknown action from worker: ".concat(data.action));
+ }
+ };
+
+ comObj.addEventListener('message', this._onComObjOnMessage);
+}
+
+MessageHandler.prototype = {
+ on: function on(actionName, handler, scope) {
+ var ah = this.actionHandler;
+
+ if (ah[actionName]) {
+ throw new Error("There is already an actionName called \"".concat(actionName, "\""));
+ }
+
+ ah[actionName] = [handler, scope];
+ },
+ send: function send(actionName, data, transfers) {
+ var message = {
+ sourceName: this.sourceName,
+ targetName: this.targetName,
+ action: actionName,
+ data: data
+ };
+ this.postMessage(message, transfers);
+ },
+ sendWithPromise: function sendWithPromise(actionName, data, transfers) {
+ var callbackId = this.callbackId++;
+ var message = {
+ sourceName: this.sourceName,
+ targetName: this.targetName,
+ action: actionName,
+ data: data,
+ callbackId: callbackId
+ };
+ var capability = (0, _util.createPromiseCapability)();
+ this.callbacksCapabilities[callbackId] = capability;
+
+ try {
+ this.postMessage(message, transfers);
+ } catch (e) {
+ capability.reject(e);
+ }
+
+ return capability.promise;
+ },
+ sendWithStream: function sendWithStream(actionName, data, queueingStrategy, transfers) {
+ var _this2 = this;
+
+ var streamId = this.streamId++;
+ var sourceName = this.sourceName;
+ var targetName = this.targetName;
+ return new _util.ReadableStream({
+ start: function start(controller) {
+ var startCapability = (0, _util.createPromiseCapability)();
+ _this2.streamControllers[streamId] = {
+ controller: controller,
+ startCall: startCapability,
+ isClosed: false
+ };
+
+ _this2.postMessage({
+ sourceName: sourceName,
+ targetName: targetName,
+ action: actionName,
+ streamId: streamId,
+ data: data,
+ desiredSize: controller.desiredSize
+ });
+
+ return startCapability.promise;
+ },
+ pull: function pull(controller) {
+ var pullCapability = (0, _util.createPromiseCapability)();
+ _this2.streamControllers[streamId].pullCall = pullCapability;
+
+ _this2.postMessage({
+ sourceName: sourceName,
+ targetName: targetName,
+ stream: 'pull',
+ streamId: streamId,
+ desiredSize: controller.desiredSize
+ });
+
+ return pullCapability.promise;
+ },
+ cancel: function cancel(reason) {
+ var cancelCapability = (0, _util.createPromiseCapability)();
+ _this2.streamControllers[streamId].cancelCall = cancelCapability;
+ _this2.streamControllers[streamId].isClosed = true;
+
+ _this2.postMessage({
+ sourceName: sourceName,
+ targetName: targetName,
+ stream: 'cancel',
+ reason: reason,
+ streamId: streamId
+ });
+
+ return cancelCapability.promise;
+ }
+ }, queueingStrategy);
+ },
+ _createStreamSink: function _createStreamSink(data) {
+ var _this3 = this;
+
+ var self = this;
+ var action = this.actionHandler[data.action];
+ var streamId = data.streamId;
+ var desiredSize = data.desiredSize;
+ var sourceName = this.sourceName;
+ var targetName = data.sourceName;
+ var capability = (0, _util.createPromiseCapability)();
+
+ var sendStreamRequest = function sendStreamRequest(_ref) {
+ var stream = _ref.stream,
+ chunk = _ref.chunk,
+ transfers = _ref.transfers,
+ success = _ref.success,
+ reason = _ref.reason;
+
+ _this3.postMessage({
+ sourceName: sourceName,
+ targetName: targetName,
+ stream: stream,
+ streamId: streamId,
+ chunk: chunk,
+ success: success,
+ reason: reason
+ }, transfers);
+ };
+
+ var streamSink = {
+ enqueue: function enqueue(chunk) {
+ var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
+ var transfers = arguments.length > 2 ? arguments[2] : undefined;
+
+ if (this.isCancelled) {
+ return;
+ }
+
+ var lastDesiredSize = this.desiredSize;
+ this.desiredSize -= size;
+
+ if (lastDesiredSize > 0 && this.desiredSize <= 0) {
+ this.sinkCapability = (0, _util.createPromiseCapability)();
+ this.ready = this.sinkCapability.promise;
+ }
+
+ sendStreamRequest({
+ stream: 'enqueue',
+ chunk: chunk,
+ transfers: transfers
+ });
+ },
+ close: function close() {
+ if (this.isCancelled) {
+ return;
+ }
+
+ this.isCancelled = true;
+ sendStreamRequest({
+ stream: 'close'
+ });
+ delete self.streamSinks[streamId];
+ },
+ error: function error(reason) {
+ if (this.isCancelled) {
+ return;
+ }
+
+ this.isCancelled = true;
+ sendStreamRequest({
+ stream: 'error',
+ reason: reason
+ });
+ },
+ sinkCapability: capability,
+ onPull: null,
+ onCancel: null,
+ isCancelled: false,
+ desiredSize: desiredSize,
+ ready: null
+ };
+ streamSink.sinkCapability.resolve();
+ streamSink.ready = streamSink.sinkCapability.promise;
+ this.streamSinks[streamId] = streamSink;
+ resolveCall(action[0], [data.data, streamSink], action[1]).then(function () {
+ sendStreamRequest({
+ stream: 'start_complete',
+ success: true
+ });
+ }, function (reason) {
+ sendStreamRequest({
+ stream: 'start_complete',
+ success: false,
+ reason: reason
+ });
+ });
+ },
+ _processStreamMessage: function _processStreamMessage(data) {
+ var _this4 = this;
+
+ var sourceName = this.sourceName;
+ var targetName = data.sourceName;
+ var streamId = data.streamId;
+
+ var sendStreamResponse = function sendStreamResponse(_ref2) {
+ var stream = _ref2.stream,
+ success = _ref2.success,
+ reason = _ref2.reason;
+
+ _this4.comObj.postMessage({
+ sourceName: sourceName,
+ targetName: targetName,
+ stream: stream,
+ success: success,
+ streamId: streamId,
+ reason: reason
+ });
+ };
+
+ var deleteStreamController = function deleteStreamController() {
+ Promise.all([_this4.streamControllers[data.streamId].startCall, _this4.streamControllers[data.streamId].pullCall, _this4.streamControllers[data.streamId].cancelCall].map(function (capability) {
+ return capability && finalize(capability.promise);
+ })).then(function () {
+ delete _this4.streamControllers[data.streamId];
+ });
+ };
+
+ switch (data.stream) {
+ case 'start_complete':
+ resolveOrReject(this.streamControllers[data.streamId].startCall, data.success, wrapReason(data.reason));
+ break;
+
+ case 'pull_complete':
+ resolveOrReject(this.streamControllers[data.streamId].pullCall, data.success, wrapReason(data.reason));
+ break;
+
+ case 'pull':
+ if (!this.streamSinks[data.streamId]) {
+ sendStreamResponse({
+ stream: 'pull_complete',
+ success: true
+ });
+ break;
+ }
+
+ if (this.streamSinks[data.streamId].desiredSize <= 0 && data.desiredSize > 0) {
+ this.streamSinks[data.streamId].sinkCapability.resolve();
+ }
+
+ this.streamSinks[data.streamId].desiredSize = data.desiredSize;
+ resolveCall(this.streamSinks[data.streamId].onPull).then(function () {
+ sendStreamResponse({
+ stream: 'pull_complete',
+ success: true
+ });
+ }, function (reason) {
+ sendStreamResponse({
+ stream: 'pull_complete',
+ success: false,
+ reason: reason
+ });
+ });
+ break;
+
+ case 'enqueue':
+ (0, _util.assert)(this.streamControllers[data.streamId], 'enqueue should have stream controller');
+
+ if (!this.streamControllers[data.streamId].isClosed) {
+ this.streamControllers[data.streamId].controller.enqueue(data.chunk);
+ }
+
+ break;
+
+ case 'close':
+ (0, _util.assert)(this.streamControllers[data.streamId], 'close should have stream controller');
+
+ if (this.streamControllers[data.streamId].isClosed) {
+ break;
+ }
+
+ this.streamControllers[data.streamId].isClosed = true;
+ this.streamControllers[data.streamId].controller.close();
+ deleteStreamController();
+ break;
+
+ case 'error':
+ (0, _util.assert)(this.streamControllers[data.streamId], 'error should have stream controller');
+ this.streamControllers[data.streamId].controller.error(wrapReason(data.reason));
+ deleteStreamController();
+ break;
+
+ case 'cancel_complete':
+ resolveOrReject(this.streamControllers[data.streamId].cancelCall, data.success, wrapReason(data.reason));
+ deleteStreamController();
+ break;
+
+ case 'cancel':
+ if (!this.streamSinks[data.streamId]) {
+ break;
+ }
+
+ resolveCall(this.streamSinks[data.streamId].onCancel, [wrapReason(data.reason)]).then(function () {
+ sendStreamResponse({
+ stream: 'cancel_complete',
+ success: true
+ });
+ }, function (reason) {
+ sendStreamResponse({
+ stream: 'cancel_complete',
+ success: false,
+ reason: reason
+ });
+ });
+ this.streamSinks[data.streamId].sinkCapability.reject(wrapReason(data.reason));
+ this.streamSinks[data.streamId].isCancelled = true;
+ delete this.streamSinks[data.streamId];
+ break;
+
+ default:
+ throw new Error('Unexpected stream case');
+ }
+ },
+ postMessage: function postMessage(message, transfers) {
+ if (transfers && this.postMessageTransfers) {
+ this.comObj.postMessage(message, transfers);
+ } else {
+ this.comObj.postMessage(message);
+ }
+ },
+ destroy: function destroy() {
+ this.comObj.removeEventListener('message', this._onComObjOnMessage);
+ }
+};
+
+/***/ }),
+/* 158 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.Metadata = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+var _xml_parser = __w_pdfjs_require__(159);
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var Metadata =
+/*#__PURE__*/
+function () {
+ function Metadata(data) {
+ _classCallCheck(this, Metadata);
+
+ (0, _util.assert)(typeof data === 'string', 'Metadata: input is not a string');
+ data = this._repair(data);
+ var parser = new _xml_parser.SimpleXMLParser();
+ var xmlDocument = parser.parseFromString(data);
+ this._metadata = Object.create(null);
+
+ if (xmlDocument) {
+ this._parse(xmlDocument);
+ }
+ }
+
+ _createClass(Metadata, [{
+ key: "_repair",
+ value: function _repair(data) {
+ return data.replace(/^([^<]+)/, '').replace(/>\\376\\377([^<]+)/g, function (all, codes) {
+ var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
+ return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
+ }).replace(/&(amp|apos|gt|lt|quot);/g, function (str, name) {
+ switch (name) {
+ case 'amp':
+ return '&';
+
+ case 'apos':
+ return '\'';
+
+ case 'gt':
+ return '>';
+
+ case 'lt':
+ return '<';
+
+ case 'quot':
+ return '\"';
+ }
+
+ throw new Error("_repair: ".concat(name, " isn't defined."));
+ });
+ var chars = '';
+
+ for (var i = 0, ii = bytes.length; i < ii; i += 2) {
+ var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
+
+ if (code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38) {
+ chars += String.fromCharCode(code);
+ } else {
+ chars += '' + (0x10000 + code).toString(16).substring(1) + ';';
+ }
+ }
+
+ return '>' + chars;
+ });
+ }
+ }, {
+ key: "_parse",
+ value: function _parse(xmlDocument) {
+ var rdf = xmlDocument.documentElement;
+
+ if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
+ rdf = rdf.firstChild;
+
+ while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
+ rdf = rdf.nextSibling;
+ }
+ }
+
+ var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
+
+ if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
+ return;
+ }
+
+ var children = rdf.childNodes;
+
+ for (var i = 0, ii = children.length; i < ii; i++) {
+ var desc = children[i];
+
+ if (desc.nodeName.toLowerCase() !== 'rdf:description') {
+ continue;
+ }
+
+ for (var j = 0, jj = desc.childNodes.length; j < jj; j++) {
+ if (desc.childNodes[j].nodeName.toLowerCase() !== '#text') {
+ var entry = desc.childNodes[j];
+ var name = entry.nodeName.toLowerCase();
+ this._metadata[name] = entry.textContent.trim();
+ }
+ }
+ }
+ }
+ }, {
+ key: "get",
+ value: function get(name) {
+ var data = this._metadata[name];
+ return typeof data !== 'undefined' ? data : null;
+ }
+ }, {
+ key: "getAll",
+ value: function getAll() {
+ return this._metadata;
+ }
+ }, {
+ key: "has",
+ value: function has(name) {
+ return typeof this._metadata[name] !== 'undefined';
+ }
+ }]);
+
+ return Metadata;
+}();
+
+exports.Metadata = Metadata;
+
+/***/ }),
+/* 159 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.SimpleXMLParser = void 0;
+
+function _typeof(obj) { 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); }
+
+function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
+
+function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
+
+function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
+
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
+
+function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
+
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
+
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var XMLParserErrorCode = {
+ NoError: 0,
+ EndOfDocument: -1,
+ UnterminatedCdat: -2,
+ UnterminatedXmlDeclaration: -3,
+ UnterminatedDoctypeDeclaration: -4,
+ UnterminatedComment: -5,
+ MalformedElement: -6,
+ OutOfMemory: -7,
+ UnterminatedAttributeValue: -8,
+ UnterminatedElement: -9,
+ ElementNeverBegun: -10
+};
+
+function isWhitespace(s, index) {
+ var ch = s[index];
+ return ch === ' ' || ch === '\n' || ch === '\r' || ch === '\t';
+}
+
+function isWhitespaceString(s) {
+ for (var i = 0, ii = s.length; i < ii; i++) {
+ if (!isWhitespace(s, i)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+var XMLParserBase =
+/*#__PURE__*/
+function () {
+ function XMLParserBase() {
+ _classCallCheck(this, XMLParserBase);
+ }
+
+ _createClass(XMLParserBase, [{
+ key: "_resolveEntities",
+ value: function _resolveEntities(s) {
+ var _this = this;
+
+ return s.replace(/&([^;]+);/g, function (all, entity) {
+ if (entity.substring(0, 2) === '#x') {
+ return String.fromCharCode(parseInt(entity.substring(2), 16));
+ } else if (entity.substring(0, 1) === '#') {
+ return String.fromCharCode(parseInt(entity.substring(1), 10));
+ }
+
+ switch (entity) {
+ case 'lt':
+ return '<';
+
+ case 'gt':
+ return '>';
+
+ case 'amp':
+ return '&';
+
+ case 'quot':
+ return '\"';
+ }
+
+ return _this.onResolveEntity(entity);
+ });
+ }
+ }, {
+ key: "_parseContent",
+ value: function _parseContent(s, start) {
+ var pos = start,
+ name,
+ attributes = [];
+
+ function skipWs() {
+ while (pos < s.length && isWhitespace(s, pos)) {
+ ++pos;
+ }
+ }
+
+ while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== '>' && s[pos] !== '/') {
+ ++pos;
+ }
+
+ name = s.substring(start, pos);
+ skipWs();
+
+ while (pos < s.length && s[pos] !== '>' && s[pos] !== '/' && s[pos] !== '?') {
+ skipWs();
+ var attrName = '',
+ attrValue = '';
+
+ while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== '=') {
+ attrName += s[pos];
+ ++pos;
+ }
+
+ skipWs();
+
+ if (s[pos] !== '=') {
+ return null;
+ }
+
+ ++pos;
+ skipWs();
+ var attrEndChar = s[pos];
+
+ if (attrEndChar !== '\"' && attrEndChar !== '\'') {
+ return null;
+ }
+
+ var attrEndIndex = s.indexOf(attrEndChar, ++pos);
+
+ if (attrEndIndex < 0) {
+ return null;
+ }
+
+ attrValue = s.substring(pos, attrEndIndex);
+ attributes.push({
+ name: attrName,
+ value: this._resolveEntities(attrValue)
+ });
+ pos = attrEndIndex + 1;
+ skipWs();
+ }
+
+ return {
+ name: name,
+ attributes: attributes,
+ parsed: pos - start
+ };
+ }
+ }, {
+ key: "_parseProcessingInstruction",
+ value: function _parseProcessingInstruction(s, start) {
+ var pos = start,
+ name,
+ value;
+
+ function skipWs() {
+ while (pos < s.length && isWhitespace(s, pos)) {
+ ++pos;
+ }
+ }
+
+ while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== '>' && s[pos] !== '/') {
+ ++pos;
+ }
+
+ name = s.substring(start, pos);
+ skipWs();
+ var attrStart = pos;
+
+ while (pos < s.length && (s[pos] !== '?' || s[pos + 1] !== '>')) {
+ ++pos;
+ }
+
+ value = s.substring(attrStart, pos);
+ return {
+ name: name,
+ value: value,
+ parsed: pos - start
+ };
+ }
+ }, {
+ key: "parseXml",
+ value: function parseXml(s) {
+ var i = 0;
+
+ while (i < s.length) {
+ var ch = s[i];
+ var j = i;
+
+ if (ch === '<') {
+ ++j;
+ var ch2 = s[j];
+ var q = void 0;
+
+ switch (ch2) {
+ case '/':
+ ++j;
+ q = s.indexOf('>', j);
+
+ if (q < 0) {
+ this.onError(XMLParserErrorCode.UnterminatedElement);
+ return;
+ }
+
+ this.onEndElement(s.substring(j, q));
+ j = q + 1;
+ break;
+
+ case '?':
+ ++j;
+
+ var pi = this._parseProcessingInstruction(s, j);
+
+ if (s.substring(j + pi.parsed, j + pi.parsed + 2) !== '?>') {
+ this.onError(XMLParserErrorCode.UnterminatedXmlDeclaration);
+ return;
+ }
+
+ this.onPi(pi.name, pi.value);
+ j += pi.parsed + 2;
+ break;
+
+ case '!':
+ if (s.substring(j + 1, j + 3) === '--') {
+ q = s.indexOf('-->', j + 3);
+
+ if (q < 0) {
+ this.onError(XMLParserErrorCode.UnterminatedComment);
+ return;
+ }
+
+ this.onComment(s.substring(j + 3, q));
+ j = q + 3;
+ } else if (s.substring(j + 1, j + 8) === '[CDATA[') {
+ q = s.indexOf(']]>', j + 8);
+
+ if (q < 0) {
+ this.onError(XMLParserErrorCode.UnterminatedCdat);
+ return;
+ }
+
+ this.onCdata(s.substring(j + 8, q));
+ j = q + 3;
+ } else if (s.substring(j + 1, j + 8) === 'DOCTYPE') {
+ var q2 = s.indexOf('[', j + 8);
+ var complexDoctype = false;
+ q = s.indexOf('>', j + 8);
+
+ if (q < 0) {
+ this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
+ return;
+ }
+
+ if (q2 > 0 && q > q2) {
+ q = s.indexOf(']>', j + 8);
+
+ if (q < 0) {
+ this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
+ return;
+ }
+
+ complexDoctype = true;
+ }
+
+ var doctypeContent = s.substring(j + 8, q + (complexDoctype ? 1 : 0));
+ this.onDoctype(doctypeContent);
+ j = q + (complexDoctype ? 2 : 1);
+ } else {
+ this.onError(XMLParserErrorCode.MalformedElement);
+ return;
+ }
+
+ break;
+
+ default:
+ var content = this._parseContent(s, j);
+
+ if (content === null) {
+ this.onError(XMLParserErrorCode.MalformedElement);
+ return;
+ }
+
+ var isClosed = false;
+
+ if (s.substring(j + content.parsed, j + content.parsed + 2) === '/>') {
+ isClosed = true;
+ } else if (s.substring(j + content.parsed, j + content.parsed + 1) !== '>') {
+ this.onError(XMLParserErrorCode.UnterminatedElement);
+ return;
+ }
+
+ this.onBeginElement(content.name, content.attributes, isClosed);
+ j += content.parsed + (isClosed ? 2 : 1);
+ break;
+ }
+ } else {
+ while (j < s.length && s[j] !== '<') {
+ j++;
+ }
+
+ var text = s.substring(i, j);
+ this.onText(this._resolveEntities(text));
+ }
+
+ i = j;
+ }
+ }
+ }, {
+ key: "onResolveEntity",
+ value: function onResolveEntity(name) {
+ return "&".concat(name, ";");
+ }
+ }, {
+ key: "onPi",
+ value: function onPi(name, value) {}
+ }, {
+ key: "onComment",
+ value: function onComment(text) {}
+ }, {
+ key: "onCdata",
+ value: function onCdata(text) {}
+ }, {
+ key: "onDoctype",
+ value: function onDoctype(doctypeContent) {}
+ }, {
+ key: "onText",
+ value: function onText(text) {}
+ }, {
+ key: "onBeginElement",
+ value: function onBeginElement(name, attributes, isEmpty) {}
+ }, {
+ key: "onEndElement",
+ value: function onEndElement(name) {}
+ }, {
+ key: "onError",
+ value: function onError(code) {}
+ }]);
+
+ return XMLParserBase;
+}();
+
+var SimpleDOMNode =
+/*#__PURE__*/
+function () {
+ function SimpleDOMNode(nodeName, nodeValue) {
+ _classCallCheck(this, SimpleDOMNode);
+
+ this.nodeName = nodeName;
+ this.nodeValue = nodeValue;
+ Object.defineProperty(this, 'parentNode', {
+ value: null,
+ writable: true
+ });
+ }
+
+ _createClass(SimpleDOMNode, [{
+ key: "hasChildNodes",
+ value: function hasChildNodes() {
+ return this.childNodes && this.childNodes.length > 0;
+ }
+ }, {
+ key: "firstChild",
+ get: function get() {
+ return this.childNodes && this.childNodes[0];
+ }
+ }, {
+ key: "nextSibling",
+ get: function get() {
+ var childNodes = this.parentNode.childNodes;
+
+ if (!childNodes) {
+ return undefined;
+ }
+
+ var index = childNodes.indexOf(this);
+
+ if (index === -1) {
+ return undefined;
+ }
+
+ return childNodes[index + 1];
+ }
+ }, {
+ key: "textContent",
+ get: function get() {
+ if (!this.childNodes) {
+ return this.nodeValue || '';
+ }
+
+ return this.childNodes.map(function (child) {
+ return child.textContent;
+ }).join('');
+ }
+ }]);
+
+ return SimpleDOMNode;
+}();
+
+var SimpleXMLParser =
+/*#__PURE__*/
+function (_XMLParserBase) {
+ _inherits(SimpleXMLParser, _XMLParserBase);
+
+ function SimpleXMLParser() {
+ var _this2;
+
+ _classCallCheck(this, SimpleXMLParser);
+
+ _this2 = _possibleConstructorReturn(this, _getPrototypeOf(SimpleXMLParser).call(this));
+ _this2._currentFragment = null;
+ _this2._stack = null;
+ _this2._errorCode = XMLParserErrorCode.NoError;
+ return _this2;
+ }
+
+ _createClass(SimpleXMLParser, [{
+ key: "parseFromString",
+ value: function parseFromString(data) {
+ this._currentFragment = [];
+ this._stack = [];
+ this._errorCode = XMLParserErrorCode.NoError;
+ this.parseXml(data);
+
+ if (this._errorCode !== XMLParserErrorCode.NoError) {
+ return undefined;
+ }
+
+ var _this$_currentFragmen = _slicedToArray(this._currentFragment, 1),
+ documentElement = _this$_currentFragmen[0];
+
+ if (!documentElement) {
+ return undefined;
+ }
+
+ return {
+ documentElement: documentElement
+ };
+ }
+ }, {
+ key: "onResolveEntity",
+ value: function onResolveEntity(name) {
+ switch (name) {
+ case 'apos':
+ return '\'';
+ }
+
+ return _get(_getPrototypeOf(SimpleXMLParser.prototype), "onResolveEntity", this).call(this, name);
+ }
+ }, {
+ key: "onText",
+ value: function onText(text) {
+ if (isWhitespaceString(text)) {
+ return;
+ }
+
+ var node = new SimpleDOMNode('#text', text);
+
+ this._currentFragment.push(node);
+ }
+ }, {
+ key: "onCdata",
+ value: function onCdata(text) {
+ var node = new SimpleDOMNode('#text', text);
+
+ this._currentFragment.push(node);
+ }
+ }, {
+ key: "onBeginElement",
+ value: function onBeginElement(name, attributes, isEmpty) {
+ var node = new SimpleDOMNode(name);
+ node.childNodes = [];
+
+ this._currentFragment.push(node);
+
+ if (isEmpty) {
+ return;
+ }
+
+ this._stack.push(this._currentFragment);
+
+ this._currentFragment = node.childNodes;
+ }
+ }, {
+ key: "onEndElement",
+ value: function onEndElement(name) {
+ this._currentFragment = this._stack.pop() || [];
+ var lastElement = this._currentFragment[this._currentFragment.length - 1];
+
+ if (!lastElement) {
+ return;
+ }
+
+ for (var i = 0, ii = lastElement.childNodes.length; i < ii; i++) {
+ lastElement.childNodes[i].parentNode = lastElement;
+ }
+ }
+ }, {
+ key: "onError",
+ value: function onError(code) {
+ this._errorCode = code;
+ }
+ }]);
+
+ return SimpleXMLParser;
+}(XMLParserBase);
+
+exports.SimpleXMLParser = SimpleXMLParser;
+
+/***/ }),
+/* 160 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.PDFDataTransportStream = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var PDFDataTransportStream =
+/*#__PURE__*/
+function () {
+ function PDFDataTransportStream(params, pdfDataRangeTransport) {
+ var _this = this;
+
+ _classCallCheck(this, PDFDataTransportStream);
+
+ (0, _util.assert)(pdfDataRangeTransport);
+ this._queuedChunks = [];
+ this._progressiveDone = params.progressiveDone || false;
+ var initialData = params.initialData;
+
+ if (initialData && initialData.length > 0) {
+ var buffer = new Uint8Array(initialData).buffer;
+
+ this._queuedChunks.push(buffer);
+ }
+
+ this._pdfDataRangeTransport = pdfDataRangeTransport;
+ this._isStreamingSupported = !params.disableStream;
+ this._isRangeSupported = !params.disableRange;
+ this._contentLength = params.length;
+ this._fullRequestReader = null;
+ this._rangeReaders = [];
+
+ this._pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
+ _this._onReceiveData({
+ begin: begin,
+ chunk: chunk
+ });
+ });
+
+ this._pdfDataRangeTransport.addProgressListener(function (loaded, total) {
+ _this._onProgress({
+ loaded: loaded,
+ total: total
+ });
+ });
+
+ this._pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
+ _this._onReceiveData({
+ chunk: chunk
+ });
+ });
+
+ this._pdfDataRangeTransport.addProgressiveDoneListener(function () {
+ _this._onProgressiveDone();
+ });
+
+ this._pdfDataRangeTransport.transportReady();
+ }
+
+ _createClass(PDFDataTransportStream, [{
+ key: "_onReceiveData",
+ value: function _onReceiveData(args) {
+ var buffer = new Uint8Array(args.chunk).buffer;
+
+ if (args.begin === undefined) {
+ if (this._fullRequestReader) {
+ this._fullRequestReader._enqueue(buffer);
+ } else {
+ this._queuedChunks.push(buffer);
+ }
+ } else {
+ var found = this._rangeReaders.some(function (rangeReader) {
+ if (rangeReader._begin !== args.begin) {
+ return false;
+ }
+
+ rangeReader._enqueue(buffer);
+
+ return true;
+ });
+
+ (0, _util.assert)(found);
+ }
+ }
+ }, {
+ key: "_onProgress",
+ value: function _onProgress(evt) {
+ if (evt.total === undefined) {
+ var firstReader = this._rangeReaders[0];
+
+ if (firstReader && firstReader.onProgress) {
+ firstReader.onProgress({
+ loaded: evt.loaded
+ });
+ }
+ } else {
+ var fullReader = this._fullRequestReader;
+
+ if (fullReader && fullReader.onProgress) {
+ fullReader.onProgress({
+ loaded: evt.loaded,
+ total: evt.total
+ });
+ }
+ }
+ }
+ }, {
+ key: "_onProgressiveDone",
+ value: function _onProgressiveDone() {
+ if (this._fullRequestReader) {
+ this._fullRequestReader.progressiveDone();
+ }
+
+ this._progressiveDone = true;
+ }
+ }, {
+ key: "_removeRangeReader",
+ value: function _removeRangeReader(reader) {
+ var i = this._rangeReaders.indexOf(reader);
+
+ if (i >= 0) {
+ this._rangeReaders.splice(i, 1);
+ }
+ }
+ }, {
+ key: "getFullReader",
+ value: function getFullReader() {
+ (0, _util.assert)(!this._fullRequestReader);
+ var queuedChunks = this._queuedChunks;
+ this._queuedChunks = null;
+ return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone);
+ }
+ }, {
+ key: "getRangeReader",
+ value: function getRangeReader(begin, end) {
+ if (end <= this._progressiveDataLength) {
+ return null;
+ }
+
+ var reader = new PDFDataTransportStreamRangeReader(this, begin, end);
+
+ this._pdfDataRangeTransport.requestDataRange(begin, end);
+
+ this._rangeReaders.push(reader);
+
+ return reader;
+ }
+ }, {
+ key: "cancelAllRequests",
+ value: function cancelAllRequests(reason) {
+ if (this._fullRequestReader) {
+ this._fullRequestReader.cancel(reason);
+ }
+
+ var readers = this._rangeReaders.slice(0);
+
+ readers.forEach(function (rangeReader) {
+ rangeReader.cancel(reason);
+ });
+
+ this._pdfDataRangeTransport.abort();
+ }
+ }, {
+ key: "_progressiveDataLength",
+ get: function get() {
+ return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
+ }
+ }]);
+
+ return PDFDataTransportStream;
+}();
+
+exports.PDFDataTransportStream = PDFDataTransportStream;
+
+var PDFDataTransportStreamReader =
+/*#__PURE__*/
+function () {
+ function PDFDataTransportStreamReader(stream, queuedChunks) {
+ var progressiveDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
+ _classCallCheck(this, PDFDataTransportStreamReader);
+
+ this._stream = stream;
+ this._done = progressiveDone || false;
+ this._filename = null;
+ this._queuedChunks = queuedChunks || [];
+ this._loaded = 0;
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = this._queuedChunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var chunk = _step.value;
+ this._loaded += chunk.byteLength;
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+ _iterator["return"]();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ this._requests = [];
+ this._headersReady = Promise.resolve();
+ stream._fullRequestReader = this;
+ this.onProgress = null;
+ }
+
+ _createClass(PDFDataTransportStreamReader, [{
+ key: "_enqueue",
+ value: function _enqueue(chunk) {
+ if (this._done) {
+ return;
+ }
+
+ if (this._requests.length > 0) {
+ var requestCapability = this._requests.shift();
+
+ requestCapability.resolve({
+ value: chunk,
+ done: false
+ });
+ } else {
+ this._queuedChunks.push(chunk);
+ }
+
+ this._loaded += chunk.byteLength;
+ }
+ }, {
+ key: "read",
+ value: function () {
+ var _read = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee() {
+ var chunk, requestCapability;
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (!(this._queuedChunks.length > 0)) {
+ _context.next = 3;
+ break;
+ }
+
+ chunk = this._queuedChunks.shift();
+ return _context.abrupt("return", {
+ value: chunk,
+ done: false
+ });
+
+ case 3:
+ if (!this._done) {
+ _context.next = 5;
+ break;
+ }
+
+ return _context.abrupt("return", {
+ value: undefined,
+ done: true
+ });
+
+ case 5:
+ requestCapability = (0, _util.createPromiseCapability)();
+
+ this._requests.push(requestCapability);
+
+ return _context.abrupt("return", requestCapability.promise);
+
+ case 8:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee, this);
+ }));
+
+ function read() {
+ return _read.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ this._done = true;
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+ }
+ }, {
+ key: "progressiveDone",
+ value: function progressiveDone() {
+ if (this._done) {
+ return;
+ }
+
+ this._done = true;
+ }
+ }, {
+ key: "headersReady",
+ get: function get() {
+ return this._headersReady;
+ }
+ }, {
+ key: "filename",
+ get: function get() {
+ return this._filename;
+ }
+ }, {
+ key: "isRangeSupported",
+ get: function get() {
+ return this._stream._isRangeSupported;
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return this._stream._isStreamingSupported;
+ }
+ }, {
+ key: "contentLength",
+ get: function get() {
+ return this._stream._contentLength;
+ }
+ }]);
+
+ return PDFDataTransportStreamReader;
+}();
+
+var PDFDataTransportStreamRangeReader =
+/*#__PURE__*/
+function () {
+ function PDFDataTransportStreamRangeReader(stream, begin, end) {
+ _classCallCheck(this, PDFDataTransportStreamRangeReader);
+
+ this._stream = stream;
+ this._begin = begin;
+ this._end = end;
+ this._queuedChunk = null;
+ this._requests = [];
+ this._done = false;
+ this.onProgress = null;
+ }
+
+ _createClass(PDFDataTransportStreamRangeReader, [{
+ key: "_enqueue",
+ value: function _enqueue(chunk) {
+ if (this._done) {
+ return;
+ }
+
+ if (this._requests.length === 0) {
+ this._queuedChunk = chunk;
+ } else {
+ var requestsCapability = this._requests.shift();
+
+ requestsCapability.resolve({
+ value: chunk,
+ done: false
+ });
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+ }
+
+ this._done = true;
+
+ this._stream._removeRangeReader(this);
+ }
+ }, {
+ key: "read",
+ value: function () {
+ var _read2 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee2() {
+ var chunk, requestCapability;
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
+ while (1) {
+ switch (_context2.prev = _context2.next) {
+ case 0:
+ if (!this._queuedChunk) {
+ _context2.next = 4;
+ break;
+ }
+
+ chunk = this._queuedChunk;
+ this._queuedChunk = null;
+ return _context2.abrupt("return", {
+ value: chunk,
+ done: false
+ });
+
+ case 4:
+ if (!this._done) {
+ _context2.next = 6;
+ break;
+ }
+
+ return _context2.abrupt("return", {
+ value: undefined,
+ done: true
+ });
+
+ case 6:
+ requestCapability = (0, _util.createPromiseCapability)();
+
+ this._requests.push(requestCapability);
+
+ return _context2.abrupt("return", requestCapability.promise);
+
+ case 9:
+ case "end":
+ return _context2.stop();
+ }
+ }
+ }, _callee2, this);
+ }));
+
+ function read() {
+ return _read2.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ this._done = true;
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+
+ this._stream._removeRangeReader(this);
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return false;
+ }
+ }]);
+
+ return PDFDataTransportStreamRangeReader;
+}();
+
+/***/ }),
+/* 161 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.WebGLContext = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var WebGLContext =
+/*#__PURE__*/
+function () {
+ function WebGLContext(_ref) {
+ var _ref$enable = _ref.enable,
+ enable = _ref$enable === void 0 ? false : _ref$enable;
+
+ _classCallCheck(this, WebGLContext);
+
+ this._enabled = enable === true;
+ }
+
+ _createClass(WebGLContext, [{
+ key: "composeSMask",
+ value: function composeSMask(_ref2) {
+ var layer = _ref2.layer,
+ mask = _ref2.mask,
+ properties = _ref2.properties;
+ return WebGLUtils.composeSMask(layer, mask, properties);
+ }
+ }, {
+ key: "drawFigures",
+ value: function drawFigures(_ref3) {
+ var width = _ref3.width,
+ height = _ref3.height,
+ backgroundColor = _ref3.backgroundColor,
+ figures = _ref3.figures,
+ context = _ref3.context;
+ return WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
+ }
+ }, {
+ key: "clear",
+ value: function clear() {
+ WebGLUtils.cleanup();
+ }
+ }, {
+ key: "isEnabled",
+ get: function get() {
+ var enabled = this._enabled;
+
+ if (enabled) {
+ enabled = WebGLUtils.tryInitGL();
+ }
+
+ return (0, _util.shadow)(this, 'isEnabled', enabled);
+ }
+ }]);
+
+ return WebGLContext;
+}();
+
+exports.WebGLContext = WebGLContext;
+
+var WebGLUtils = function WebGLUtilsClosure() {
+ function loadShader(gl, code, shaderType) {
+ var shader = gl.createShader(shaderType);
+ gl.shaderSource(shader, code);
+ gl.compileShader(shader);
+ var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
+
+ if (!compiled) {
+ var errorMsg = gl.getShaderInfoLog(shader);
+ throw new Error('Error during shader compilation: ' + errorMsg);
+ }
+
+ return shader;
+ }
+
+ function createVertexShader(gl, code) {
+ return loadShader(gl, code, gl.VERTEX_SHADER);
+ }
+
+ function createFragmentShader(gl, code) {
+ return loadShader(gl, code, gl.FRAGMENT_SHADER);
+ }
+
+ function createProgram(gl, shaders) {
+ var program = gl.createProgram();
+
+ for (var i = 0, ii = shaders.length; i < ii; ++i) {
+ gl.attachShader(program, shaders[i]);
+ }
+
+ gl.linkProgram(program);
+ var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
+
+ if (!linked) {
+ var errorMsg = gl.getProgramInfoLog(program);
+ throw new Error('Error during program linking: ' + errorMsg);
+ }
+
+ return program;
+ }
+
+ function createTexture(gl, image, textureId) {
+ gl.activeTexture(textureId);
+ var texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
+ return texture;
+ }
+
+ var currentGL, currentCanvas;
+
+ function generateGL() {
+ if (currentGL) {
+ return;
+ }
+
+ currentCanvas = document.createElement('canvas');
+ currentGL = currentCanvas.getContext('webgl', {
+ premultipliedalpha: false
+ });
+ }
+
+ var smaskVertexShaderCode = '\
+ attribute vec2 a_position; \
+ attribute vec2 a_texCoord; \
+ \
+ uniform vec2 u_resolution; \
+ \
+ varying vec2 v_texCoord; \
+ \
+ void main() { \
+ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
+ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
+ \
+ v_texCoord = a_texCoord; \
+ } ';
+ var smaskFragmentShaderCode = '\
+ precision mediump float; \
+ \
+ uniform vec4 u_backdrop; \
+ uniform int u_subtype; \
+ uniform sampler2D u_image; \
+ uniform sampler2D u_mask; \
+ \
+ varying vec2 v_texCoord; \
+ \
+ void main() { \
+ vec4 imageColor = texture2D(u_image, v_texCoord); \
+ vec4 maskColor = texture2D(u_mask, v_texCoord); \
+ if (u_backdrop.a > 0.0) { \
+ maskColor.rgb = maskColor.rgb * maskColor.a + \
+ u_backdrop.rgb * (1.0 - maskColor.a); \
+ } \
+ float lum; \
+ if (u_subtype == 0) { \
+ lum = maskColor.a; \
+ } else { \
+ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
+ maskColor.b * 0.11; \
+ } \
+ imageColor.a *= lum; \
+ imageColor.rgb *= imageColor.a; \
+ gl_FragColor = imageColor; \
+ } ';
+ var smaskCache = null;
+
+ function initSmaskGL() {
+ var canvas, gl;
+ generateGL();
+ canvas = currentCanvas;
+ currentCanvas = null;
+ gl = currentGL;
+ currentGL = null;
+ var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
+ var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
+ var program = createProgram(gl, [vertexShader, fragmentShader]);
+ gl.useProgram(program);
+ var cache = {};
+ cache.gl = gl;
+ cache.canvas = canvas;
+ cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
+ cache.positionLocation = gl.getAttribLocation(program, 'a_position');
+ cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
+ cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
+ var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
+ var texLayerLocation = gl.getUniformLocation(program, 'u_image');
+ var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
+ var texCoordBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(texCoordLocation);
+ gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
+ gl.uniform1i(texLayerLocation, 0);
+ gl.uniform1i(texMaskLocation, 1);
+ smaskCache = cache;
+ }
+
+ function composeSMask(layer, mask, properties) {
+ var width = layer.width,
+ height = layer.height;
+
+ if (!smaskCache) {
+ initSmaskGL();
+ }
+
+ var cache = smaskCache,
+ canvas = cache.canvas,
+ gl = cache.gl;
+ canvas.width = width;
+ canvas.height = height;
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
+ gl.uniform2f(cache.resolutionLocation, width, height);
+
+ if (properties.backdrop) {
+ gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
+ } else {
+ gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
+ }
+
+ gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
+ var texture = createTexture(gl, layer, gl.TEXTURE0);
+ var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
+ var buffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(cache.positionLocation);
+ gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
+ gl.clearColor(0, 0, 0, 0);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.flush();
+ gl.deleteTexture(texture);
+ gl.deleteTexture(maskTexture);
+ gl.deleteBuffer(buffer);
+ return canvas;
+ }
+
+ var figuresVertexShaderCode = '\
+ attribute vec2 a_position; \
+ attribute vec3 a_color; \
+ \
+ uniform vec2 u_resolution; \
+ uniform vec2 u_scale; \
+ uniform vec2 u_offset; \
+ \
+ varying vec4 v_color; \
+ \
+ void main() { \
+ vec2 position = (a_position + u_offset) * u_scale; \
+ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
+ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
+ \
+ v_color = vec4(a_color / 255.0, 1.0); \
+ } ';
+ var figuresFragmentShaderCode = '\
+ precision mediump float; \
+ \
+ varying vec4 v_color; \
+ \
+ void main() { \
+ gl_FragColor = v_color; \
+ } ';
+ var figuresCache = null;
+
+ function initFiguresGL() {
+ var canvas, gl;
+ generateGL();
+ canvas = currentCanvas;
+ currentCanvas = null;
+ gl = currentGL;
+ currentGL = null;
+ var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
+ var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
+ var program = createProgram(gl, [vertexShader, fragmentShader]);
+ gl.useProgram(program);
+ var cache = {};
+ cache.gl = gl;
+ cache.canvas = canvas;
+ cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
+ cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
+ cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
+ cache.positionLocation = gl.getAttribLocation(program, 'a_position');
+ cache.colorLocation = gl.getAttribLocation(program, 'a_color');
+ figuresCache = cache;
+ }
+
+ function drawFigures(width, height, backgroundColor, figures, context) {
+ if (!figuresCache) {
+ initFiguresGL();
+ }
+
+ var cache = figuresCache,
+ canvas = cache.canvas,
+ gl = cache.gl;
+ canvas.width = width;
+ canvas.height = height;
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
+ gl.uniform2f(cache.resolutionLocation, width, height);
+ var count = 0;
+ var i, ii, rows;
+
+ for (i = 0, ii = figures.length; i < ii; i++) {
+ switch (figures[i].type) {
+ case 'lattice':
+ rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
+ count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
+ break;
+
+ case 'triangles':
+ count += figures[i].coords.length;
+ break;
+ }
+ }
+
+ var coords = new Float32Array(count * 2);
+ var colors = new Uint8Array(count * 3);
+ var coordsMap = context.coords,
+ colorsMap = context.colors;
+ var pIndex = 0,
+ cIndex = 0;
+
+ for (i = 0, ii = figures.length; i < ii; i++) {
+ var figure = figures[i],
+ ps = figure.coords,
+ cs = figure.colors;
+
+ switch (figure.type) {
+ case 'lattice':
+ var cols = figure.verticesPerRow;
+ rows = ps.length / cols | 0;
+
+ for (var row = 1; row < rows; row++) {
+ var offset = row * cols + 1;
+
+ for (var col = 1; col < cols; col++, offset++) {
+ coords[pIndex] = coordsMap[ps[offset - cols - 1]];
+ coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
+ coords[pIndex + 2] = coordsMap[ps[offset - cols]];
+ coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
+ coords[pIndex + 4] = coordsMap[ps[offset - 1]];
+ coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
+ colors[cIndex] = colorsMap[cs[offset - cols - 1]];
+ colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
+ colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
+ colors[cIndex + 3] = colorsMap[cs[offset - cols]];
+ colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
+ colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
+ colors[cIndex + 6] = colorsMap[cs[offset - 1]];
+ colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
+ colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
+ coords[pIndex + 6] = coords[pIndex + 2];
+ coords[pIndex + 7] = coords[pIndex + 3];
+ coords[pIndex + 8] = coords[pIndex + 4];
+ coords[pIndex + 9] = coords[pIndex + 5];
+ coords[pIndex + 10] = coordsMap[ps[offset]];
+ coords[pIndex + 11] = coordsMap[ps[offset] + 1];
+ colors[cIndex + 9] = colors[cIndex + 3];
+ colors[cIndex + 10] = colors[cIndex + 4];
+ colors[cIndex + 11] = colors[cIndex + 5];
+ colors[cIndex + 12] = colors[cIndex + 6];
+ colors[cIndex + 13] = colors[cIndex + 7];
+ colors[cIndex + 14] = colors[cIndex + 8];
+ colors[cIndex + 15] = colorsMap[cs[offset]];
+ colors[cIndex + 16] = colorsMap[cs[offset] + 1];
+ colors[cIndex + 17] = colorsMap[cs[offset] + 2];
+ pIndex += 12;
+ cIndex += 18;
+ }
+ }
+
+ break;
+
+ case 'triangles':
+ for (var j = 0, jj = ps.length; j < jj; j++) {
+ coords[pIndex] = coordsMap[ps[j]];
+ coords[pIndex + 1] = coordsMap[ps[j] + 1];
+ colors[cIndex] = colorsMap[cs[j]];
+ colors[cIndex + 1] = colorsMap[cs[j] + 1];
+ colors[cIndex + 2] = colorsMap[cs[j] + 2];
+ pIndex += 2;
+ cIndex += 3;
+ }
+
+ break;
+ }
+ }
+
+ if (backgroundColor) {
+ gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
+ } else {
+ gl.clearColor(0, 0, 0, 0);
+ }
+
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ var coordsBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(cache.positionLocation);
+ gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
+ var colorsBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(cache.colorLocation);
+ gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
+ gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
+ gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
+ gl.drawArrays(gl.TRIANGLES, 0, count);
+ gl.flush();
+ gl.deleteBuffer(coordsBuffer);
+ gl.deleteBuffer(colorsBuffer);
+ return canvas;
+ }
+
+ return {
+ tryInitGL: function tryInitGL() {
+ try {
+ generateGL();
+ return !!currentGL;
+ } catch (ex) {}
+
+ return false;
+ },
+ composeSMask: composeSMask,
+ drawFigures: drawFigures,
+ cleanup: function cleanup() {
+ if (smaskCache && smaskCache.canvas) {
+ smaskCache.canvas.width = 0;
+ smaskCache.canvas.height = 0;
+ }
+
+ if (figuresCache && figuresCache.canvas) {
+ figuresCache.canvas.width = 0;
+ figuresCache.canvas.height = 0;
+ }
+
+ smaskCache = null;
+ figuresCache = null;
+ }
+ };
+}();
+
+/***/ }),
+/* 162 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.renderTextLayer = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+var _global_scope = _interopRequireDefault(__w_pdfjs_require__(3));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
+
+var renderTextLayer = function renderTextLayerClosure() {
+ var MAX_TEXT_DIVS_TO_RENDER = 100000;
+ var NonWhitespaceRegexp = /\S/;
+
+ function isAllWhitespace(str) {
+ return !NonWhitespaceRegexp.test(str);
+ }
+
+ var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0, 'px; font-family: ', '', ';'];
+
+ function appendText(task, geom, styles) {
+ var textDiv = document.createElement('span');
+ var textDivProperties = {
+ style: null,
+ angle: 0,
+ canvasWidth: 0,
+ isWhitespace: false,
+ originalTransform: null,
+ paddingBottom: 0,
+ paddingLeft: 0,
+ paddingRight: 0,
+ paddingTop: 0,
+ scale: 1
+ };
+
+ task._textDivs.push(textDiv);
+
+ if (isAllWhitespace(geom.str)) {
+ textDivProperties.isWhitespace = true;
+
+ task._textDivProperties.set(textDiv, textDivProperties);
+
+ return;
+ }
+
+ var tx = _util.Util.transform(task._viewport.transform, geom.transform);
+
+ var angle = Math.atan2(tx[1], tx[0]);
+ var style = styles[geom.fontName];
+
+ if (style.vertical) {
+ angle += Math.PI / 2;
+ }
+
+ var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
+ var fontAscent = fontHeight;
+
+ if (style.ascent) {
+ fontAscent = style.ascent * fontAscent;
+ } else if (style.descent) {
+ fontAscent = (1 + style.descent) * fontAscent;
+ }
+
+ var left;
+ var top;
+
+ if (angle === 0) {
+ left = tx[4];
+ top = tx[5] - fontAscent;
+ } else {
+ left = tx[4] + fontAscent * Math.sin(angle);
+ top = tx[5] - fontAscent * Math.cos(angle);
+ }
+
+ styleBuf[1] = left;
+ styleBuf[3] = top;
+ styleBuf[5] = fontHeight;
+ styleBuf[7] = style.fontFamily;
+ textDivProperties.style = styleBuf.join('');
+ textDiv.setAttribute('style', textDivProperties.style);
+ textDiv.textContent = geom.str;
+
+ if (task._fontInspectorEnabled) {
+ textDiv.dataset.fontName = geom.fontName;
+ }
+
+ if (angle !== 0) {
+ textDivProperties.angle = angle * (180 / Math.PI);
+ }
+
+ if (geom.str.length > 1) {
+ if (style.vertical) {
+ textDivProperties.canvasWidth = geom.height * task._viewport.scale;
+ } else {
+ textDivProperties.canvasWidth = geom.width * task._viewport.scale;
+ }
+ }
+
+ task._textDivProperties.set(textDiv, textDivProperties);
+
+ if (task._textContentStream) {
+ task._layoutText(textDiv);
+ }
+
+ if (task._enhanceTextSelection) {
+ var angleCos = 1,
+ angleSin = 0;
+
+ if (angle !== 0) {
+ angleCos = Math.cos(angle);
+ angleSin = Math.sin(angle);
+ }
+
+ var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
+ var divHeight = fontHeight;
+ var m, b;
+
+ if (angle !== 0) {
+ m = [angleCos, angleSin, -angleSin, angleCos, left, top];
+ b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
+ } else {
+ b = [left, top, left + divWidth, top + divHeight];
+ }
+
+ task._bounds.push({
+ left: b[0],
+ top: b[1],
+ right: b[2],
+ bottom: b[3],
+ div: textDiv,
+ size: [divWidth, divHeight],
+ m: m
+ });
+ }
+ }
+
+ function render(task) {
+ if (task._canceled) {
+ return;
+ }
+
+ var textDivs = task._textDivs;
+ var capability = task._capability;
+ var textDivsLength = textDivs.length;
+
+ if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
+ task._renderingDone = true;
+ capability.resolve();
+ return;
+ }
+
+ if (!task._textContentStream) {
+ for (var i = 0; i < textDivsLength; i++) {
+ task._layoutText(textDivs[i]);
+ }
+ }
+
+ task._renderingDone = true;
+ capability.resolve();
+ }
+
+ function expand(task) {
+ var bounds = task._bounds;
+ var viewport = task._viewport;
+ var expanded = expandBounds(viewport.width, viewport.height, bounds);
+
+ for (var i = 0; i < expanded.length; i++) {
+ var div = bounds[i].div;
+
+ var divProperties = task._textDivProperties.get(div);
+
+ if (divProperties.angle === 0) {
+ divProperties.paddingLeft = bounds[i].left - expanded[i].left;
+ divProperties.paddingTop = bounds[i].top - expanded[i].top;
+ divProperties.paddingRight = expanded[i].right - bounds[i].right;
+ divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
+
+ task._textDivProperties.set(div, divProperties);
+
+ continue;
+ }
+
+ var e = expanded[i],
+ b = bounds[i];
+ var m = b.m,
+ c = m[0],
+ s = m[1];
+ var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
+ var ts = new Float64Array(64);
+ points.forEach(function (p, i) {
+ var t = _util.Util.applyTransform(p, m);
+
+ ts[i + 0] = c && (e.left - t[0]) / c;
+ ts[i + 4] = s && (e.top - t[1]) / s;
+ ts[i + 8] = c && (e.right - t[0]) / c;
+ ts[i + 12] = s && (e.bottom - t[1]) / s;
+ ts[i + 16] = s && (e.left - t[0]) / -s;
+ ts[i + 20] = c && (e.top - t[1]) / c;
+ ts[i + 24] = s && (e.right - t[0]) / -s;
+ ts[i + 28] = c && (e.bottom - t[1]) / c;
+ ts[i + 32] = c && (e.left - t[0]) / -c;
+ ts[i + 36] = s && (e.top - t[1]) / -s;
+ ts[i + 40] = c && (e.right - t[0]) / -c;
+ ts[i + 44] = s && (e.bottom - t[1]) / -s;
+ ts[i + 48] = s && (e.left - t[0]) / s;
+ ts[i + 52] = c && (e.top - t[1]) / -c;
+ ts[i + 56] = s && (e.right - t[0]) / s;
+ ts[i + 60] = c && (e.bottom - t[1]) / -c;
+ });
+
+ var findPositiveMin = function findPositiveMin(ts, offset, count) {
+ var result = 0;
+
+ for (var i = 0; i < count; i++) {
+ var t = ts[offset++];
+
+ if (t > 0) {
+ result = result ? Math.min(t, result) : t;
+ }
+ }
+
+ return result;
+ };
+
+ var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
+ divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
+ divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
+ divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
+ divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
+
+ task._textDivProperties.set(div, divProperties);
+ }
+ }
+
+ function expandBounds(width, height, boxes) {
+ var bounds = boxes.map(function (box, i) {
+ return {
+ x1: box.left,
+ y1: box.top,
+ x2: box.right,
+ y2: box.bottom,
+ index: i,
+ x1New: undefined,
+ x2New: undefined
+ };
+ });
+ expandBoundsLTR(width, bounds);
+ var expanded = new Array(boxes.length);
+ bounds.forEach(function (b) {
+ var i = b.index;
+ expanded[i] = {
+ left: b.x1New,
+ top: 0,
+ right: b.x2New,
+ bottom: 0
+ };
+ });
+ boxes.map(function (box, i) {
+ var e = expanded[i],
+ b = bounds[i];
+ b.x1 = box.top;
+ b.y1 = width - e.right;
+ b.x2 = box.bottom;
+ b.y2 = width - e.left;
+ b.index = i;
+ b.x1New = undefined;
+ b.x2New = undefined;
+ });
+ expandBoundsLTR(height, bounds);
+ bounds.forEach(function (b) {
+ var i = b.index;
+ expanded[i].top = b.x1New;
+ expanded[i].bottom = b.x2New;
+ });
+ return expanded;
+ }
+
+ function expandBoundsLTR(width, bounds) {
+ bounds.sort(function (a, b) {
+ return a.x1 - b.x1 || a.index - b.index;
+ });
+ var fakeBoundary = {
+ x1: -Infinity,
+ y1: -Infinity,
+ x2: 0,
+ y2: Infinity,
+ index: -1,
+ x1New: 0,
+ x2New: 0
+ };
+ var horizon = [{
+ start: -Infinity,
+ end: Infinity,
+ boundary: fakeBoundary
+ }];
+ bounds.forEach(function (boundary) {
+ var i = 0;
+
+ while (i < horizon.length && horizon[i].end <= boundary.y1) {
+ i++;
+ }
+
+ var j = horizon.length - 1;
+
+ while (j >= 0 && horizon[j].start >= boundary.y2) {
+ j--;
+ }
+
+ var horizonPart, affectedBoundary;
+ var q,
+ k,
+ maxXNew = -Infinity;
+
+ for (q = i; q <= j; q++) {
+ horizonPart = horizon[q];
+ affectedBoundary = horizonPart.boundary;
+ var xNew;
+
+ if (affectedBoundary.x2 > boundary.x1) {
+ xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
+ } else if (affectedBoundary.x2New === undefined) {
+ xNew = (affectedBoundary.x2 + boundary.x1) / 2;
+ } else {
+ xNew = affectedBoundary.x2New;
+ }
+
+ if (xNew > maxXNew) {
+ maxXNew = xNew;
+ }
+ }
+
+ boundary.x1New = maxXNew;
+
+ for (q = i; q <= j; q++) {
+ horizonPart = horizon[q];
+ affectedBoundary = horizonPart.boundary;
+
+ if (affectedBoundary.x2New === undefined) {
+ if (affectedBoundary.x2 > boundary.x1) {
+ if (affectedBoundary.index > boundary.index) {
+ affectedBoundary.x2New = affectedBoundary.x2;
+ }
+ } else {
+ affectedBoundary.x2New = maxXNew;
+ }
+ } else if (affectedBoundary.x2New > maxXNew) {
+ affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
+ }
+ }
+
+ var changedHorizon = [],
+ lastBoundary = null;
+
+ for (q = i; q <= j; q++) {
+ horizonPart = horizon[q];
+ affectedBoundary = horizonPart.boundary;
+ var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
+
+ if (lastBoundary === useBoundary) {
+ changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
+ } else {
+ changedHorizon.push({
+ start: horizonPart.start,
+ end: horizonPart.end,
+ boundary: useBoundary
+ });
+ lastBoundary = useBoundary;
+ }
+ }
+
+ if (horizon[i].start < boundary.y1) {
+ changedHorizon[0].start = boundary.y1;
+ changedHorizon.unshift({
+ start: horizon[i].start,
+ end: boundary.y1,
+ boundary: horizon[i].boundary
+ });
+ }
+
+ if (boundary.y2 < horizon[j].end) {
+ changedHorizon[changedHorizon.length - 1].end = boundary.y2;
+ changedHorizon.push({
+ start: boundary.y2,
+ end: horizon[j].end,
+ boundary: horizon[j].boundary
+ });
+ }
+
+ for (q = i; q <= j; q++) {
+ horizonPart = horizon[q];
+ affectedBoundary = horizonPart.boundary;
+
+ if (affectedBoundary.x2New !== undefined) {
+ continue;
+ }
+
+ var used = false;
+
+ for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
+ used = horizon[k].boundary === affectedBoundary;
+ }
+
+ for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
+ used = horizon[k].boundary === affectedBoundary;
+ }
+
+ for (k = 0; !used && k < changedHorizon.length; k++) {
+ used = changedHorizon[k].boundary === affectedBoundary;
+ }
+
+ if (!used) {
+ affectedBoundary.x2New = maxXNew;
+ }
+ }
+
+ Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
+ });
+ horizon.forEach(function (horizonPart) {
+ var affectedBoundary = horizonPart.boundary;
+
+ if (affectedBoundary.x2New === undefined) {
+ affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
+ }
+ });
+ }
+
+ function TextLayerRenderTask(_ref) {
+ var _this = this;
+
+ var textContent = _ref.textContent,
+ textContentStream = _ref.textContentStream,
+ container = _ref.container,
+ viewport = _ref.viewport,
+ textDivs = _ref.textDivs,
+ textContentItemsStr = _ref.textContentItemsStr,
+ enhanceTextSelection = _ref.enhanceTextSelection;
+ this._textContent = textContent;
+ this._textContentStream = textContentStream;
+ this._container = container;
+ this._viewport = viewport;
+ this._textDivs = textDivs || [];
+ this._textContentItemsStr = textContentItemsStr || [];
+ this._enhanceTextSelection = !!enhanceTextSelection;
+ this._fontInspectorEnabled = !!(_global_scope["default"].FontInspector && _global_scope["default"].FontInspector.enabled);
+ this._reader = null;
+ this._layoutTextLastFontSize = null;
+ this._layoutTextLastFontFamily = null;
+ this._layoutTextCtx = null;
+ this._textDivProperties = new WeakMap();
+ this._renderingDone = false;
+ this._canceled = false;
+ this._capability = (0, _util.createPromiseCapability)();
+ this._renderTimer = null;
+ this._bounds = [];
+
+ this._capability.promise["finally"](function () {
+ if (_this._layoutTextCtx) {
+ _this._layoutTextCtx.canvas.width = 0;
+ _this._layoutTextCtx.canvas.height = 0;
+ _this._layoutTextCtx = null;
+ }
+ });
+ }
+
+ TextLayerRenderTask.prototype = {
+ get promise() {
+ return this._capability.promise;
+ },
+
+ cancel: function TextLayer_cancel() {
+ this._canceled = true;
+
+ if (this._reader) {
+ this._reader.cancel(new _util.AbortException('TextLayer task cancelled.'));
+
+ this._reader = null;
+ }
+
+ if (this._renderTimer !== null) {
+ clearTimeout(this._renderTimer);
+ this._renderTimer = null;
+ }
+
+ this._capability.reject(new Error('TextLayer task cancelled.'));
+ },
+ _processItems: function _processItems(items, styleCache) {
+ for (var i = 0, len = items.length; i < len; i++) {
+ this._textContentItemsStr.push(items[i].str);
+
+ appendText(this, items[i], styleCache);
+ }
+ },
+ _layoutText: function _layoutText(textDiv) {
+ var textLayerFrag = this._container;
+
+ var textDivProperties = this._textDivProperties.get(textDiv);
+
+ if (textDivProperties.isWhitespace) {
+ return;
+ }
+
+ var fontSize = textDiv.style.fontSize;
+ var fontFamily = textDiv.style.fontFamily;
+
+ if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
+ this._layoutTextCtx.font = fontSize + ' ' + fontFamily;
+ this._layoutTextLastFontSize = fontSize;
+ this._layoutTextLastFontFamily = fontFamily;
+ }
+
+ var width = this._layoutTextCtx.measureText(textDiv.textContent).width;
+
+ var transform = '';
+
+ if (textDivProperties.canvasWidth !== 0 && width > 0) {
+ textDivProperties.scale = textDivProperties.canvasWidth / width;
+ transform = "scaleX(".concat(textDivProperties.scale, ")");
+ }
+
+ if (textDivProperties.angle !== 0) {
+ transform = "rotate(".concat(textDivProperties.angle, "deg) ").concat(transform);
+ }
+
+ if (transform.length > 0) {
+ textDivProperties.originalTransform = transform;
+ textDiv.style.transform = transform;
+ }
+
+ this._textDivProperties.set(textDiv, textDivProperties);
+
+ textLayerFrag.appendChild(textDiv);
+ },
+ _render: function TextLayer_render(timeout) {
+ var _this2 = this;
+
+ var capability = (0, _util.createPromiseCapability)();
+ var styleCache = Object.create(null);
+ var canvas = document.createElement('canvas');
+ canvas.mozOpaque = true;
+ this._layoutTextCtx = canvas.getContext('2d', {
+ alpha: false
+ });
+
+ if (this._textContent) {
+ var textItems = this._textContent.items;
+ var textStyles = this._textContent.styles;
+
+ this._processItems(textItems, textStyles);
+
+ capability.resolve();
+ } else if (this._textContentStream) {
+ var pump = function pump() {
+ _this2._reader.read().then(function (_ref2) {
+ var value = _ref2.value,
+ done = _ref2.done;
+
+ if (done) {
+ capability.resolve();
+ return;
+ }
+
+ Object.assign(styleCache, value.styles);
+
+ _this2._processItems(value.items, styleCache);
+
+ pump();
+ }, capability.reject);
+ };
+
+ this._reader = this._textContentStream.getReader();
+ pump();
+ } else {
+ throw new Error('Neither "textContent" nor "textContentStream"' + ' parameters specified.');
+ }
+
+ capability.promise.then(function () {
+ styleCache = null;
+
+ if (!timeout) {
+ render(_this2);
+ } else {
+ _this2._renderTimer = setTimeout(function () {
+ render(_this2);
+ _this2._renderTimer = null;
+ }, timeout);
+ }
+ }, this._capability.reject);
+ },
+ expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
+ if (!this._enhanceTextSelection || !this._renderingDone) {
+ return;
+ }
+
+ if (this._bounds !== null) {
+ expand(this);
+ this._bounds = null;
+ }
+
+ for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
+ var div = this._textDivs[i];
+
+ var divProperties = this._textDivProperties.get(div);
+
+ if (divProperties.isWhitespace) {
+ continue;
+ }
+
+ if (expandDivs) {
+ var transform = '',
+ padding = '';
+
+ if (divProperties.scale !== 1) {
+ transform = 'scaleX(' + divProperties.scale + ')';
+ }
+
+ if (divProperties.angle !== 0) {
+ transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
+ }
+
+ if (divProperties.paddingLeft !== 0) {
+ padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
+ transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
+ }
+
+ if (divProperties.paddingTop !== 0) {
+ padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
+ transform += ' translateY(' + -divProperties.paddingTop + 'px)';
+ }
+
+ if (divProperties.paddingRight !== 0) {
+ padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
+ }
+
+ if (divProperties.paddingBottom !== 0) {
+ padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
+ }
+
+ if (padding !== '') {
+ div.setAttribute('style', divProperties.style + padding);
+ }
+
+ if (transform !== '') {
+ div.style.transform = transform;
+ }
+ } else {
+ div.style.padding = 0;
+ div.style.transform = divProperties.originalTransform || '';
+ }
+ }
+ }
+ };
+
+ function renderTextLayer(renderParameters) {
+ var task = new TextLayerRenderTask({
+ textContent: renderParameters.textContent,
+ textContentStream: renderParameters.textContentStream,
+ container: renderParameters.container,
+ viewport: renderParameters.viewport,
+ textDivs: renderParameters.textDivs,
+ textContentItemsStr: renderParameters.textContentItemsStr,
+ enhanceTextSelection: renderParameters.enhanceTextSelection
+ });
+
+ task._render(renderParameters.timeout);
+
+ return task;
+ }
+
+ return renderTextLayer;
+}();
+
+exports.renderTextLayer = renderTextLayer;
+
+/***/ }),
+/* 163 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.AnnotationLayer = void 0;
+
+var _display_utils = __w_pdfjs_require__(151);
+
+var _util = __w_pdfjs_require__(1);
+
+function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
+
+function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
+
+function _typeof(obj) { 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); }
+
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
+
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
+
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var AnnotationElementFactory =
+/*#__PURE__*/
+function () {
+ function AnnotationElementFactory() {
+ _classCallCheck(this, AnnotationElementFactory);
+ }
+
+ _createClass(AnnotationElementFactory, null, [{
+ key: "create",
+ value: function create(parameters) {
+ var subtype = parameters.data.annotationType;
+
+ switch (subtype) {
+ case _util.AnnotationType.LINK:
+ return new LinkAnnotationElement(parameters);
+
+ case _util.AnnotationType.TEXT:
+ return new TextAnnotationElement(parameters);
+
+ case _util.AnnotationType.WIDGET:
+ var fieldType = parameters.data.fieldType;
+
+ switch (fieldType) {
+ case 'Tx':
+ return new TextWidgetAnnotationElement(parameters);
+
+ case 'Btn':
+ if (parameters.data.radioButton) {
+ return new RadioButtonWidgetAnnotationElement(parameters);
+ } else if (parameters.data.checkBox) {
+ return new CheckboxWidgetAnnotationElement(parameters);
+ }
+
+ return new PushButtonWidgetAnnotationElement(parameters);
+
+ case 'Ch':
+ return new ChoiceWidgetAnnotationElement(parameters);
+ }
+
+ return new WidgetAnnotationElement(parameters);
+
+ case _util.AnnotationType.POPUP:
+ return new PopupAnnotationElement(parameters);
+
+ case _util.AnnotationType.FREETEXT:
+ return new FreeTextAnnotationElement(parameters);
+
+ case _util.AnnotationType.LINE:
+ return new LineAnnotationElement(parameters);
+
+ case _util.AnnotationType.SQUARE:
+ return new SquareAnnotationElement(parameters);
+
+ case _util.AnnotationType.CIRCLE:
+ return new CircleAnnotationElement(parameters);
+
+ case _util.AnnotationType.POLYLINE:
+ return new PolylineAnnotationElement(parameters);
+
+ case _util.AnnotationType.CARET:
+ return new CaretAnnotationElement(parameters);
+
+ case _util.AnnotationType.INK:
+ return new InkAnnotationElement(parameters);
+
+ case _util.AnnotationType.POLYGON:
+ return new PolygonAnnotationElement(parameters);
+
+ case _util.AnnotationType.HIGHLIGHT:
+ return new HighlightAnnotationElement(parameters);
+
+ case _util.AnnotationType.UNDERLINE:
+ return new UnderlineAnnotationElement(parameters);
+
+ case _util.AnnotationType.SQUIGGLY:
+ return new SquigglyAnnotationElement(parameters);
+
+ case _util.AnnotationType.STRIKEOUT:
+ return new StrikeOutAnnotationElement(parameters);
+
+ case _util.AnnotationType.STAMP:
+ return new StampAnnotationElement(parameters);
+
+ case _util.AnnotationType.FILEATTACHMENT:
+ return new FileAttachmentAnnotationElement(parameters);
+
+ default:
+ return new AnnotationElement(parameters);
+ }
+ }
+ }]);
+
+ return AnnotationElementFactory;
+}();
+
+var AnnotationElement =
+/*#__PURE__*/
+function () {
+ function AnnotationElement(parameters) {
+ var isRenderable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
+ var ignoreBorder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
+ _classCallCheck(this, AnnotationElement);
+
+ this.isRenderable = isRenderable;
+ this.data = parameters.data;
+ this.layer = parameters.layer;
+ this.page = parameters.page;
+ this.viewport = parameters.viewport;
+ this.linkService = parameters.linkService;
+ this.downloadManager = parameters.downloadManager;
+ this.imageResourcesPath = parameters.imageResourcesPath;
+ this.renderInteractiveForms = parameters.renderInteractiveForms;
+ this.svgFactory = parameters.svgFactory;
+
+ if (isRenderable) {
+ this.container = this._createContainer(ignoreBorder);
+ }
+ }
+
+ _createClass(AnnotationElement, [{
+ key: "_createContainer",
+ value: function _createContainer() {
+ var ignoreBorder = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
+ var data = this.data,
+ page = this.page,
+ viewport = this.viewport;
+ var container = document.createElement('section');
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ container.setAttribute('data-annotation-id', data.id);
+
+ var rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
+
+ container.style.transform = 'matrix(' + viewport.transform.join(',') + ')';
+ container.style.transformOrigin = -rect[0] + 'px ' + -rect[1] + 'px';
+
+ if (!ignoreBorder && data.borderStyle.width > 0) {
+ container.style.borderWidth = data.borderStyle.width + 'px';
+
+ if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
+ width = width - 2 * data.borderStyle.width;
+ height = height - 2 * data.borderStyle.width;
+ }
+
+ var horizontalRadius = data.borderStyle.horizontalCornerRadius;
+ var verticalRadius = data.borderStyle.verticalCornerRadius;
+
+ if (horizontalRadius > 0 || verticalRadius > 0) {
+ var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
+ container.style.borderRadius = radius;
+ }
+
+ switch (data.borderStyle.style) {
+ case _util.AnnotationBorderStyleType.SOLID:
+ container.style.borderStyle = 'solid';
+ break;
+
+ case _util.AnnotationBorderStyleType.DASHED:
+ container.style.borderStyle = 'dashed';
+ break;
+
+ case _util.AnnotationBorderStyleType.BEVELED:
+ (0, _util.warn)('Unimplemented border style: beveled');
+ break;
+
+ case _util.AnnotationBorderStyleType.INSET:
+ (0, _util.warn)('Unimplemented border style: inset');
+ break;
+
+ case _util.AnnotationBorderStyleType.UNDERLINE:
+ container.style.borderBottomStyle = 'solid';
+ break;
+
+ default:
+ break;
+ }
+
+ if (data.color) {
+ container.style.borderColor = _util.Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
+ } else {
+ container.style.borderWidth = 0;
+ }
+ }
+
+ container.style.left = rect[0] + 'px';
+ container.style.top = rect[1] + 'px';
+ container.style.width = width + 'px';
+ container.style.height = height + 'px';
+ return container;
+ }
+ }, {
+ key: "_createPopup",
+ value: function _createPopup(container, trigger, data) {
+ if (!trigger) {
+ trigger = document.createElement('div');
+ trigger.style.height = container.style.height;
+ trigger.style.width = container.style.width;
+ container.appendChild(trigger);
+ }
+
+ var popupElement = new PopupElement({
+ container: container,
+ trigger: trigger,
+ color: data.color,
+ title: data.title,
+ modificationDate: data.modificationDate,
+ contents: data.contents,
+ hideWrapper: true
+ });
+ var popup = popupElement.render();
+ popup.style.left = container.style.width;
+ container.appendChild(popup);
+ }
+ }, {
+ key: "render",
+ value: function render() {
+ (0, _util.unreachable)('Abstract method `AnnotationElement.render` called');
+ }
+ }]);
+
+ return AnnotationElement;
+}();
+
+var LinkAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement) {
+ _inherits(LinkAnnotationElement, _AnnotationElement);
+
+ function LinkAnnotationElement(parameters) {
+ _classCallCheck(this, LinkAnnotationElement);
+
+ var isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action);
+ return _possibleConstructorReturn(this, _getPrototypeOf(LinkAnnotationElement).call(this, parameters, isRenderable));
+ }
+
+ _createClass(LinkAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'linkAnnotation';
+ var data = this.data,
+ linkService = this.linkService;
+ var link = document.createElement('a');
+ (0, _display_utils.addLinkAttributes)(link, {
+ url: data.url,
+ target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
+ rel: linkService.externalLinkRel
+ });
+
+ if (!data.url) {
+ if (data.action) {
+ this._bindNamedAction(link, data.action);
+ } else {
+ this._bindLink(link, data.dest);
+ }
+ }
+
+ this.container.appendChild(link);
+ return this.container;
+ }
+ }, {
+ key: "_bindLink",
+ value: function _bindLink(link, destination) {
+ var _this = this;
+
+ link.href = this.linkService.getDestinationHash(destination);
+
+ link.onclick = function () {
+ if (destination) {
+ _this.linkService.navigateTo(destination);
+ }
+
+ return false;
+ };
+
+ if (destination) {
+ link.className = 'internalLink';
+ }
+ }
+ }, {
+ key: "_bindNamedAction",
+ value: function _bindNamedAction(link, action) {
+ var _this2 = this;
+
+ link.href = this.linkService.getAnchorUrl('');
+
+ link.onclick = function () {
+ _this2.linkService.executeNamedAction(action);
+
+ return false;
+ };
+
+ link.className = 'internalLink';
+ }
+ }]);
+
+ return LinkAnnotationElement;
+}(AnnotationElement);
+
+var TextAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement2) {
+ _inherits(TextAnnotationElement, _AnnotationElement2);
+
+ function TextAnnotationElement(parameters) {
+ _classCallCheck(this, TextAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(TextAnnotationElement).call(this, parameters, isRenderable));
+ }
+
+ _createClass(TextAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'textAnnotation';
+ var image = document.createElement('img');
+ image.style.height = this.container.style.height;
+ image.style.width = this.container.style.width;
+ image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
+ image.alt = '[{{type}} Annotation]';
+ image.dataset.l10nId = 'text_annotation_type';
+ image.dataset.l10nArgs = JSON.stringify({
+ type: this.data.name
+ });
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, image, this.data);
+ }
+
+ this.container.appendChild(image);
+ return this.container;
+ }
+ }]);
+
+ return TextAnnotationElement;
+}(AnnotationElement);
+
+var WidgetAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement3) {
+ _inherits(WidgetAnnotationElement, _AnnotationElement3);
+
+ function WidgetAnnotationElement() {
+ _classCallCheck(this, WidgetAnnotationElement);
+
+ return _possibleConstructorReturn(this, _getPrototypeOf(WidgetAnnotationElement).apply(this, arguments));
+ }
+
+ _createClass(WidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ return this.container;
+ }
+ }]);
+
+ return WidgetAnnotationElement;
+}(AnnotationElement);
+
+var TextWidgetAnnotationElement =
+/*#__PURE__*/
+function (_WidgetAnnotationElem) {
+ _inherits(TextWidgetAnnotationElement, _WidgetAnnotationElem);
+
+ function TextWidgetAnnotationElement(parameters) {
+ _classCallCheck(this, TextWidgetAnnotationElement);
+
+ var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
+ return _possibleConstructorReturn(this, _getPrototypeOf(TextWidgetAnnotationElement).call(this, parameters, isRenderable));
+ }
+
+ _createClass(TextWidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ var TEXT_ALIGNMENT = ['left', 'center', 'right'];
+ this.container.className = 'textWidgetAnnotation';
+ var element = null;
+
+ if (this.renderInteractiveForms) {
+ if (this.data.multiLine) {
+ element = document.createElement('textarea');
+ element.textContent = this.data.fieldValue;
+ } else {
+ element = document.createElement('input');
+ element.type = 'text';
+ element.setAttribute('value', this.data.fieldValue);
+ }
+
+ element.disabled = this.data.readOnly;
+
+ if (this.data.maxLen !== null) {
+ element.maxLength = this.data.maxLen;
+ }
+
+ if (this.data.comb) {
+ var fieldWidth = this.data.rect[2] - this.data.rect[0];
+ var combWidth = fieldWidth / this.data.maxLen;
+ element.classList.add('comb');
+ element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
+ }
+ } else {
+ element = document.createElement('div');
+ element.textContent = this.data.fieldValue;
+ element.style.verticalAlign = 'middle';
+ element.style.display = 'table-cell';
+ var font = null;
+
+ if (this.data.fontRefName && this.page.commonObjs.has(this.data.fontRefName)) {
+ font = this.page.commonObjs.get(this.data.fontRefName);
+ }
+
+ this._setTextStyle(element, font);
+ }
+
+ if (this.data.textAlignment !== null) {
+ element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
+ }
+
+ this.container.appendChild(element);
+ return this.container;
+ }
+ }, {
+ key: "_setTextStyle",
+ value: function _setTextStyle(element, font) {
+ var style = element.style;
+ style.fontSize = this.data.fontSize + 'px';
+ style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
+
+ if (!font) {
+ return;
+ }
+
+ style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
+ style.fontStyle = font.italic ? 'italic' : 'normal';
+ var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
+ var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
+ style.fontFamily = fontFamily + fallbackName;
+ }
+ }]);
+
+ return TextWidgetAnnotationElement;
+}(WidgetAnnotationElement);
+
+var CheckboxWidgetAnnotationElement =
+/*#__PURE__*/
+function (_WidgetAnnotationElem2) {
+ _inherits(CheckboxWidgetAnnotationElement, _WidgetAnnotationElem2);
+
+ function CheckboxWidgetAnnotationElement(parameters) {
+ _classCallCheck(this, CheckboxWidgetAnnotationElement);
+
+ return _possibleConstructorReturn(this, _getPrototypeOf(CheckboxWidgetAnnotationElement).call(this, parameters, parameters.renderInteractiveForms));
+ }
+
+ _createClass(CheckboxWidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'buttonWidgetAnnotation checkBox';
+ var element = document.createElement('input');
+ element.disabled = this.data.readOnly;
+ element.type = 'checkbox';
+
+ if (this.data.fieldValue && this.data.fieldValue !== 'Off') {
+ element.setAttribute('checked', true);
+ }
+
+ this.container.appendChild(element);
+ return this.container;
+ }
+ }]);
+
+ return CheckboxWidgetAnnotationElement;
+}(WidgetAnnotationElement);
+
+var RadioButtonWidgetAnnotationElement =
+/*#__PURE__*/
+function (_WidgetAnnotationElem3) {
+ _inherits(RadioButtonWidgetAnnotationElement, _WidgetAnnotationElem3);
+
+ function RadioButtonWidgetAnnotationElement(parameters) {
+ _classCallCheck(this, RadioButtonWidgetAnnotationElement);
+
+ return _possibleConstructorReturn(this, _getPrototypeOf(RadioButtonWidgetAnnotationElement).call(this, parameters, parameters.renderInteractiveForms));
+ }
+
+ _createClass(RadioButtonWidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'buttonWidgetAnnotation radioButton';
+ var element = document.createElement('input');
+ element.disabled = this.data.readOnly;
+ element.type = 'radio';
+ element.name = this.data.fieldName;
+
+ if (this.data.fieldValue === this.data.buttonValue) {
+ element.setAttribute('checked', true);
+ }
+
+ this.container.appendChild(element);
+ return this.container;
+ }
+ }]);
+
+ return RadioButtonWidgetAnnotationElement;
+}(WidgetAnnotationElement);
+
+var PushButtonWidgetAnnotationElement =
+/*#__PURE__*/
+function (_LinkAnnotationElemen) {
+ _inherits(PushButtonWidgetAnnotationElement, _LinkAnnotationElemen);
+
+ function PushButtonWidgetAnnotationElement() {
+ _classCallCheck(this, PushButtonWidgetAnnotationElement);
+
+ return _possibleConstructorReturn(this, _getPrototypeOf(PushButtonWidgetAnnotationElement).apply(this, arguments));
+ }
+
+ _createClass(PushButtonWidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ var container = _get(_getPrototypeOf(PushButtonWidgetAnnotationElement.prototype), "render", this).call(this);
+
+ container.className = 'buttonWidgetAnnotation pushButton';
+ return container;
+ }
+ }]);
+
+ return PushButtonWidgetAnnotationElement;
+}(LinkAnnotationElement);
+
+var ChoiceWidgetAnnotationElement =
+/*#__PURE__*/
+function (_WidgetAnnotationElem4) {
+ _inherits(ChoiceWidgetAnnotationElement, _WidgetAnnotationElem4);
+
+ function ChoiceWidgetAnnotationElement(parameters) {
+ _classCallCheck(this, ChoiceWidgetAnnotationElement);
+
+ return _possibleConstructorReturn(this, _getPrototypeOf(ChoiceWidgetAnnotationElement).call(this, parameters, parameters.renderInteractiveForms));
+ }
+
+ _createClass(ChoiceWidgetAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'choiceWidgetAnnotation';
+ var selectElement = document.createElement('select');
+ selectElement.disabled = this.data.readOnly;
+
+ if (!this.data.combo) {
+ selectElement.size = this.data.options.length;
+
+ if (this.data.multiSelect) {
+ selectElement.multiple = true;
+ }
+ }
+
+ for (var i = 0, ii = this.data.options.length; i < ii; i++) {
+ var option = this.data.options[i];
+ var optionElement = document.createElement('option');
+ optionElement.textContent = option.displayValue;
+ optionElement.value = option.exportValue;
+
+ if (this.data.fieldValue.includes(option.displayValue)) {
+ optionElement.setAttribute('selected', true);
+ }
+
+ selectElement.appendChild(optionElement);
+ }
+
+ this.container.appendChild(selectElement);
+ return this.container;
+ }
+ }]);
+
+ return ChoiceWidgetAnnotationElement;
+}(WidgetAnnotationElement);
+
+var PopupAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement4) {
+ _inherits(PopupAnnotationElement, _AnnotationElement4);
+
+ function PopupAnnotationElement(parameters) {
+ _classCallCheck(this, PopupAnnotationElement);
+
+ var isRenderable = !!(parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(PopupAnnotationElement).call(this, parameters, isRenderable));
+ }
+
+ _createClass(PopupAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ var IGNORE_TYPES = ['Line', 'Square', 'Circle', 'PolyLine', 'Polygon', 'Ink'];
+ this.container.className = 'popupAnnotation';
+
+ if (IGNORE_TYPES.includes(this.data.parentType)) {
+ return this.container;
+ }
+
+ var selector = '[data-annotation-id="' + this.data.parentId + '"]';
+ var parentElement = this.layer.querySelector(selector);
+
+ if (!parentElement) {
+ return this.container;
+ }
+
+ var popup = new PopupElement({
+ container: this.container,
+ trigger: parentElement,
+ color: this.data.color,
+ title: this.data.title,
+ modificationDate: this.data.modificationDate,
+ contents: this.data.contents
+ });
+ var parentLeft = parseFloat(parentElement.style.left);
+ var parentWidth = parseFloat(parentElement.style.width);
+ this.container.style.transformOrigin = -(parentLeft + parentWidth) + 'px -' + parentElement.style.top;
+ this.container.style.left = parentLeft + parentWidth + 'px';
+ this.container.appendChild(popup.render());
+ return this.container;
+ }
+ }]);
+
+ return PopupAnnotationElement;
+}(AnnotationElement);
+
+var PopupElement =
+/*#__PURE__*/
+function () {
+ function PopupElement(parameters) {
+ _classCallCheck(this, PopupElement);
+
+ this.container = parameters.container;
+ this.trigger = parameters.trigger;
+ this.color = parameters.color;
+ this.title = parameters.title;
+ this.modificationDate = parameters.modificationDate;
+ this.contents = parameters.contents;
+ this.hideWrapper = parameters.hideWrapper || false;
+ this.pinned = false;
+ }
+
+ _createClass(PopupElement, [{
+ key: "render",
+ value: function render() {
+ var BACKGROUND_ENLIGHT = 0.7;
+ var wrapper = document.createElement('div');
+ wrapper.className = 'popupWrapper';
+ this.hideElement = this.hideWrapper ? wrapper : this.container;
+ this.hideElement.setAttribute('hidden', true);
+ var popup = document.createElement('div');
+ popup.className = 'popup';
+ var color = this.color;
+
+ if (color) {
+ var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
+ var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
+ var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
+ popup.style.backgroundColor = _util.Util.makeCssRgb(r | 0, g | 0, b | 0);
+ }
+
+ var title = document.createElement('h1');
+ title.textContent = this.title;
+ popup.appendChild(title);
+
+ var dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
+
+ if (dateObject) {
+ var modificationDate = document.createElement('span');
+ modificationDate.textContent = '{{date}}, {{time}}';
+ modificationDate.dataset.l10nId = 'annotation_date_string';
+ modificationDate.dataset.l10nArgs = JSON.stringify({
+ date: dateObject.toLocaleDateString(),
+ time: dateObject.toLocaleTimeString()
+ });
+ popup.appendChild(modificationDate);
+ }
+
+ var contents = this._formatContents(this.contents);
+
+ popup.appendChild(contents);
+ this.trigger.addEventListener('click', this._toggle.bind(this));
+ this.trigger.addEventListener('mouseover', this._show.bind(this, false));
+ this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
+ popup.addEventListener('click', this._hide.bind(this, true));
+ wrapper.appendChild(popup);
+ return wrapper;
+ }
+ }, {
+ key: "_formatContents",
+ value: function _formatContents(contents) {
+ var p = document.createElement('p');
+ var lines = contents.split(/(?:\r\n?|\n)/);
+
+ for (var i = 0, ii = lines.length; i < ii; ++i) {
+ var line = lines[i];
+ p.appendChild(document.createTextNode(line));
+
+ if (i < ii - 1) {
+ p.appendChild(document.createElement('br'));
+ }
+ }
+
+ return p;
+ }
+ }, {
+ key: "_toggle",
+ value: function _toggle() {
+ if (this.pinned) {
+ this._hide(true);
+ } else {
+ this._show(true);
+ }
+ }
+ }, {
+ key: "_show",
+ value: function _show() {
+ var pin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
+
+ if (pin) {
+ this.pinned = true;
+ }
+
+ if (this.hideElement.hasAttribute('hidden')) {
+ this.hideElement.removeAttribute('hidden');
+ this.container.style.zIndex += 1;
+ }
+ }
+ }, {
+ key: "_hide",
+ value: function _hide() {
+ var unpin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+
+ if (unpin) {
+ this.pinned = false;
+ }
+
+ if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
+ this.hideElement.setAttribute('hidden', true);
+ this.container.style.zIndex -= 1;
+ }
+ }
+ }]);
+
+ return PopupElement;
+}();
+
+var FreeTextAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement5) {
+ _inherits(FreeTextAnnotationElement, _AnnotationElement5);
+
+ function FreeTextAnnotationElement(parameters) {
+ _classCallCheck(this, FreeTextAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(FreeTextAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(FreeTextAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'freeTextAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return FreeTextAnnotationElement;
+}(AnnotationElement);
+
+var LineAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement6) {
+ _inherits(LineAnnotationElement, _AnnotationElement6);
+
+ function LineAnnotationElement(parameters) {
+ _classCallCheck(this, LineAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(LineAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(LineAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'lineAnnotation';
+ var data = this.data;
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ var svg = this.svgFactory.create(width, height);
+ var line = this.svgFactory.createElement('svg:line');
+ line.setAttribute('x1', data.rect[2] - data.lineCoordinates[0]);
+ line.setAttribute('y1', data.rect[3] - data.lineCoordinates[1]);
+ line.setAttribute('x2', data.rect[2] - data.lineCoordinates[2]);
+ line.setAttribute('y2', data.rect[3] - data.lineCoordinates[3]);
+ line.setAttribute('stroke-width', data.borderStyle.width);
+ line.setAttribute('stroke', 'transparent');
+ svg.appendChild(line);
+ this.container.append(svg);
+
+ this._createPopup(this.container, line, data);
+
+ return this.container;
+ }
+ }]);
+
+ return LineAnnotationElement;
+}(AnnotationElement);
+
+var SquareAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement7) {
+ _inherits(SquareAnnotationElement, _AnnotationElement7);
+
+ function SquareAnnotationElement(parameters) {
+ _classCallCheck(this, SquareAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(SquareAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(SquareAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'squareAnnotation';
+ var data = this.data;
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ var svg = this.svgFactory.create(width, height);
+ var borderWidth = data.borderStyle.width;
+ var square = this.svgFactory.createElement('svg:rect');
+ square.setAttribute('x', borderWidth / 2);
+ square.setAttribute('y', borderWidth / 2);
+ square.setAttribute('width', width - borderWidth);
+ square.setAttribute('height', height - borderWidth);
+ square.setAttribute('stroke-width', borderWidth);
+ square.setAttribute('stroke', 'transparent');
+ square.setAttribute('fill', 'none');
+ svg.appendChild(square);
+ this.container.append(svg);
+
+ this._createPopup(this.container, square, data);
+
+ return this.container;
+ }
+ }]);
+
+ return SquareAnnotationElement;
+}(AnnotationElement);
+
+var CircleAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement8) {
+ _inherits(CircleAnnotationElement, _AnnotationElement8);
+
+ function CircleAnnotationElement(parameters) {
+ _classCallCheck(this, CircleAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(CircleAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(CircleAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'circleAnnotation';
+ var data = this.data;
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ var svg = this.svgFactory.create(width, height);
+ var borderWidth = data.borderStyle.width;
+ var circle = this.svgFactory.createElement('svg:ellipse');
+ circle.setAttribute('cx', width / 2);
+ circle.setAttribute('cy', height / 2);
+ circle.setAttribute('rx', width / 2 - borderWidth / 2);
+ circle.setAttribute('ry', height / 2 - borderWidth / 2);
+ circle.setAttribute('stroke-width', borderWidth);
+ circle.setAttribute('stroke', 'transparent');
+ circle.setAttribute('fill', 'none');
+ svg.appendChild(circle);
+ this.container.append(svg);
+
+ this._createPopup(this.container, circle, data);
+
+ return this.container;
+ }
+ }]);
+
+ return CircleAnnotationElement;
+}(AnnotationElement);
+
+var PolylineAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement9) {
+ _inherits(PolylineAnnotationElement, _AnnotationElement9);
+
+ function PolylineAnnotationElement(parameters) {
+ var _this3;
+
+ _classCallCheck(this, PolylineAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ _this3 = _possibleConstructorReturn(this, _getPrototypeOf(PolylineAnnotationElement).call(this, parameters, isRenderable, true));
+ _this3.containerClassName = 'polylineAnnotation';
+ _this3.svgElementName = 'svg:polyline';
+ return _this3;
+ }
+
+ _createClass(PolylineAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = this.containerClassName;
+ var data = this.data;
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ var svg = this.svgFactory.create(width, height);
+ var vertices = data.vertices;
+ var points = [];
+
+ for (var i = 0, ii = vertices.length; i < ii; i++) {
+ var x = vertices[i].x - data.rect[0];
+ var y = data.rect[3] - vertices[i].y;
+ points.push(x + ',' + y);
+ }
+
+ points = points.join(' ');
+ var borderWidth = data.borderStyle.width;
+ var polyline = this.svgFactory.createElement(this.svgElementName);
+ polyline.setAttribute('points', points);
+ polyline.setAttribute('stroke-width', borderWidth);
+ polyline.setAttribute('stroke', 'transparent');
+ polyline.setAttribute('fill', 'none');
+ svg.appendChild(polyline);
+ this.container.append(svg);
+
+ this._createPopup(this.container, polyline, data);
+
+ return this.container;
+ }
+ }]);
+
+ return PolylineAnnotationElement;
+}(AnnotationElement);
+
+var PolygonAnnotationElement =
+/*#__PURE__*/
+function (_PolylineAnnotationEl) {
+ _inherits(PolygonAnnotationElement, _PolylineAnnotationEl);
+
+ function PolygonAnnotationElement(parameters) {
+ var _this4;
+
+ _classCallCheck(this, PolygonAnnotationElement);
+
+ _this4 = _possibleConstructorReturn(this, _getPrototypeOf(PolygonAnnotationElement).call(this, parameters));
+ _this4.containerClassName = 'polygonAnnotation';
+ _this4.svgElementName = 'svg:polygon';
+ return _this4;
+ }
+
+ return PolygonAnnotationElement;
+}(PolylineAnnotationElement);
+
+var CaretAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement10) {
+ _inherits(CaretAnnotationElement, _AnnotationElement10);
+
+ function CaretAnnotationElement(parameters) {
+ _classCallCheck(this, CaretAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(CaretAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(CaretAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'caretAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return CaretAnnotationElement;
+}(AnnotationElement);
+
+var InkAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement11) {
+ _inherits(InkAnnotationElement, _AnnotationElement11);
+
+ function InkAnnotationElement(parameters) {
+ var _this5;
+
+ _classCallCheck(this, InkAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ _this5 = _possibleConstructorReturn(this, _getPrototypeOf(InkAnnotationElement).call(this, parameters, isRenderable, true));
+ _this5.containerClassName = 'inkAnnotation';
+ _this5.svgElementName = 'svg:polyline';
+ return _this5;
+ }
+
+ _createClass(InkAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = this.containerClassName;
+ var data = this.data;
+ var width = data.rect[2] - data.rect[0];
+ var height = data.rect[3] - data.rect[1];
+ var svg = this.svgFactory.create(width, height);
+ var inkLists = data.inkLists;
+
+ for (var i = 0, ii = inkLists.length; i < ii; i++) {
+ var inkList = inkLists[i];
+ var points = [];
+
+ for (var j = 0, jj = inkList.length; j < jj; j++) {
+ var x = inkList[j].x - data.rect[0];
+ var y = data.rect[3] - inkList[j].y;
+ points.push(x + ',' + y);
+ }
+
+ points = points.join(' ');
+ var borderWidth = data.borderStyle.width;
+ var polyline = this.svgFactory.createElement(this.svgElementName);
+ polyline.setAttribute('points', points);
+ polyline.setAttribute('stroke-width', borderWidth);
+ polyline.setAttribute('stroke', 'transparent');
+ polyline.setAttribute('fill', 'none');
+
+ this._createPopup(this.container, polyline, data);
+
+ svg.appendChild(polyline);
+ }
+
+ this.container.append(svg);
+ return this.container;
+ }
+ }]);
+
+ return InkAnnotationElement;
+}(AnnotationElement);
+
+var HighlightAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement12) {
+ _inherits(HighlightAnnotationElement, _AnnotationElement12);
+
+ function HighlightAnnotationElement(parameters) {
+ _classCallCheck(this, HighlightAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(HighlightAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(HighlightAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'highlightAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return HighlightAnnotationElement;
+}(AnnotationElement);
+
+var UnderlineAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement13) {
+ _inherits(UnderlineAnnotationElement, _AnnotationElement13);
+
+ function UnderlineAnnotationElement(parameters) {
+ _classCallCheck(this, UnderlineAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(UnderlineAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(UnderlineAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'underlineAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return UnderlineAnnotationElement;
+}(AnnotationElement);
+
+var SquigglyAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement14) {
+ _inherits(SquigglyAnnotationElement, _AnnotationElement14);
+
+ function SquigglyAnnotationElement(parameters) {
+ _classCallCheck(this, SquigglyAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(SquigglyAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(SquigglyAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'squigglyAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return SquigglyAnnotationElement;
+}(AnnotationElement);
+
+var StrikeOutAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement15) {
+ _inherits(StrikeOutAnnotationElement, _AnnotationElement15);
+
+ function StrikeOutAnnotationElement(parameters) {
+ _classCallCheck(this, StrikeOutAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(StrikeOutAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(StrikeOutAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'strikeoutAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return StrikeOutAnnotationElement;
+}(AnnotationElement);
+
+var StampAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement16) {
+ _inherits(StampAnnotationElement, _AnnotationElement16);
+
+ function StampAnnotationElement(parameters) {
+ _classCallCheck(this, StampAnnotationElement);
+
+ var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+ return _possibleConstructorReturn(this, _getPrototypeOf(StampAnnotationElement).call(this, parameters, isRenderable, true));
+ }
+
+ _createClass(StampAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'stampAnnotation';
+
+ if (!this.data.hasPopup) {
+ this._createPopup(this.container, null, this.data);
+ }
+
+ return this.container;
+ }
+ }]);
+
+ return StampAnnotationElement;
+}(AnnotationElement);
+
+var FileAttachmentAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement17) {
+ _inherits(FileAttachmentAnnotationElement, _AnnotationElement17);
+
+ function FileAttachmentAnnotationElement(parameters) {
+ var _this6;
+
+ _classCallCheck(this, FileAttachmentAnnotationElement);
+
+ _this6 = _possibleConstructorReturn(this, _getPrototypeOf(FileAttachmentAnnotationElement).call(this, parameters, true));
+ var _this6$data$file = _this6.data.file,
+ filename = _this6$data$file.filename,
+ content = _this6$data$file.content;
+ _this6.filename = (0, _display_utils.getFilenameFromUrl)(filename);
+ _this6.content = content;
+
+ if (_this6.linkService.eventBus) {
+ _this6.linkService.eventBus.dispatch('fileattachmentannotation', {
+ source: _assertThisInitialized(_this6),
+ id: (0, _util.stringToPDFString)(filename),
+ filename: filename,
+ content: content
+ });
+ }
+
+ return _this6;
+ }
+
+ _createClass(FileAttachmentAnnotationElement, [{
+ key: "render",
+ value: function render() {
+ this.container.className = 'fileAttachmentAnnotation';
+ var trigger = document.createElement('div');
+ trigger.style.height = this.container.style.height;
+ trigger.style.width = this.container.style.width;
+ trigger.addEventListener('dblclick', this._download.bind(this));
+
+ if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
+ this._createPopup(this.container, trigger, this.data);
+ }
+
+ this.container.appendChild(trigger);
+ return this.container;
+ }
+ }, {
+ key: "_download",
+ value: function _download() {
+ if (!this.downloadManager) {
+ (0, _util.warn)('Download cannot be started due to unavailable download manager');
+ return;
+ }
+
+ this.downloadManager.downloadData(this.content, this.filename, '');
+ }
+ }]);
+
+ return FileAttachmentAnnotationElement;
+}(AnnotationElement);
+
+var AnnotationLayer =
+/*#__PURE__*/
+function () {
+ function AnnotationLayer() {
+ _classCallCheck(this, AnnotationLayer);
+ }
+
+ _createClass(AnnotationLayer, null, [{
+ key: "render",
+ value: function render(parameters) {
+ for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
+ var data = parameters.annotations[i];
+
+ if (!data) {
+ continue;
+ }
+
+ var element = AnnotationElementFactory.create({
+ data: data,
+ layer: parameters.div,
+ page: parameters.page,
+ viewport: parameters.viewport,
+ linkService: parameters.linkService,
+ downloadManager: parameters.downloadManager,
+ imageResourcesPath: parameters.imageResourcesPath || '',
+ renderInteractiveForms: parameters.renderInteractiveForms || false,
+ svgFactory: new _display_utils.DOMSVGFactory()
+ });
+
+ if (element.isRenderable) {
+ parameters.div.appendChild(element.render());
+ }
+ }
+ }
+ }, {
+ key: "update",
+ value: function update(parameters) {
+ for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
+ var data = parameters.annotations[i];
+ var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
+
+ if (element) {
+ element.style.transform = 'matrix(' + parameters.viewport.transform.join(',') + ')';
+ }
+ }
+
+ parameters.div.removeAttribute('hidden');
+ }
+ }]);
+
+ return AnnotationLayer;
+}();
+
+exports.AnnotationLayer = AnnotationLayer;
+
+/***/ }),
+/* 164 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.SVGGraphics = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+var _display_utils = __w_pdfjs_require__(151);
+
+var _is_node = _interopRequireDefault(__w_pdfjs_require__(4));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
+
+function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
+
+function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
+
+function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
+
+function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
+
+function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
+
+function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
+
+function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var SVGGraphics = function SVGGraphics() {
+ throw new Error('Not implemented: SVGGraphics');
+};
+
+exports.SVGGraphics = SVGGraphics;
+{
+ var opListToTree = function opListToTree(opList) {
+ var opTree = [];
+ var tmp = [];
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = opList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var opListElement = _step.value;
+
+ if (opListElement.fn === 'save') {
+ opTree.push({
+ 'fnId': 92,
+ 'fn': 'group',
+ 'items': []
+ });
+ tmp.push(opTree);
+ opTree = opTree[opTree.length - 1].items;
+ continue;
+ }
+
+ if (opListElement.fn === 'restore') {
+ opTree = tmp.pop();
+ } else {
+ opTree.push(opListElement);
+ }
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+ _iterator["return"]();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ return opTree;
+ };
+
+ var pf = function pf(value) {
+ if (Number.isInteger(value)) {
+ return value.toString();
+ }
+
+ var s = value.toFixed(10);
+ var i = s.length - 1;
+
+ if (s[i] !== '0') {
+ return s;
+ }
+
+ do {
+ i--;
+ } while (s[i] === '0');
+
+ return s.substring(0, s[i] === '.' ? i : i + 1);
+ };
+
+ var pm = function pm(m) {
+ if (m[4] === 0 && m[5] === 0) {
+ if (m[1] === 0 && m[2] === 0) {
+ if (m[0] === 1 && m[3] === 1) {
+ return '';
+ }
+
+ return "scale(".concat(pf(m[0]), " ").concat(pf(m[3]), ")");
+ }
+
+ if (m[0] === m[3] && m[1] === -m[2]) {
+ var a = Math.acos(m[0]) * 180 / Math.PI;
+ return "rotate(".concat(pf(a), ")");
+ }
+ } else {
+ if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
+ return "translate(".concat(pf(m[4]), " ").concat(pf(m[5]), ")");
+ }
+ }
+
+ return "matrix(".concat(pf(m[0]), " ").concat(pf(m[1]), " ").concat(pf(m[2]), " ").concat(pf(m[3]), " ").concat(pf(m[4]), " ") + "".concat(pf(m[5]), ")");
+ };
+
+ var SVG_DEFAULTS = {
+ fontStyle: 'normal',
+ fontWeight: 'normal',
+ fillColor: '#000000'
+ };
+ var XML_NS = 'http://www.w3.org/XML/1998/namespace';
+ var XLINK_NS = 'http://www.w3.org/1999/xlink';
+ var LINE_CAP_STYLES = ['butt', 'round', 'square'];
+ var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
+
+ var convertImgDataToPng = function () {
+ var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ var CHUNK_WRAPPER_SIZE = 12;
+ var crcTable = new Int32Array(256);
+
+ for (var i = 0; i < 256; i++) {
+ var c = i;
+
+ for (var h = 0; h < 8; h++) {
+ if (c & 1) {
+ c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
+ } else {
+ c = c >> 1 & 0x7fffffff;
+ }
+ }
+
+ crcTable[i] = c;
+ }
+
+ function crc32(data, start, end) {
+ var crc = -1;
+
+ for (var _i = start; _i < end; _i++) {
+ var a = (crc ^ data[_i]) & 0xff;
+ var b = crcTable[a];
+ crc = crc >>> 8 ^ b;
+ }
+
+ return crc ^ -1;
+ }
+
+ function writePngChunk(type, body, data, offset) {
+ var p = offset;
+ var len = body.length;
+ data[p] = len >> 24 & 0xff;
+ data[p + 1] = len >> 16 & 0xff;
+ data[p + 2] = len >> 8 & 0xff;
+ data[p + 3] = len & 0xff;
+ p += 4;
+ data[p] = type.charCodeAt(0) & 0xff;
+ data[p + 1] = type.charCodeAt(1) & 0xff;
+ data[p + 2] = type.charCodeAt(2) & 0xff;
+ data[p + 3] = type.charCodeAt(3) & 0xff;
+ p += 4;
+ data.set(body, p);
+ p += body.length;
+ var crc = crc32(data, offset + 4, p);
+ data[p] = crc >> 24 & 0xff;
+ data[p + 1] = crc >> 16 & 0xff;
+ data[p + 2] = crc >> 8 & 0xff;
+ data[p + 3] = crc & 0xff;
+ }
+
+ function adler32(data, start, end) {
+ var a = 1;
+ var b = 0;
+
+ for (var _i2 = start; _i2 < end; ++_i2) {
+ a = (a + (data[_i2] & 0xff)) % 65521;
+ b = (b + a) % 65521;
+ }
+
+ return b << 16 | a;
+ }
+
+ function deflateSync(literals) {
+ if (!(0, _is_node["default"])()) {
+ return deflateSyncUncompressed(literals);
+ }
+
+ try {
+ var input;
+
+ if (parseInt(process.versions.node) >= 8) {
+ input = literals;
+ } else {
+ input = new Buffer(literals);
+ }
+
+ var output = require('zlib').deflateSync(input, {
+ level: 9
+ });
+
+ return output instanceof Uint8Array ? output : new Uint8Array(output);
+ } catch (e) {
+ (0, _util.warn)('Not compressing PNG because zlib.deflateSync is unavailable: ' + e);
+ }
+
+ return deflateSyncUncompressed(literals);
+ }
+
+ function deflateSyncUncompressed(literals) {
+ var len = literals.length;
+ var maxBlockLength = 0xFFFF;
+ var deflateBlocks = Math.ceil(len / maxBlockLength);
+ var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
+ var pi = 0;
+ idat[pi++] = 0x78;
+ idat[pi++] = 0x9c;
+ var pos = 0;
+
+ while (len > maxBlockLength) {
+ idat[pi++] = 0x00;
+ idat[pi++] = 0xff;
+ idat[pi++] = 0xff;
+ idat[pi++] = 0x00;
+ idat[pi++] = 0x00;
+ idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
+ pi += maxBlockLength;
+ pos += maxBlockLength;
+ len -= maxBlockLength;
+ }
+
+ idat[pi++] = 0x01;
+ idat[pi++] = len & 0xff;
+ idat[pi++] = len >> 8 & 0xff;
+ idat[pi++] = ~len & 0xffff & 0xff;
+ idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
+ idat.set(literals.subarray(pos), pi);
+ pi += literals.length - pos;
+ var adler = adler32(literals, 0, literals.length);
+ idat[pi++] = adler >> 24 & 0xff;
+ idat[pi++] = adler >> 16 & 0xff;
+ idat[pi++] = adler >> 8 & 0xff;
+ idat[pi++] = adler & 0xff;
+ return idat;
+ }
+
+ function encode(imgData, kind, forceDataSchema, isMask) {
+ var width = imgData.width;
+ var height = imgData.height;
+ var bitDepth, colorType, lineSize;
+ var bytes = imgData.data;
+
+ switch (kind) {
+ case _util.ImageKind.GRAYSCALE_1BPP:
+ colorType = 0;
+ bitDepth = 1;
+ lineSize = width + 7 >> 3;
+ break;
+
+ case _util.ImageKind.RGB_24BPP:
+ colorType = 2;
+ bitDepth = 8;
+ lineSize = width * 3;
+ break;
+
+ case _util.ImageKind.RGBA_32BPP:
+ colorType = 6;
+ bitDepth = 8;
+ lineSize = width * 4;
+ break;
+
+ default:
+ throw new Error('invalid format');
+ }
+
+ var literals = new Uint8Array((1 + lineSize) * height);
+ var offsetLiterals = 0,
+ offsetBytes = 0;
+
+ for (var y = 0; y < height; ++y) {
+ literals[offsetLiterals++] = 0;
+ literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
+ offsetBytes += lineSize;
+ offsetLiterals += lineSize;
+ }
+
+ if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
+ offsetLiterals = 0;
+
+ for (var _y = 0; _y < height; _y++) {
+ offsetLiterals++;
+
+ for (var _i3 = 0; _i3 < lineSize; _i3++) {
+ literals[offsetLiterals++] ^= 0xFF;
+ }
+ }
+ }
+
+ var ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
+ var idat = deflateSync(literals);
+ var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
+ var data = new Uint8Array(pngLength);
+ var offset = 0;
+ data.set(PNG_HEADER, offset);
+ offset += PNG_HEADER.length;
+ writePngChunk('IHDR', ihdr, data, offset);
+ offset += CHUNK_WRAPPER_SIZE + ihdr.length;
+ writePngChunk('IDATA', idat, data, offset);
+ offset += CHUNK_WRAPPER_SIZE + idat.length;
+ writePngChunk('IEND', new Uint8Array(0), data, offset);
+ return (0, _util.createObjectURL)(data, 'image/png', forceDataSchema);
+ }
+
+ return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
+ var kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
+ return encode(imgData, kind, forceDataSchema, isMask);
+ };
+ }();
+
+ var SVGExtraState =
+ /*#__PURE__*/
+ function () {
+ function SVGExtraState() {
+ _classCallCheck(this, SVGExtraState);
+
+ this.fontSizeScale = 1;
+ this.fontWeight = SVG_DEFAULTS.fontWeight;
+ this.fontSize = 0;
+ this.textMatrix = _util.IDENTITY_MATRIX;
+ this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
+ this.leading = 0;
+ this.textRenderingMode = _util.TextRenderingMode.FILL;
+ this.textMatrixScale = 1;
+ this.x = 0;
+ this.y = 0;
+ this.lineX = 0;
+ this.lineY = 0;
+ this.charSpacing = 0;
+ this.wordSpacing = 0;
+ this.textHScale = 1;
+ this.textRise = 0;
+ this.fillColor = SVG_DEFAULTS.fillColor;
+ this.strokeColor = '#000000';
+ this.fillAlpha = 1;
+ this.strokeAlpha = 1;
+ this.lineWidth = 1;
+ this.lineJoin = '';
+ this.lineCap = '';
+ this.miterLimit = 0;
+ this.dashArray = [];
+ this.dashPhase = 0;
+ this.dependencies = [];
+ this.activeClipUrl = null;
+ this.clipGroup = null;
+ this.maskId = '';
+ }
+
+ _createClass(SVGExtraState, [{
+ key: "clone",
+ value: function clone() {
+ return Object.create(this);
+ }
+ }, {
+ key: "setCurrentPoint",
+ value: function setCurrentPoint(x, y) {
+ this.x = x;
+ this.y = y;
+ }
+ }]);
+
+ return SVGExtraState;
+ }();
+
+ var clipCount = 0;
+ var maskCount = 0;
+ var shadingCount = 0;
+
+ exports.SVGGraphics = SVGGraphics =
+ /*#__PURE__*/
+ function () {
+ function SVGGraphics(commonObjs, objs, forceDataSchema) {
+ _classCallCheck(this, SVGGraphics);
+
+ this.svgFactory = new _display_utils.DOMSVGFactory();
+ this.current = new SVGExtraState();
+ this.transformMatrix = _util.IDENTITY_MATRIX;
+ this.transformStack = [];
+ this.extraStack = [];
+ this.commonObjs = commonObjs;
+ this.objs = objs;
+ this.pendingClip = null;
+ this.pendingEOFill = false;
+ this.embedFonts = false;
+ this.embeddedFonts = Object.create(null);
+ this.cssStyle = null;
+ this.forceDataSchema = !!forceDataSchema;
+ this._operatorIdMapping = [];
+
+ for (var op in _util.OPS) {
+ this._operatorIdMapping[_util.OPS[op]] = op;
+ }
+ }
+
+ _createClass(SVGGraphics, [{
+ key: "save",
+ value: function save() {
+ this.transformStack.push(this.transformMatrix);
+ var old = this.current;
+ this.extraStack.push(old);
+ this.current = old.clone();
+ }
+ }, {
+ key: "restore",
+ value: function restore() {
+ this.transformMatrix = this.transformStack.pop();
+ this.current = this.extraStack.pop();
+ this.pendingClip = null;
+ this.tgrp = null;
+ }
+ }, {
+ key: "group",
+ value: function group(items) {
+ this.save();
+ this.executeOpTree(items);
+ this.restore();
+ }
+ }, {
+ key: "loadDependencies",
+ value: function loadDependencies(operatorList) {
+ var _this = this;
+
+ var fnArray = operatorList.fnArray;
+ var argsArray = operatorList.argsArray;
+
+ for (var i = 0, ii = fnArray.length; i < ii; i++) {
+ if (fnArray[i] !== _util.OPS.dependency) {
+ continue;
+ }
+
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ var _loop = function _loop() {
+ var obj = _step2.value;
+ var objsPool = obj.startsWith('g_') ? _this.commonObjs : _this.objs;
+ var promise = new Promise(function (resolve) {
+ objsPool.get(obj, resolve);
+ });
+
+ _this.current.dependencies.push(promise);
+ };
+
+ for (var _iterator2 = argsArray[i][Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ _loop();
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+ _iterator2["return"]();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ }
+
+ return Promise.all(this.current.dependencies);
+ }
+ }, {
+ key: "transform",
+ value: function transform(a, b, c, d, e, f) {
+ var transformMatrix = [a, b, c, d, e, f];
+ this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
+ this.tgrp = null;
+ }
+ }, {
+ key: "getSVG",
+ value: function getSVG(operatorList, viewport) {
+ var _this2 = this;
+
+ this.viewport = viewport;
+
+ var svgElement = this._initialize(viewport);
+
+ return this.loadDependencies(operatorList).then(function () {
+ _this2.transformMatrix = _util.IDENTITY_MATRIX;
+
+ _this2.executeOpTree(_this2.convertOpList(operatorList));
+
+ return svgElement;
+ });
+ }
+ }, {
+ key: "convertOpList",
+ value: function convertOpList(operatorList) {
+ var operatorIdMapping = this._operatorIdMapping;
+ var argsArray = operatorList.argsArray;
+ var fnArray = operatorList.fnArray;
+ var opList = [];
+
+ for (var i = 0, ii = fnArray.length; i < ii; i++) {
+ var fnId = fnArray[i];
+ opList.push({
+ 'fnId': fnId,
+ 'fn': operatorIdMapping[fnId],
+ 'args': argsArray[i]
+ });
+ }
+
+ return opListToTree(opList);
+ }
+ }, {
+ key: "executeOpTree",
+ value: function executeOpTree(opTree) {
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+
+ try {
+ for (var _iterator3 = opTree[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
+ var opTreeElement = _step3.value;
+ var fn = opTreeElement.fn;
+ var fnId = opTreeElement.fnId;
+ var args = opTreeElement.args;
+
+ switch (fnId | 0) {
+ case _util.OPS.beginText:
+ this.beginText();
+ break;
+
+ case _util.OPS.dependency:
+ break;
+
+ case _util.OPS.setLeading:
+ this.setLeading(args);
+ break;
+
+ case _util.OPS.setLeadingMoveText:
+ this.setLeadingMoveText(args[0], args[1]);
+ break;
+
+ case _util.OPS.setFont:
+ this.setFont(args);
+ break;
+
+ case _util.OPS.showText:
+ this.showText(args[0]);
+ break;
+
+ case _util.OPS.showSpacedText:
+ this.showText(args[0]);
+ break;
+
+ case _util.OPS.endText:
+ this.endText();
+ break;
+
+ case _util.OPS.moveText:
+ this.moveText(args[0], args[1]);
+ break;
+
+ case _util.OPS.setCharSpacing:
+ this.setCharSpacing(args[0]);
+ break;
+
+ case _util.OPS.setWordSpacing:
+ this.setWordSpacing(args[0]);
+ break;
+
+ case _util.OPS.setHScale:
+ this.setHScale(args[0]);
+ break;
+
+ case _util.OPS.setTextMatrix:
+ this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
+ break;
+
+ case _util.OPS.setTextRise:
+ this.setTextRise(args[0]);
+ break;
+
+ case _util.OPS.setTextRenderingMode:
+ this.setTextRenderingMode(args[0]);
+ break;
+
+ case _util.OPS.setLineWidth:
+ this.setLineWidth(args[0]);
+ break;
+
+ case _util.OPS.setLineJoin:
+ this.setLineJoin(args[0]);
+ break;
+
+ case _util.OPS.setLineCap:
+ this.setLineCap(args[0]);
+ break;
+
+ case _util.OPS.setMiterLimit:
+ this.setMiterLimit(args[0]);
+ break;
+
+ case _util.OPS.setFillRGBColor:
+ this.setFillRGBColor(args[0], args[1], args[2]);
+ break;
+
+ case _util.OPS.setStrokeRGBColor:
+ this.setStrokeRGBColor(args[0], args[1], args[2]);
+ break;
+
+ case _util.OPS.setStrokeColorN:
+ this.setStrokeColorN(args);
+ break;
+
+ case _util.OPS.setFillColorN:
+ this.setFillColorN(args);
+ break;
+
+ case _util.OPS.shadingFill:
+ this.shadingFill(args[0]);
+ break;
+
+ case _util.OPS.setDash:
+ this.setDash(args[0], args[1]);
+ break;
+
+ case _util.OPS.setRenderingIntent:
+ this.setRenderingIntent(args[0]);
+ break;
+
+ case _util.OPS.setFlatness:
+ this.setFlatness(args[0]);
+ break;
+
+ case _util.OPS.setGState:
+ this.setGState(args[0]);
+ break;
+
+ case _util.OPS.fill:
+ this.fill();
+ break;
+
+ case _util.OPS.eoFill:
+ this.eoFill();
+ break;
+
+ case _util.OPS.stroke:
+ this.stroke();
+ break;
+
+ case _util.OPS.fillStroke:
+ this.fillStroke();
+ break;
+
+ case _util.OPS.eoFillStroke:
+ this.eoFillStroke();
+ break;
+
+ case _util.OPS.clip:
+ this.clip('nonzero');
+ break;
+
+ case _util.OPS.eoClip:
+ this.clip('evenodd');
+ break;
+
+ case _util.OPS.paintSolidColorImageMask:
+ this.paintSolidColorImageMask();
+ break;
+
+ case _util.OPS.paintJpegXObject:
+ this.paintJpegXObject(args[0], args[1], args[2]);
+ break;
+
+ case _util.OPS.paintImageXObject:
+ this.paintImageXObject(args[0]);
+ break;
+
+ case _util.OPS.paintInlineImageXObject:
+ this.paintInlineImageXObject(args[0]);
+ break;
+
+ case _util.OPS.paintImageMaskXObject:
+ this.paintImageMaskXObject(args[0]);
+ break;
+
+ case _util.OPS.paintFormXObjectBegin:
+ this.paintFormXObjectBegin(args[0], args[1]);
+ break;
+
+ case _util.OPS.paintFormXObjectEnd:
+ this.paintFormXObjectEnd();
+ break;
+
+ case _util.OPS.closePath:
+ this.closePath();
+ break;
+
+ case _util.OPS.closeStroke:
+ this.closeStroke();
+ break;
+
+ case _util.OPS.closeFillStroke:
+ this.closeFillStroke();
+ break;
+
+ case _util.OPS.closeEOFillStroke:
+ this.closeEOFillStroke();
+ break;
+
+ case _util.OPS.nextLine:
+ this.nextLine();
+ break;
+
+ case _util.OPS.transform:
+ this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
+ break;
+
+ case _util.OPS.constructPath:
+ this.constructPath(args[0], args[1]);
+ break;
+
+ case _util.OPS.endPath:
+ this.endPath();
+ break;
+
+ case 92:
+ this.group(opTreeElement.items);
+ break;
+
+ default:
+ (0, _util.warn)("Unimplemented operator ".concat(fn));
+ break;
+ }
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
+ _iterator3["return"]();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+ }
+ }, {
+ key: "setWordSpacing",
+ value: function setWordSpacing(wordSpacing) {
+ this.current.wordSpacing = wordSpacing;
+ }
+ }, {
+ key: "setCharSpacing",
+ value: function setCharSpacing(charSpacing) {
+ this.current.charSpacing = charSpacing;
+ }
+ }, {
+ key: "nextLine",
+ value: function nextLine() {
+ this.moveText(0, this.current.leading);
+ }
+ }, {
+ key: "setTextMatrix",
+ value: function setTextMatrix(a, b, c, d, e, f) {
+ var current = this.current;
+ current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
+ current.textMatrixScale = Math.sqrt(a * a + b * b);
+ current.x = current.lineX = 0;
+ current.y = current.lineY = 0;
+ current.xcoords = [];
+ current.tspan = this.svgFactory.createElement('svg:tspan');
+ current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
+ current.tspan.setAttributeNS(null, 'font-size', "".concat(pf(current.fontSize), "px"));
+ current.tspan.setAttributeNS(null, 'y', pf(-current.y));
+ current.txtElement = this.svgFactory.createElement('svg:text');
+ current.txtElement.appendChild(current.tspan);
+ }
+ }, {
+ key: "beginText",
+ value: function beginText() {
+ var current = this.current;
+ current.x = current.lineX = 0;
+ current.y = current.lineY = 0;
+ current.textMatrix = _util.IDENTITY_MATRIX;
+ current.lineMatrix = _util.IDENTITY_MATRIX;
+ current.textMatrixScale = 1;
+ current.tspan = this.svgFactory.createElement('svg:tspan');
+ current.txtElement = this.svgFactory.createElement('svg:text');
+ current.txtgrp = this.svgFactory.createElement('svg:g');
+ current.xcoords = [];
+ }
+ }, {
+ key: "moveText",
+ value: function moveText(x, y) {
+ var current = this.current;
+ current.x = current.lineX += x;
+ current.y = current.lineY += y;
+ current.xcoords = [];
+ current.tspan = this.svgFactory.createElement('svg:tspan');
+ current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
+ current.tspan.setAttributeNS(null, 'font-size', "".concat(pf(current.fontSize), "px"));
+ current.tspan.setAttributeNS(null, 'y', pf(-current.y));
+ }
+ }, {
+ key: "showText",
+ value: function showText(glyphs) {
+ var current = this.current;
+ var font = current.font;
+ var fontSize = current.fontSize;
+
+ if (fontSize === 0) {
+ return;
+ }
+
+ var charSpacing = current.charSpacing;
+ var wordSpacing = current.wordSpacing;
+ var fontDirection = current.fontDirection;
+ var textHScale = current.textHScale * fontDirection;
+ var vertical = font.vertical;
+ var widthAdvanceScale = fontSize * current.fontMatrix[0];
+ var x = 0;
+ var _iteratorNormalCompletion4 = true;
+ var _didIteratorError4 = false;
+ var _iteratorError4 = undefined;
+
+ try {
+ for (var _iterator4 = glyphs[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
+ var glyph = _step4.value;
+
+ if (glyph === null) {
+ x += fontDirection * wordSpacing;
+ continue;
+ } else if ((0, _util.isNum)(glyph)) {
+ x += -glyph * fontSize * 0.001;
+ continue;
+ }
+
+ var width = glyph.width;
+ var character = glyph.fontChar;
+ var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
+ var charWidth = width * widthAdvanceScale + spacing * fontDirection;
+
+ if (!glyph.isInFont && !font.missingFile) {
+ x += charWidth;
+ continue;
+ }
+
+ current.xcoords.push(current.x + x * textHScale);
+ current.tspan.textContent += character;
+ x += charWidth;
+ }
+ } catch (err) {
+ _didIteratorError4 = true;
+ _iteratorError4 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
+ _iterator4["return"]();
+ }
+ } finally {
+ if (_didIteratorError4) {
+ throw _iteratorError4;
+ }
+ }
+ }
+
+ if (vertical) {
+ current.y -= x * textHScale;
+ } else {
+ current.x += x * textHScale;
+ }
+
+ current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
+ current.tspan.setAttributeNS(null, 'y', pf(-current.y));
+ current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
+ current.tspan.setAttributeNS(null, 'font-size', "".concat(pf(current.fontSize), "px"));
+
+ if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
+ current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
+ }
+
+ if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
+ current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
+ }
+
+ var fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
+
+ if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ if (current.fillColor !== SVG_DEFAULTS.fillColor) {
+ current.tspan.setAttributeNS(null, 'fill', current.fillColor);
+ }
+
+ if (current.fillAlpha < 1) {
+ current.tspan.setAttributeNS(null, 'fill-opacity', current.fillAlpha);
+ }
+ } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
+ current.tspan.setAttributeNS(null, 'fill', 'transparent');
+ } else {
+ current.tspan.setAttributeNS(null, 'fill', 'none');
+ }
+
+ if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
+ var lineWidthScale = 1 / (current.textMatrixScale || 1);
+
+ this._setStrokeAttributes(current.tspan, lineWidthScale);
+ }
+
+ var textMatrix = current.textMatrix;
+
+ if (current.textRise !== 0) {
+ textMatrix = textMatrix.slice();
+ textMatrix[5] += current.textRise;
+ }
+
+ current.txtElement.setAttributeNS(null, 'transform', "".concat(pm(textMatrix), " scale(1, -1)"));
+ current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
+ current.txtElement.appendChild(current.tspan);
+ current.txtgrp.appendChild(current.txtElement);
+
+ this._ensureTransformGroup().appendChild(current.txtElement);
+ }
+ }, {
+ key: "setLeadingMoveText",
+ value: function setLeadingMoveText(x, y) {
+ this.setLeading(-y);
+ this.moveText(x, y);
+ }
+ }, {
+ key: "addFontStyle",
+ value: function addFontStyle(fontObj) {
+ if (!this.cssStyle) {
+ this.cssStyle = this.svgFactory.createElement('svg:style');
+ this.cssStyle.setAttributeNS(null, 'type', 'text/css');
+ this.defs.appendChild(this.cssStyle);
+ }
+
+ var url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
+ this.cssStyle.textContent += "@font-face { font-family: \"".concat(fontObj.loadedName, "\";") + " src: url(".concat(url, "); }\n");
+ }
+ }, {
+ key: "setFont",
+ value: function setFont(details) {
+ var current = this.current;
+ var fontObj = this.commonObjs.get(details[0]);
+ var size = details[1];
+ current.font = fontObj;
+
+ if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
+ this.addFontStyle(fontObj);
+ this.embeddedFonts[fontObj.loadedName] = fontObj;
+ }
+
+ current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX;
+ var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
+ var italic = fontObj.italic ? 'italic' : 'normal';
+
+ if (size < 0) {
+ size = -size;
+ current.fontDirection = -1;
+ } else {
+ current.fontDirection = 1;
+ }
+
+ current.fontSize = size;
+ current.fontFamily = fontObj.loadedName;
+ current.fontWeight = bold;
+ current.fontStyle = italic;
+ current.tspan = this.svgFactory.createElement('svg:tspan');
+ current.tspan.setAttributeNS(null, 'y', pf(-current.y));
+ current.xcoords = [];
+ }
+ }, {
+ key: "endText",
+ value: function endText() {
+ var current = this.current;
+
+ if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement && current.txtElement.hasChildNodes()) {
+ current.element = current.txtElement;
+ this.clip('nonzero');
+ this.endPath();
+ }
+ }
+ }, {
+ key: "setLineWidth",
+ value: function setLineWidth(width) {
+ if (width > 0) {
+ this.current.lineWidth = width;
+ }
+ }
+ }, {
+ key: "setLineCap",
+ value: function setLineCap(style) {
+ this.current.lineCap = LINE_CAP_STYLES[style];
+ }
+ }, {
+ key: "setLineJoin",
+ value: function setLineJoin(style) {
+ this.current.lineJoin = LINE_JOIN_STYLES[style];
+ }
+ }, {
+ key: "setMiterLimit",
+ value: function setMiterLimit(limit) {
+ this.current.miterLimit = limit;
+ }
+ }, {
+ key: "setStrokeAlpha",
+ value: function setStrokeAlpha(strokeAlpha) {
+ this.current.strokeAlpha = strokeAlpha;
+ }
+ }, {
+ key: "setStrokeRGBColor",
+ value: function setStrokeRGBColor(r, g, b) {
+ this.current.strokeColor = _util.Util.makeCssRgb(r, g, b);
+ }
+ }, {
+ key: "setFillAlpha",
+ value: function setFillAlpha(fillAlpha) {
+ this.current.fillAlpha = fillAlpha;
+ }
+ }, {
+ key: "setFillRGBColor",
+ value: function setFillRGBColor(r, g, b) {
+ this.current.fillColor = _util.Util.makeCssRgb(r, g, b);
+ this.current.tspan = this.svgFactory.createElement('svg:tspan');
+ this.current.xcoords = [];
+ }
+ }, {
+ key: "setStrokeColorN",
+ value: function setStrokeColorN(args) {
+ this.current.strokeColor = this._makeColorN_Pattern(args);
+ }
+ }, {
+ key: "setFillColorN",
+ value: function setFillColorN(args) {
+ this.current.fillColor = this._makeColorN_Pattern(args);
+ }
+ }, {
+ key: "shadingFill",
+ value: function shadingFill(args) {
+ var width = this.viewport.width;
+ var height = this.viewport.height;
+
+ var inv = _util.Util.inverseTransform(this.transformMatrix);
+
+ var bl = _util.Util.applyTransform([0, 0], inv);
+
+ var br = _util.Util.applyTransform([0, height], inv);
+
+ var ul = _util.Util.applyTransform([width, 0], inv);
+
+ var ur = _util.Util.applyTransform([width, height], inv);
+
+ var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
+ var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
+ var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
+ var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
+ var rect = this.svgFactory.createElement('svg:rect');
+ rect.setAttributeNS(null, 'x', x0);
+ rect.setAttributeNS(null, 'y', y0);
+ rect.setAttributeNS(null, 'width', x1 - x0);
+ rect.setAttributeNS(null, 'height', y1 - y0);
+ rect.setAttributeNS(null, 'fill', this._makeShadingPattern(args));
+
+ this._ensureTransformGroup().appendChild(rect);
+ }
+ }, {
+ key: "_makeColorN_Pattern",
+ value: function _makeColorN_Pattern(args) {
+ if (args[0] === 'TilingPattern') {
+ return this._makeTilingPattern(args);
+ }
+
+ return this._makeShadingPattern(args);
+ }
+ }, {
+ key: "_makeTilingPattern",
+ value: function _makeTilingPattern(args) {
+ var color = args[1];
+ var operatorList = args[2];
+ var matrix = args[3] || _util.IDENTITY_MATRIX;
+
+ var _args$ = _slicedToArray(args[4], 4),
+ x0 = _args$[0],
+ y0 = _args$[1],
+ x1 = _args$[2],
+ y1 = _args$[3];
+
+ var xstep = args[5];
+ var ystep = args[6];
+ var paintType = args[7];
+ var tilingId = "shading".concat(shadingCount++);
+
+ var _Util$applyTransform = _util.Util.applyTransform([x0, y0], matrix),
+ _Util$applyTransform2 = _slicedToArray(_Util$applyTransform, 2),
+ tx0 = _Util$applyTransform2[0],
+ ty0 = _Util$applyTransform2[1];
+
+ var _Util$applyTransform3 = _util.Util.applyTransform([x1, y1], matrix),
+ _Util$applyTransform4 = _slicedToArray(_Util$applyTransform3, 2),
+ tx1 = _Util$applyTransform4[0],
+ ty1 = _Util$applyTransform4[1];
+
+ var _Util$singularValueDe = _util.Util.singularValueDecompose2dScale(matrix),
+ _Util$singularValueDe2 = _slicedToArray(_Util$singularValueDe, 2),
+ xscale = _Util$singularValueDe2[0],
+ yscale = _Util$singularValueDe2[1];
+
+ var txstep = xstep * xscale;
+ var tystep = ystep * yscale;
+ var tiling = this.svgFactory.createElement('svg:pattern');
+ tiling.setAttributeNS(null, 'id', tilingId);
+ tiling.setAttributeNS(null, 'patternUnits', 'userSpaceOnUse');
+ tiling.setAttributeNS(null, 'width', txstep);
+ tiling.setAttributeNS(null, 'height', tystep);
+ tiling.setAttributeNS(null, 'x', "".concat(tx0));
+ tiling.setAttributeNS(null, 'y', "".concat(ty0));
+ var svg = this.svg;
+ var transformMatrix = this.transformMatrix;
+ var fillColor = this.current.fillColor;
+ var strokeColor = this.current.strokeColor;
+ var bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
+ this.svg = bbox;
+ this.transformMatrix = matrix;
+
+ if (paintType === 2) {
+ var cssColor = _util.Util.makeCssRgb.apply(_util.Util, _toConsumableArray(color));
+
+ this.current.fillColor = cssColor;
+ this.current.strokeColor = cssColor;
+ }
+
+ this.executeOpTree(this.convertOpList(operatorList));
+ this.svg = svg;
+ this.transformMatrix = transformMatrix;
+ this.current.fillColor = fillColor;
+ this.current.strokeColor = strokeColor;
+ tiling.appendChild(bbox.childNodes[0]);
+ this.defs.appendChild(tiling);
+ return "url(#".concat(tilingId, ")");
+ }
+ }, {
+ key: "_makeShadingPattern",
+ value: function _makeShadingPattern(args) {
+ switch (args[0]) {
+ case 'RadialAxial':
+ var shadingId = "shading".concat(shadingCount++);
+ var colorStops = args[2];
+ var gradient;
+
+ switch (args[1]) {
+ case 'axial':
+ var point0 = args[3];
+ var point1 = args[4];
+ gradient = this.svgFactory.createElement('svg:linearGradient');
+ gradient.setAttributeNS(null, 'id', shadingId);
+ gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse');
+ gradient.setAttributeNS(null, 'x1', point0[0]);
+ gradient.setAttributeNS(null, 'y1', point0[1]);
+ gradient.setAttributeNS(null, 'x2', point1[0]);
+ gradient.setAttributeNS(null, 'y2', point1[1]);
+ break;
+
+ case 'radial':
+ var focalPoint = args[3];
+ var circlePoint = args[4];
+ var focalRadius = args[5];
+ var circleRadius = args[6];
+ gradient = this.svgFactory.createElement('svg:radialGradient');
+ gradient.setAttributeNS(null, 'id', shadingId);
+ gradient.setAttributeNS(null, 'gradientUnits', 'userSpaceOnUse');
+ gradient.setAttributeNS(null, 'cx', circlePoint[0]);
+ gradient.setAttributeNS(null, 'cy', circlePoint[1]);
+ gradient.setAttributeNS(null, 'r', circleRadius);
+ gradient.setAttributeNS(null, 'fx', focalPoint[0]);
+ gradient.setAttributeNS(null, 'fy', focalPoint[1]);
+ gradient.setAttributeNS(null, 'fr', focalRadius);
+ break;
+
+ default:
+ throw new Error("Unknown RadialAxial type: ".concat(args[1]));
+ }
+
+ var _iteratorNormalCompletion5 = true;
+ var _didIteratorError5 = false;
+ var _iteratorError5 = undefined;
+
+ try {
+ for (var _iterator5 = colorStops[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
+ var colorStop = _step5.value;
+ var stop = this.svgFactory.createElement('svg:stop');
+ stop.setAttributeNS(null, 'offset', colorStop[0]);
+ stop.setAttributeNS(null, 'stop-color', colorStop[1]);
+ gradient.appendChild(stop);
+ }
+ } catch (err) {
+ _didIteratorError5 = true;
+ _iteratorError5 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion5 && _iterator5["return"] != null) {
+ _iterator5["return"]();
+ }
+ } finally {
+ if (_didIteratorError5) {
+ throw _iteratorError5;
+ }
+ }
+ }
+
+ this.defs.appendChild(gradient);
+ return "url(#".concat(shadingId, ")");
+
+ case 'Mesh':
+ (0, _util.warn)('Unimplemented pattern Mesh');
+ return null;
+
+ case 'Dummy':
+ return 'hotpink';
+
+ default:
+ throw new Error("Unknown IR type: ".concat(args[0]));
+ }
+ }
+ }, {
+ key: "setDash",
+ value: function setDash(dashArray, dashPhase) {
+ this.current.dashArray = dashArray;
+ this.current.dashPhase = dashPhase;
+ }
+ }, {
+ key: "constructPath",
+ value: function constructPath(ops, args) {
+ var current = this.current;
+ var x = current.x,
+ y = current.y;
+ var d = [];
+ var j = 0;
+ var _iteratorNormalCompletion6 = true;
+ var _didIteratorError6 = false;
+ var _iteratorError6 = undefined;
+
+ try {
+ for (var _iterator6 = ops[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
+ var op = _step6.value;
+
+ switch (op | 0) {
+ case _util.OPS.rectangle:
+ x = args[j++];
+ y = args[j++];
+ var width = args[j++];
+ var height = args[j++];
+ var xw = x + width;
+ var yh = y + height;
+ d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
+ break;
+
+ case _util.OPS.moveTo:
+ x = args[j++];
+ y = args[j++];
+ d.push('M', pf(x), pf(y));
+ break;
+
+ case _util.OPS.lineTo:
+ x = args[j++];
+ y = args[j++];
+ d.push('L', pf(x), pf(y));
+ break;
+
+ case _util.OPS.curveTo:
+ x = args[j + 4];
+ y = args[j + 5];
+ d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
+ j += 6;
+ break;
+
+ case _util.OPS.curveTo2:
+ x = args[j + 2];
+ y = args[j + 3];
+ d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
+ j += 4;
+ break;
+
+ case _util.OPS.curveTo3:
+ x = args[j + 2];
+ y = args[j + 3];
+ d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
+ j += 4;
+ break;
+
+ case _util.OPS.closePath:
+ d.push('Z');
+ break;
+ }
+ }
+ } catch (err) {
+ _didIteratorError6 = true;
+ _iteratorError6 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion6 && _iterator6["return"] != null) {
+ _iterator6["return"]();
+ }
+ } finally {
+ if (_didIteratorError6) {
+ throw _iteratorError6;
+ }
+ }
+ }
+
+ d = d.join(' ');
+
+ if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
+ d = current.path.getAttributeNS(null, 'd') + d;
+ } else {
+ current.path = this.svgFactory.createElement('svg:path');
+
+ this._ensureTransformGroup().appendChild(current.path);
+ }
+
+ current.path.setAttributeNS(null, 'd', d);
+ current.path.setAttributeNS(null, 'fill', 'none');
+ current.element = current.path;
+ current.setCurrentPoint(x, y);
+ }
+ }, {
+ key: "endPath",
+ value: function endPath() {
+ var current = this.current;
+ current.path = null;
+
+ if (!this.pendingClip) {
+ return;
+ }
+
+ if (!current.element) {
+ this.pendingClip = null;
+ return;
+ }
+
+ var clipId = "clippath".concat(clipCount++);
+ var clipPath = this.svgFactory.createElement('svg:clipPath');
+ clipPath.setAttributeNS(null, 'id', clipId);
+ clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
+ var clipElement = current.element.cloneNode(true);
+
+ if (this.pendingClip === 'evenodd') {
+ clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
+ } else {
+ clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
+ }
+
+ this.pendingClip = null;
+ clipPath.appendChild(clipElement);
+ this.defs.appendChild(clipPath);
+
+ if (current.activeClipUrl) {
+ current.clipGroup = null;
+ this.extraStack.forEach(function (prev) {
+ prev.clipGroup = null;
+ });
+ clipPath.setAttributeNS(null, 'clip-path', current.activeClipUrl);
+ }
+
+ current.activeClipUrl = "url(#".concat(clipId, ")");
+ this.tgrp = null;
+ }
+ }, {
+ key: "clip",
+ value: function clip(type) {
+ this.pendingClip = type;
+ }
+ }, {
+ key: "closePath",
+ value: function closePath() {
+ var current = this.current;
+
+ if (current.path) {
+ var d = "".concat(current.path.getAttributeNS(null, 'd'), "Z");
+ current.path.setAttributeNS(null, 'd', d);
+ }
+ }
+ }, {
+ key: "setLeading",
+ value: function setLeading(leading) {
+ this.current.leading = -leading;
+ }
+ }, {
+ key: "setTextRise",
+ value: function setTextRise(textRise) {
+ this.current.textRise = textRise;
+ }
+ }, {
+ key: "setTextRenderingMode",
+ value: function setTextRenderingMode(textRenderingMode) {
+ this.current.textRenderingMode = textRenderingMode;
+ }
+ }, {
+ key: "setHScale",
+ value: function setHScale(scale) {
+ this.current.textHScale = scale / 100;
+ }
+ }, {
+ key: "setRenderingIntent",
+ value: function setRenderingIntent(intent) {}
+ }, {
+ key: "setFlatness",
+ value: function setFlatness(flatness) {}
+ }, {
+ key: "setGState",
+ value: function setGState(states) {
+ var _iteratorNormalCompletion7 = true;
+ var _didIteratorError7 = false;
+ var _iteratorError7 = undefined;
+
+ try {
+ for (var _iterator7 = states[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
+ var _step7$value = _slicedToArray(_step7.value, 2),
+ key = _step7$value[0],
+ value = _step7$value[1];
+
+ switch (key) {
+ case 'LW':
+ this.setLineWidth(value);
+ break;
+
+ case 'LC':
+ this.setLineCap(value);
+ break;
+
+ case 'LJ':
+ this.setLineJoin(value);
+ break;
+
+ case 'ML':
+ this.setMiterLimit(value);
+ break;
+
+ case 'D':
+ this.setDash(value[0], value[1]);
+ break;
+
+ case 'RI':
+ this.setRenderingIntent(value);
+ break;
+
+ case 'FL':
+ this.setFlatness(value);
+ break;
+
+ case 'Font':
+ this.setFont(value);
+ break;
+
+ case 'CA':
+ this.setStrokeAlpha(value);
+ break;
+
+ case 'ca':
+ this.setFillAlpha(value);
+ break;
+
+ default:
+ (0, _util.warn)("Unimplemented graphic state operator ".concat(key));
+ break;
+ }
+ }
+ } catch (err) {
+ _didIteratorError7 = true;
+ _iteratorError7 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion7 && _iterator7["return"] != null) {
+ _iterator7["return"]();
+ }
+ } finally {
+ if (_didIteratorError7) {
+ throw _iteratorError7;
+ }
+ }
+ }
+ }
+ }, {
+ key: "fill",
+ value: function fill() {
+ var current = this.current;
+
+ if (current.element) {
+ current.element.setAttributeNS(null, 'fill', current.fillColor);
+ current.element.setAttributeNS(null, 'fill-opacity', current.fillAlpha);
+ this.endPath();
+ }
+ }
+ }, {
+ key: "stroke",
+ value: function stroke() {
+ var current = this.current;
+
+ if (current.element) {
+ this._setStrokeAttributes(current.element);
+
+ current.element.setAttributeNS(null, 'fill', 'none');
+ this.endPath();
+ }
+ }
+ }, {
+ key: "_setStrokeAttributes",
+ value: function _setStrokeAttributes(element) {
+ var lineWidthScale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
+ var current = this.current;
+ var dashArray = current.dashArray;
+
+ if (lineWidthScale !== 1 && dashArray.length > 0) {
+ dashArray = dashArray.map(function (value) {
+ return lineWidthScale * value;
+ });
+ }
+
+ element.setAttributeNS(null, 'stroke', current.strokeColor);
+ element.setAttributeNS(null, 'stroke-opacity', current.strokeAlpha);
+ element.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
+ element.setAttributeNS(null, 'stroke-linecap', current.lineCap);
+ element.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
+ element.setAttributeNS(null, 'stroke-width', pf(lineWidthScale * current.lineWidth) + 'px');
+ element.setAttributeNS(null, 'stroke-dasharray', dashArray.map(pf).join(' '));
+ element.setAttributeNS(null, 'stroke-dashoffset', pf(lineWidthScale * current.dashPhase) + 'px');
+ }
+ }, {
+ key: "eoFill",
+ value: function eoFill() {
+ if (this.current.element) {
+ this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
+ }
+
+ this.fill();
+ }
+ }, {
+ key: "fillStroke",
+ value: function fillStroke() {
+ this.stroke();
+ this.fill();
+ }
+ }, {
+ key: "eoFillStroke",
+ value: function eoFillStroke() {
+ if (this.current.element) {
+ this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
+ }
+
+ this.fillStroke();
+ }
+ }, {
+ key: "closeStroke",
+ value: function closeStroke() {
+ this.closePath();
+ this.stroke();
+ }
+ }, {
+ key: "closeFillStroke",
+ value: function closeFillStroke() {
+ this.closePath();
+ this.fillStroke();
+ }
+ }, {
+ key: "closeEOFillStroke",
+ value: function closeEOFillStroke() {
+ this.closePath();
+ this.eoFillStroke();
+ }
+ }, {
+ key: "paintSolidColorImageMask",
+ value: function paintSolidColorImageMask() {
+ var rect = this.svgFactory.createElement('svg:rect');
+ rect.setAttributeNS(null, 'x', '0');
+ rect.setAttributeNS(null, 'y', '0');
+ rect.setAttributeNS(null, 'width', '1px');
+ rect.setAttributeNS(null, 'height', '1px');
+ rect.setAttributeNS(null, 'fill', this.current.fillColor);
+
+ this._ensureTransformGroup().appendChild(rect);
+ }
+ }, {
+ key: "paintJpegXObject",
+ value: function paintJpegXObject(objId, w, h) {
+ var imgObj = this.objs.get(objId);
+ var imgEl = this.svgFactory.createElement('svg:image');
+ imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
+ imgEl.setAttributeNS(null, 'width', pf(w));
+ imgEl.setAttributeNS(null, 'height', pf(h));
+ imgEl.setAttributeNS(null, 'x', '0');
+ imgEl.setAttributeNS(null, 'y', pf(-h));
+ imgEl.setAttributeNS(null, 'transform', "scale(".concat(pf(1 / w), " ").concat(pf(-1 / h), ")"));
+
+ this._ensureTransformGroup().appendChild(imgEl);
+ }
+ }, {
+ key: "paintImageXObject",
+ value: function paintImageXObject(objId) {
+ var imgData = this.objs.get(objId);
+
+ if (!imgData) {
+ (0, _util.warn)("Dependent image with object ID ".concat(objId, " is not ready yet"));
+ return;
+ }
+
+ this.paintInlineImageXObject(imgData);
+ }
+ }, {
+ key: "paintInlineImageXObject",
+ value: function paintInlineImageXObject(imgData, mask) {
+ var width = imgData.width;
+ var height = imgData.height;
+ var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
+ var cliprect = this.svgFactory.createElement('svg:rect');
+ cliprect.setAttributeNS(null, 'x', '0');
+ cliprect.setAttributeNS(null, 'y', '0');
+ cliprect.setAttributeNS(null, 'width', pf(width));
+ cliprect.setAttributeNS(null, 'height', pf(height));
+ this.current.element = cliprect;
+ this.clip('nonzero');
+ var imgEl = this.svgFactory.createElement('svg:image');
+ imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
+ imgEl.setAttributeNS(null, 'x', '0');
+ imgEl.setAttributeNS(null, 'y', pf(-height));
+ imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
+ imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
+ imgEl.setAttributeNS(null, 'transform', "scale(".concat(pf(1 / width), " ").concat(pf(-1 / height), ")"));
+
+ if (mask) {
+ mask.appendChild(imgEl);
+ } else {
+ this._ensureTransformGroup().appendChild(imgEl);
+ }
+ }
+ }, {
+ key: "paintImageMaskXObject",
+ value: function paintImageMaskXObject(imgData) {
+ var current = this.current;
+ var width = imgData.width;
+ var height = imgData.height;
+ var fillColor = current.fillColor;
+ current.maskId = "mask".concat(maskCount++);
+ var mask = this.svgFactory.createElement('svg:mask');
+ mask.setAttributeNS(null, 'id', current.maskId);
+ var rect = this.svgFactory.createElement('svg:rect');
+ rect.setAttributeNS(null, 'x', '0');
+ rect.setAttributeNS(null, 'y', '0');
+ rect.setAttributeNS(null, 'width', pf(width));
+ rect.setAttributeNS(null, 'height', pf(height));
+ rect.setAttributeNS(null, 'fill', fillColor);
+ rect.setAttributeNS(null, 'mask', "url(#".concat(current.maskId, ")"));
+ this.defs.appendChild(mask);
+
+ this._ensureTransformGroup().appendChild(rect);
+
+ this.paintInlineImageXObject(imgData, mask);
+ }
+ }, {
+ key: "paintFormXObjectBegin",
+ value: function paintFormXObjectBegin(matrix, bbox) {
+ if (Array.isArray(matrix) && matrix.length === 6) {
+ this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
+ }
+
+ if (bbox) {
+ var width = bbox[2] - bbox[0];
+ var height = bbox[3] - bbox[1];
+ var cliprect = this.svgFactory.createElement('svg:rect');
+ cliprect.setAttributeNS(null, 'x', bbox[0]);
+ cliprect.setAttributeNS(null, 'y', bbox[1]);
+ cliprect.setAttributeNS(null, 'width', pf(width));
+ cliprect.setAttributeNS(null, 'height', pf(height));
+ this.current.element = cliprect;
+ this.clip('nonzero');
+ this.endPath();
+ }
+ }
+ }, {
+ key: "paintFormXObjectEnd",
+ value: function paintFormXObjectEnd() {}
+ }, {
+ key: "_initialize",
+ value: function _initialize(viewport) {
+ var svg = this.svgFactory.create(viewport.width, viewport.height);
+ var definitions = this.svgFactory.createElement('svg:defs');
+ svg.appendChild(definitions);
+ this.defs = definitions;
+ var rootGroup = this.svgFactory.createElement('svg:g');
+ rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform));
+ svg.appendChild(rootGroup);
+ this.svg = rootGroup;
+ return svg;
+ }
+ }, {
+ key: "_ensureClipGroup",
+ value: function _ensureClipGroup() {
+ if (!this.current.clipGroup) {
+ var clipGroup = this.svgFactory.createElement('svg:g');
+ clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl);
+ this.svg.appendChild(clipGroup);
+ this.current.clipGroup = clipGroup;
+ }
+
+ return this.current.clipGroup;
+ }
+ }, {
+ key: "_ensureTransformGroup",
+ value: function _ensureTransformGroup() {
+ if (!this.tgrp) {
+ this.tgrp = this.svgFactory.createElement('svg:g');
+ this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
+
+ if (this.current.activeClipUrl) {
+ this._ensureClipGroup().appendChild(this.tgrp);
+ } else {
+ this.svg.appendChild(this.tgrp);
+ }
+ }
+
+ return this.tgrp;
+ }
+ }]);
+
+ return SVGGraphics;
+ }();
+}
+
+/***/ }),
+/* 165 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.PDFNetworkStream = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+var _network_utils = __w_pdfjs_require__(166);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+;
+var OK_RESPONSE = 200;
+var PARTIAL_CONTENT_RESPONSE = 206;
+
+function getArrayBuffer(xhr) {
+ var data = xhr.response;
+
+ if (typeof data !== 'string') {
+ return data;
+ }
+
+ var array = (0, _util.stringToBytes)(data);
+ return array.buffer;
+}
+
+var NetworkManager =
+/*#__PURE__*/
+function () {
+ function NetworkManager(url, args) {
+ _classCallCheck(this, NetworkManager);
+
+ this.url = url;
+ args = args || {};
+ this.isHttp = /^https?:/i.test(url);
+ this.httpHeaders = this.isHttp && args.httpHeaders || {};
+ this.withCredentials = args.withCredentials || false;
+
+ this.getXhr = args.getXhr || function NetworkManager_getXhr() {
+ return new XMLHttpRequest();
+ };
+
+ this.currXhrId = 0;
+ this.pendingRequests = Object.create(null);
+ }
+
+ _createClass(NetworkManager, [{
+ key: "requestRange",
+ value: function requestRange(begin, end, listeners) {
+ var args = {
+ begin: begin,
+ end: end
+ };
+
+ for (var prop in listeners) {
+ args[prop] = listeners[prop];
+ }
+
+ return this.request(args);
+ }
+ }, {
+ key: "requestFull",
+ value: function requestFull(listeners) {
+ return this.request(listeners);
+ }
+ }, {
+ key: "request",
+ value: function request(args) {
+ var xhr = this.getXhr();
+ var xhrId = this.currXhrId++;
+ var pendingRequest = this.pendingRequests[xhrId] = {
+ xhr: xhr
+ };
+ xhr.open('GET', this.url);
+ xhr.withCredentials = this.withCredentials;
+
+ for (var property in this.httpHeaders) {
+ var value = this.httpHeaders[property];
+
+ if (typeof value === 'undefined') {
+ continue;
+ }
+
+ xhr.setRequestHeader(property, value);
+ }
+
+ if (this.isHttp && 'begin' in args && 'end' in args) {
+ xhr.setRequestHeader('Range', "bytes=".concat(args.begin, "-").concat(args.end - 1));
+ pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
+ } else {
+ pendingRequest.expectedStatus = OK_RESPONSE;
+ }
+
+ xhr.responseType = 'arraybuffer';
+
+ if (args.onError) {
+ xhr.onerror = function (evt) {
+ args.onError(xhr.status);
+ };
+ }
+
+ xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
+ xhr.onprogress = this.onProgress.bind(this, xhrId);
+ pendingRequest.onHeadersReceived = args.onHeadersReceived;
+ pendingRequest.onDone = args.onDone;
+ pendingRequest.onError = args.onError;
+ pendingRequest.onProgress = args.onProgress;
+ xhr.send(null);
+ return xhrId;
+ }
+ }, {
+ key: "onProgress",
+ value: function onProgress(xhrId, evt) {
+ var pendingRequest = this.pendingRequests[xhrId];
+
+ if (!pendingRequest) {
+ return;
+ }
+
+ if (pendingRequest.onProgress) {
+ pendingRequest.onProgress(evt);
+ }
+ }
+ }, {
+ key: "onStateChange",
+ value: function onStateChange(xhrId, evt) {
+ var pendingRequest = this.pendingRequests[xhrId];
+
+ if (!pendingRequest) {
+ return;
+ }
+
+ var xhr = pendingRequest.xhr;
+
+ if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
+ pendingRequest.onHeadersReceived();
+ delete pendingRequest.onHeadersReceived;
+ }
+
+ if (xhr.readyState !== 4) {
+ return;
+ }
+
+ if (!(xhrId in this.pendingRequests)) {
+ return;
+ }
+
+ delete this.pendingRequests[xhrId];
+
+ if (xhr.status === 0 && this.isHttp) {
+ if (pendingRequest.onError) {
+ pendingRequest.onError(xhr.status);
+ }
+
+ return;
+ }
+
+ var xhrStatus = xhr.status || OK_RESPONSE;
+ var ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
+
+ if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
+ if (pendingRequest.onError) {
+ pendingRequest.onError(xhr.status);
+ }
+
+ return;
+ }
+
+ var chunk = getArrayBuffer(xhr);
+
+ if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
+ var rangeHeader = xhr.getResponseHeader('Content-Range');
+ var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
+ pendingRequest.onDone({
+ begin: parseInt(matches[1], 10),
+ chunk: chunk
+ });
+ } else if (chunk) {
+ pendingRequest.onDone({
+ begin: 0,
+ chunk: chunk
+ });
+ } else if (pendingRequest.onError) {
+ pendingRequest.onError(xhr.status);
+ }
+ }
+ }, {
+ key: "hasPendingRequests",
+ value: function hasPendingRequests() {
+ for (var xhrId in this.pendingRequests) {
+ return true;
+ }
+
+ return false;
+ }
+ }, {
+ key: "getRequestXhr",
+ value: function getRequestXhr(xhrId) {
+ return this.pendingRequests[xhrId].xhr;
+ }
+ }, {
+ key: "isPendingRequest",
+ value: function isPendingRequest(xhrId) {
+ return xhrId in this.pendingRequests;
+ }
+ }, {
+ key: "abortAllRequests",
+ value: function abortAllRequests() {
+ for (var xhrId in this.pendingRequests) {
+ this.abortRequest(xhrId | 0);
+ }
+ }
+ }, {
+ key: "abortRequest",
+ value: function abortRequest(xhrId) {
+ var xhr = this.pendingRequests[xhrId].xhr;
+ delete this.pendingRequests[xhrId];
+ xhr.abort();
+ }
+ }]);
+
+ return NetworkManager;
+}();
+
+var PDFNetworkStream =
+/*#__PURE__*/
+function () {
+ function PDFNetworkStream(source) {
+ _classCallCheck(this, PDFNetworkStream);
+
+ this._source = source;
+ this._manager = new NetworkManager(source.url, {
+ httpHeaders: source.httpHeaders,
+ withCredentials: source.withCredentials
+ });
+ this._rangeChunkSize = source.rangeChunkSize;
+ this._fullRequestReader = null;
+ this._rangeRequestReaders = [];
+ }
+
+ _createClass(PDFNetworkStream, [{
+ key: "_onRangeRequestReaderClosed",
+ value: function _onRangeRequestReaderClosed(reader) {
+ var i = this._rangeRequestReaders.indexOf(reader);
+
+ if (i >= 0) {
+ this._rangeRequestReaders.splice(i, 1);
+ }
+ }
+ }, {
+ key: "getFullReader",
+ value: function getFullReader() {
+ (0, _util.assert)(!this._fullRequestReader);
+ this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
+ return this._fullRequestReader;
+ }
+ }, {
+ key: "getRangeReader",
+ value: function getRangeReader(begin, end) {
+ var reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
+ reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
+
+ this._rangeRequestReaders.push(reader);
+
+ return reader;
+ }
+ }, {
+ key: "cancelAllRequests",
+ value: function cancelAllRequests(reason) {
+ if (this._fullRequestReader) {
+ this._fullRequestReader.cancel(reason);
+ }
+
+ var readers = this._rangeRequestReaders.slice(0);
+
+ readers.forEach(function (reader) {
+ reader.cancel(reason);
+ });
+ }
+ }]);
+
+ return PDFNetworkStream;
+}();
+
+exports.PDFNetworkStream = PDFNetworkStream;
+
+var PDFNetworkStreamFullRequestReader =
+/*#__PURE__*/
+function () {
+ function PDFNetworkStreamFullRequestReader(manager, source) {
+ _classCallCheck(this, PDFNetworkStreamFullRequestReader);
+
+ this._manager = manager;
+ var args = {
+ onHeadersReceived: this._onHeadersReceived.bind(this),
+ onDone: this._onDone.bind(this),
+ onError: this._onError.bind(this),
+ onProgress: this._onProgress.bind(this)
+ };
+ this._url = source.url;
+ this._fullRequestId = manager.requestFull(args);
+ this._headersReceivedCapability = (0, _util.createPromiseCapability)();
+ this._disableRange = source.disableRange || false;
+ this._contentLength = source.length;
+ this._rangeChunkSize = source.rangeChunkSize;
+
+ if (!this._rangeChunkSize && !this._disableRange) {
+ this._disableRange = true;
+ }
+
+ this._isStreamingSupported = false;
+ this._isRangeSupported = false;
+ this._cachedChunks = [];
+ this._requests = [];
+ this._done = false;
+ this._storedError = undefined;
+ this._filename = null;
+ this.onProgress = null;
+ }
+
+ _createClass(PDFNetworkStreamFullRequestReader, [{
+ key: "_onHeadersReceived",
+ value: function _onHeadersReceived() {
+ var fullRequestXhrId = this._fullRequestId;
+
+ var fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
+
+ var getResponseHeader = function getResponseHeader(name) {
+ return fullRequestXhr.getResponseHeader(name);
+ };
+
+ var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
+ getResponseHeader: getResponseHeader,
+ isHttp: this._manager.isHttp,
+ rangeChunkSize: this._rangeChunkSize,
+ disableRange: this._disableRange
+ }),
+ allowRangeRequests = _validateRangeRequest.allowRangeRequests,
+ suggestedLength = _validateRangeRequest.suggestedLength;
+
+ if (allowRangeRequests) {
+ this._isRangeSupported = true;
+ }
+
+ this._contentLength = suggestedLength || this._contentLength;
+ this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
+
+ if (this._isRangeSupported) {
+ this._manager.abortRequest(fullRequestXhrId);
+ }
+
+ this._headersReceivedCapability.resolve();
+ }
+ }, {
+ key: "_onDone",
+ value: function _onDone(args) {
+ if (args) {
+ if (this._requests.length > 0) {
+ var requestCapability = this._requests.shift();
+
+ requestCapability.resolve({
+ value: args.chunk,
+ done: false
+ });
+ } else {
+ this._cachedChunks.push(args.chunk);
+ }
+ }
+
+ this._done = true;
+
+ if (this._cachedChunks.length > 0) {
+ return;
+ }
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+ }
+ }, {
+ key: "_onError",
+ value: function _onError(status) {
+ var url = this._url;
+ var exception = (0, _network_utils.createResponseStatusError)(status, url);
+ this._storedError = exception;
+
+ this._headersReceivedCapability.reject(exception);
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.reject(exception);
+ });
+
+ this._requests = [];
+ this._cachedChunks = [];
+ }
+ }, {
+ key: "_onProgress",
+ value: function _onProgress(data) {
+ if (this.onProgress) {
+ this.onProgress({
+ loaded: data.loaded,
+ total: data.lengthComputable ? data.total : this._contentLength
+ });
+ }
+ }
+ }, {
+ key: "read",
+ value: function () {
+ var _read = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee() {
+ var chunk, requestCapability;
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (!this._storedError) {
+ _context.next = 2;
+ break;
+ }
+
+ throw this._storedError;
+
+ case 2:
+ if (!(this._cachedChunks.length > 0)) {
+ _context.next = 5;
+ break;
+ }
+
+ chunk = this._cachedChunks.shift();
+ return _context.abrupt("return", {
+ value: chunk,
+ done: false
+ });
+
+ case 5:
+ if (!this._done) {
+ _context.next = 7;
+ break;
+ }
+
+ return _context.abrupt("return", {
+ value: undefined,
+ done: true
+ });
+
+ case 7:
+ requestCapability = (0, _util.createPromiseCapability)();
+
+ this._requests.push(requestCapability);
+
+ return _context.abrupt("return", requestCapability.promise);
+
+ case 10:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee, this);
+ }));
+
+ function read() {
+ return _read.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ this._done = true;
+
+ this._headersReceivedCapability.reject(reason);
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+
+ if (this._manager.isPendingRequest(this._fullRequestId)) {
+ this._manager.abortRequest(this._fullRequestId);
+ }
+
+ this._fullRequestReader = null;
+ }
+ }, {
+ key: "filename",
+ get: function get() {
+ return this._filename;
+ }
+ }, {
+ key: "isRangeSupported",
+ get: function get() {
+ return this._isRangeSupported;
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return this._isStreamingSupported;
+ }
+ }, {
+ key: "contentLength",
+ get: function get() {
+ return this._contentLength;
+ }
+ }, {
+ key: "headersReady",
+ get: function get() {
+ return this._headersReceivedCapability.promise;
+ }
+ }]);
+
+ return PDFNetworkStreamFullRequestReader;
+}();
+
+var PDFNetworkStreamRangeRequestReader =
+/*#__PURE__*/
+function () {
+ function PDFNetworkStreamRangeRequestReader(manager, begin, end) {
+ _classCallCheck(this, PDFNetworkStreamRangeRequestReader);
+
+ this._manager = manager;
+ var args = {
+ onDone: this._onDone.bind(this),
+ onProgress: this._onProgress.bind(this)
+ };
+ this._requestId = manager.requestRange(begin, end, args);
+ this._requests = [];
+ this._queuedChunk = null;
+ this._done = false;
+ this.onProgress = null;
+ this.onClosed = null;
+ }
+
+ _createClass(PDFNetworkStreamRangeRequestReader, [{
+ key: "_close",
+ value: function _close() {
+ if (this.onClosed) {
+ this.onClosed(this);
+ }
+ }
+ }, {
+ key: "_onDone",
+ value: function _onDone(data) {
+ var chunk = data.chunk;
+
+ if (this._requests.length > 0) {
+ var requestCapability = this._requests.shift();
+
+ requestCapability.resolve({
+ value: chunk,
+ done: false
+ });
+ } else {
+ this._queuedChunk = chunk;
+ }
+
+ this._done = true;
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+
+ this._close();
+ }
+ }, {
+ key: "_onProgress",
+ value: function _onProgress(evt) {
+ if (!this.isStreamingSupported && this.onProgress) {
+ this.onProgress({
+ loaded: evt.loaded
+ });
+ }
+ }
+ }, {
+ key: "read",
+ value: function () {
+ var _read2 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee2() {
+ var chunk, requestCapability;
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
+ while (1) {
+ switch (_context2.prev = _context2.next) {
+ case 0:
+ if (!(this._queuedChunk !== null)) {
+ _context2.next = 4;
+ break;
+ }
+
+ chunk = this._queuedChunk;
+ this._queuedChunk = null;
+ return _context2.abrupt("return", {
+ value: chunk,
+ done: false
+ });
+
+ case 4:
+ if (!this._done) {
+ _context2.next = 6;
+ break;
+ }
+
+ return _context2.abrupt("return", {
+ value: undefined,
+ done: true
+ });
+
+ case 6:
+ requestCapability = (0, _util.createPromiseCapability)();
+
+ this._requests.push(requestCapability);
+
+ return _context2.abrupt("return", requestCapability.promise);
+
+ case 9:
+ case "end":
+ return _context2.stop();
+ }
+ }
+ }, _callee2, this);
+ }));
+
+ function read() {
+ return _read2.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ this._done = true;
+
+ this._requests.forEach(function (requestCapability) {
+ requestCapability.resolve({
+ value: undefined,
+ done: true
+ });
+ });
+
+ this._requests = [];
+
+ if (this._manager.isPendingRequest(this._requestId)) {
+ this._manager.abortRequest(this._requestId);
+ }
+
+ this._close();
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return false;
+ }
+ }]);
+
+ return PDFNetworkStreamRangeRequestReader;
+}();
+
+/***/ }),
+/* 166 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.createResponseStatusError = createResponseStatusError;
+exports.extractFilenameFromHeader = extractFilenameFromHeader;
+exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
+exports.validateResponseStatus = validateResponseStatus;
+
+var _util = __w_pdfjs_require__(1);
+
+var _content_disposition = __w_pdfjs_require__(167);
+
+function validateRangeRequestCapabilities(_ref) {
+ var getResponseHeader = _ref.getResponseHeader,
+ isHttp = _ref.isHttp,
+ rangeChunkSize = _ref.rangeChunkSize,
+ disableRange = _ref.disableRange;
+ (0, _util.assert)(rangeChunkSize > 0, 'Range chunk size must be larger than zero');
+ var returnValues = {
+ allowRangeRequests: false,
+ suggestedLength: undefined
+ };
+ var length = parseInt(getResponseHeader('Content-Length'), 10);
+
+ if (!Number.isInteger(length)) {
+ return returnValues;
+ }
+
+ returnValues.suggestedLength = length;
+
+ if (length <= 2 * rangeChunkSize) {
+ return returnValues;
+ }
+
+ if (disableRange || !isHttp) {
+ return returnValues;
+ }
+
+ if (getResponseHeader('Accept-Ranges') !== 'bytes') {
+ return returnValues;
+ }
+
+ var contentEncoding = getResponseHeader('Content-Encoding') || 'identity';
+
+ if (contentEncoding !== 'identity') {
+ return returnValues;
+ }
+
+ returnValues.allowRangeRequests = true;
+ return returnValues;
+}
+
+function extractFilenameFromHeader(getResponseHeader) {
+ var contentDisposition = getResponseHeader('Content-Disposition');
+
+ if (contentDisposition) {
+ var filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
+
+ if (/\.pdf$/i.test(filename)) {
+ return filename;
+ }
+ }
+
+ return null;
+}
+
+function createResponseStatusError(status, url) {
+ if (status === 404 || status === 0 && /^file:/.test(url)) {
+ return new _util.MissingPDFException('Missing PDF "' + url + '".');
+ }
+
+ return new _util.UnexpectedResponseException('Unexpected server response (' + status + ') while retrieving PDF "' + url + '".', status);
+}
+
+function validateResponseStatus(status) {
+ return status === 200 || status === 206;
+}
+
+/***/ }),
+/* 167 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
+
+function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
+
+function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
+
+function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+function getFilenameFromContentDispositionHeader(contentDisposition) {
+ var needsEncodingFixup = true;
+ var tmp = toParamRegExp('filename\\*', 'i').exec(contentDisposition);
+
+ if (tmp) {
+ tmp = tmp[1];
+ var filename = rfc2616unquote(tmp);
+ filename = unescape(filename);
+ filename = rfc5987decode(filename);
+ filename = rfc2047decode(filename);
+ return fixupEncoding(filename);
+ }
+
+ tmp = rfc2231getparam(contentDisposition);
+
+ if (tmp) {
+ var _filename = rfc2047decode(tmp);
+
+ return fixupEncoding(_filename);
+ }
+
+ tmp = toParamRegExp('filename', 'i').exec(contentDisposition);
+
+ if (tmp) {
+ tmp = tmp[1];
+
+ var _filename2 = rfc2616unquote(tmp);
+
+ _filename2 = rfc2047decode(_filename2);
+ return fixupEncoding(_filename2);
+ }
+
+ function toParamRegExp(attributePattern, flags) {
+ return new RegExp('(?:^|;)\\s*' + attributePattern + '\\s*=\\s*' + '(' + '[^";\\s][^;\\s]*' + '|' + '"(?:[^"\\\\]|\\\\"?)+"?' + ')', flags);
+ }
+
+ function textdecode(encoding, value) {
+ if (encoding) {
+ if (!/^[\x00-\xFF]+$/.test(value)) {
+ return value;
+ }
+
+ try {
+ var decoder = new TextDecoder(encoding, {
+ fatal: true
+ });
+ var bytes = Array.from(value, function (ch) {
+ return ch.charCodeAt(0) & 0xFF;
+ });
+ value = decoder.decode(new Uint8Array(bytes));
+ needsEncodingFixup = false;
+ } catch (e) {
+ if (/^utf-?8$/i.test(encoding)) {
+ try {
+ value = decodeURIComponent(escape(value));
+ needsEncodingFixup = false;
+ } catch (err) {}
+ }
+ }
+ }
+
+ return value;
+ }
+
+ function fixupEncoding(value) {
+ if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
+ value = textdecode('utf-8', value);
+
+ if (needsEncodingFixup) {
+ value = textdecode('iso-8859-1', value);
+ }
+ }
+
+ return value;
+ }
+
+ function rfc2231getparam(contentDisposition) {
+ var matches = [],
+ match;
+ var iter = toParamRegExp('filename\\*((?!0\\d)\\d+)(\\*?)', 'ig');
+
+ while ((match = iter.exec(contentDisposition)) !== null) {
+ var _match = match,
+ _match2 = _slicedToArray(_match, 4),
+ n = _match2[1],
+ quot = _match2[2],
+ part = _match2[3];
+
+ n = parseInt(n, 10);
+
+ if (n in matches) {
+ if (n === 0) {
+ break;
+ }
+
+ continue;
+ }
+
+ matches[n] = [quot, part];
+ }
+
+ var parts = [];
+
+ for (var n = 0; n < matches.length; ++n) {
+ if (!(n in matches)) {
+ break;
+ }
+
+ var _matches$n = _slicedToArray(matches[n], 2),
+ quot = _matches$n[0],
+ part = _matches$n[1];
+
+ part = rfc2616unquote(part);
+
+ if (quot) {
+ part = unescape(part);
+
+ if (n === 0) {
+ part = rfc5987decode(part);
+ }
+ }
+
+ parts.push(part);
+ }
+
+ return parts.join('');
+ }
+
+ function rfc2616unquote(value) {
+ if (value.startsWith('"')) {
+ var parts = value.slice(1).split('\\"');
+
+ for (var i = 0; i < parts.length; ++i) {
+ var quotindex = parts[i].indexOf('"');
+
+ if (quotindex !== -1) {
+ parts[i] = parts[i].slice(0, quotindex);
+ parts.length = i + 1;
+ }
+
+ parts[i] = parts[i].replace(/\\(.)/g, '$1');
+ }
+
+ value = parts.join('"');
+ }
+
+ return value;
+ }
+
+ function rfc5987decode(extvalue) {
+ var encodingend = extvalue.indexOf('\'');
+
+ if (encodingend === -1) {
+ return extvalue;
+ }
+
+ var encoding = extvalue.slice(0, encodingend);
+ var langvalue = extvalue.slice(encodingend + 1);
+ var value = langvalue.replace(/^[^']*'/, '');
+ return textdecode(encoding, value);
+ }
+
+ function rfc2047decode(value) {
+ if (!value.startsWith('=?') || /[\x00-\x19\x80-\xff]/.test(value)) {
+ return value;
+ }
+
+ return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (_, charset, encoding, text) {
+ if (encoding === 'q' || encoding === 'Q') {
+ text = text.replace(/_/g, ' ');
+ text = text.replace(/=([0-9a-fA-F]{2})/g, function (_, hex) {
+ return String.fromCharCode(parseInt(hex, 16));
+ });
+ return textdecode(charset, text);
+ }
+
+ try {
+ text = atob(text);
+ } catch (e) {}
+
+ return textdecode(charset, text);
+ });
+ }
+
+ return '';
+}
+
+/***/ }),
+/* 168 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.PDFFetchStream = void 0;
+
+var _regenerator = _interopRequireDefault(__w_pdfjs_require__(148));
+
+var _util = __w_pdfjs_require__(1);
+
+var _network_utils = __w_pdfjs_require__(166);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+function createFetchOptions(headers, withCredentials, abortController) {
+ return {
+ method: 'GET',
+ headers: headers,
+ signal: abortController && abortController.signal,
+ mode: 'cors',
+ credentials: withCredentials ? 'include' : 'same-origin',
+ redirect: 'follow'
+ };
+}
+
+var PDFFetchStream =
+/*#__PURE__*/
+function () {
+ function PDFFetchStream(source) {
+ _classCallCheck(this, PDFFetchStream);
+
+ this.source = source;
+ this.isHttp = /^https?:/i.test(source.url);
+ this.httpHeaders = this.isHttp && source.httpHeaders || {};
+ this._fullRequestReader = null;
+ this._rangeRequestReaders = [];
+ }
+
+ _createClass(PDFFetchStream, [{
+ key: "getFullReader",
+ value: function getFullReader() {
+ (0, _util.assert)(!this._fullRequestReader);
+ this._fullRequestReader = new PDFFetchStreamReader(this);
+ return this._fullRequestReader;
+ }
+ }, {
+ key: "getRangeReader",
+ value: function getRangeReader(begin, end) {
+ if (end <= this._progressiveDataLength) {
+ return null;
+ }
+
+ var reader = new PDFFetchStreamRangeReader(this, begin, end);
+
+ this._rangeRequestReaders.push(reader);
+
+ return reader;
+ }
+ }, {
+ key: "cancelAllRequests",
+ value: function cancelAllRequests(reason) {
+ if (this._fullRequestReader) {
+ this._fullRequestReader.cancel(reason);
+ }
+
+ var readers = this._rangeRequestReaders.slice(0);
+
+ readers.forEach(function (reader) {
+ reader.cancel(reason);
+ });
+ }
+ }, {
+ key: "_progressiveDataLength",
+ get: function get() {
+ return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
+ }
+ }]);
+
+ return PDFFetchStream;
+}();
+
+exports.PDFFetchStream = PDFFetchStream;
+
+var PDFFetchStreamReader =
+/*#__PURE__*/
+function () {
+ function PDFFetchStreamReader(stream) {
+ var _this = this;
+
+ _classCallCheck(this, PDFFetchStreamReader);
+
+ this._stream = stream;
+ this._reader = null;
+ this._loaded = 0;
+ this._filename = null;
+ var source = stream.source;
+ this._withCredentials = source.withCredentials || false;
+ this._contentLength = source.length;
+ this._headersCapability = (0, _util.createPromiseCapability)();
+ this._disableRange = source.disableRange || false;
+ this._rangeChunkSize = source.rangeChunkSize;
+
+ if (!this._rangeChunkSize && !this._disableRange) {
+ this._disableRange = true;
+ }
+
+ if (typeof AbortController !== 'undefined') {
+ this._abortController = new AbortController();
+ }
+
+ this._isStreamingSupported = !source.disableStream;
+ this._isRangeSupported = !source.disableRange;
+ this._headers = new Headers();
+
+ for (var property in this._stream.httpHeaders) {
+ var value = this._stream.httpHeaders[property];
+
+ if (typeof value === 'undefined') {
+ continue;
+ }
+
+ this._headers.append(property, value);
+ }
+
+ var url = source.url;
+ fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(function (response) {
+ if (!(0, _network_utils.validateResponseStatus)(response.status)) {
+ throw (0, _network_utils.createResponseStatusError)(response.status, url);
+ }
+
+ _this._reader = response.body.getReader();
+
+ _this._headersCapability.resolve();
+
+ var getResponseHeader = function getResponseHeader(name) {
+ return response.headers.get(name);
+ };
+
+ var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
+ getResponseHeader: getResponseHeader,
+ isHttp: _this._stream.isHttp,
+ rangeChunkSize: _this._rangeChunkSize,
+ disableRange: _this._disableRange
+ }),
+ allowRangeRequests = _validateRangeRequest.allowRangeRequests,
+ suggestedLength = _validateRangeRequest.suggestedLength;
+
+ _this._isRangeSupported = allowRangeRequests;
+ _this._contentLength = suggestedLength || _this._contentLength;
+ _this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
+
+ if (!_this._isStreamingSupported && _this._isRangeSupported) {
+ _this.cancel(new _util.AbortException('Streaming is disabled.'));
+ }
+ })["catch"](this._headersCapability.reject);
+ this.onProgress = null;
+ }
+
+ _createClass(PDFFetchStreamReader, [{
+ key: "read",
+ value: function () {
+ var _read = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee() {
+ var _ref, value, done, buffer;
+
+ return _regenerator["default"].wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ _context.next = 2;
+ return this._headersCapability.promise;
+
+ case 2:
+ _context.next = 4;
+ return this._reader.read();
+
+ case 4:
+ _ref = _context.sent;
+ value = _ref.value;
+ done = _ref.done;
+
+ if (!done) {
+ _context.next = 9;
+ break;
+ }
+
+ return _context.abrupt("return", {
+ value: value,
+ done: done
+ });
+
+ case 9:
+ this._loaded += value.byteLength;
+
+ if (this.onProgress) {
+ this.onProgress({
+ loaded: this._loaded,
+ total: this._contentLength
+ });
+ }
+
+ buffer = new Uint8Array(value).buffer;
+ return _context.abrupt("return", {
+ value: buffer,
+ done: false
+ });
+
+ case 13:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee, this);
+ }));
+
+ function read() {
+ return _read.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ if (this._reader) {
+ this._reader.cancel(reason);
+ }
+
+ if (this._abortController) {
+ this._abortController.abort();
+ }
+ }
+ }, {
+ key: "headersReady",
+ get: function get() {
+ return this._headersCapability.promise;
+ }
+ }, {
+ key: "filename",
+ get: function get() {
+ return this._filename;
+ }
+ }, {
+ key: "contentLength",
+ get: function get() {
+ return this._contentLength;
+ }
+ }, {
+ key: "isRangeSupported",
+ get: function get() {
+ return this._isRangeSupported;
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return this._isStreamingSupported;
+ }
+ }]);
+
+ return PDFFetchStreamReader;
+}();
+
+var PDFFetchStreamRangeReader =
+/*#__PURE__*/
+function () {
+ function PDFFetchStreamRangeReader(stream, begin, end) {
+ var _this2 = this;
+
+ _classCallCheck(this, PDFFetchStreamRangeReader);
+
+ this._stream = stream;
+ this._reader = null;
+ this._loaded = 0;
+ var source = stream.source;
+ this._withCredentials = source.withCredentials || false;
+ this._readCapability = (0, _util.createPromiseCapability)();
+ this._isStreamingSupported = !source.disableStream;
+
+ if (typeof AbortController !== 'undefined') {
+ this._abortController = new AbortController();
+ }
+
+ this._headers = new Headers();
+
+ for (var property in this._stream.httpHeaders) {
+ var value = this._stream.httpHeaders[property];
+
+ if (typeof value === 'undefined') {
+ continue;
+ }
+
+ this._headers.append(property, value);
+ }
+
+ this._headers.append('Range', "bytes=".concat(begin, "-").concat(end - 1));
+
+ var url = source.url;
+ fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(function (response) {
+ if (!(0, _network_utils.validateResponseStatus)(response.status)) {
+ throw (0, _network_utils.createResponseStatusError)(response.status, url);
+ }
+
+ _this2._readCapability.resolve();
+
+ _this2._reader = response.body.getReader();
+ })["catch"](this._readCapability.reject);
+ this.onProgress = null;
+ }
+
+ _createClass(PDFFetchStreamRangeReader, [{
+ key: "read",
+ value: function () {
+ var _read2 = _asyncToGenerator(
+ /*#__PURE__*/
+ _regenerator["default"].mark(function _callee2() {
+ var _ref2, value, done, buffer;
+
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
+ while (1) {
+ switch (_context2.prev = _context2.next) {
+ case 0:
+ _context2.next = 2;
+ return this._readCapability.promise;
+
+ case 2:
+ _context2.next = 4;
+ return this._reader.read();
+
+ case 4:
+ _ref2 = _context2.sent;
+ value = _ref2.value;
+ done = _ref2.done;
+
+ if (!done) {
+ _context2.next = 9;
+ break;
+ }
+
+ return _context2.abrupt("return", {
+ value: value,
+ done: done
+ });
+
+ case 9:
+ this._loaded += value.byteLength;
+
+ if (this.onProgress) {
+ this.onProgress({
+ loaded: this._loaded
+ });
+ }
+
+ buffer = new Uint8Array(value).buffer;
+ return _context2.abrupt("return", {
+ value: buffer,
+ done: false
+ });
+
+ case 13:
+ case "end":
+ return _context2.stop();
+ }
+ }
+ }, _callee2, this);
+ }));
+
+ function read() {
+ return _read2.apply(this, arguments);
+ }
+
+ return read;
+ }()
+ }, {
+ key: "cancel",
+ value: function cancel(reason) {
+ if (this._reader) {
+ this._reader.cancel(reason);
+ }
+
+ if (this._abortController) {
+ this._abortController.abort();
+ }
+ }
+ }, {
+ key: "isStreamingSupported",
+ get: function get() {
+ return this._isStreamingSupported;
+ }
+ }]);
+
+ return PDFFetchStreamRangeReader;
+}();
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=pdf.js.map
\ No newline at end of file
diff --git a/services/web/frontend/js/vendor/libs/pdfjs-dist/build/pdf.js.map b/services/web/frontend/js/vendor/libs/pdfjs-dist/build/pdf.js.map
new file mode 100644
index 0000000000..78244846bc
--- /dev/null
+++ b/services/web/frontend/js/vendor/libs/pdfjs-dist/build/pdf.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://pdfjs-dist/build/pdf/webpack/universalModuleDefinition","webpack://pdfjs-dist/build/pdf/webpack/bootstrap","webpack://pdfjs-dist/build/pdf/src/pdf.js","webpack://pdfjs-dist/build/pdf/src/shared/util.js","webpack://pdfjs-dist/build/pdf/src/shared/compatibility.js","webpack://pdfjs-dist/build/pdf/src/shared/global_scope.js","webpack://pdfjs-dist/build/pdf/src/shared/is_node.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/starts-with.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.starts-with.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_export.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_global.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_core.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_hide.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-dp.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_an-object.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_is-object.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_ie8-dom-define.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_descriptors.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_fails.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_dom-create.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-primitive.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_property-desc.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_redefine.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_has.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_uid.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_function-to-string.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_shared.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_library.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_ctx.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_a-function.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-length.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-integer.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_string-context.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_is-regexp.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_cof.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_wks.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_defined.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_fails-is-regexp.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/ends-with.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.ends-with.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/includes.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.includes.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/array/includes.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.array.includes.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_array-includes.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-iobject.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iobject.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-absolute-index.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_add-to-unscopables.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/array/from.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.iterator.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_string-at.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iter-define.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iterators.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iter-create.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-create.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-dps.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-keys.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-keys-internal.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_shared-key.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_enum-bug-keys.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_html.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_set-to-string-tag.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-gpo.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_to-object.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.array.from.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iter-call.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_is-array-iter.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_create-property.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/core.get-iterator-method.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_classof.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iter-detect.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/object/assign.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.object.assign.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-assign.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-gops.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-pie.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/math/log2.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.math.log2.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/number/is-nan.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.number.is-nan.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/number/is-integer.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.number.is-integer.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_is-integer.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/promise.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.object.to-string.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/web.dom.iterable.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.array.iterator.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_iter-step.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.promise.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_an-instance.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_for-of.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_species-constructor.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_task.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_invoke.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_microtask.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_new-promise-capability.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_perform.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_user-agent.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_promise-resolve.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_redefine-all.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_set-species.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.promise.finally.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.promise.try.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/weak-map.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.weak-map.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_array-methods.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_array-species-create.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_array-species-constructor.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_is-array.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_meta.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_collection-weak.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_validate-collection.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_collection.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_inherit-if-required.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_set-proto.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-gopd.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.weak-map.of.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_set-collection-of.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.weak-map.from.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_set-collection-from.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/weak-set.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.weak-set.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.weak-set.of.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.weak-set.from.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/code-point-at.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.code-point-at.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/from-code-point.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.string.from-code-point.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/es6/symbol.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es6.symbol.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_wks-ext.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_wks-define.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_enum-keys.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-gopn-ext.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-gopn.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/pad-start.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.string.pad-start.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_string-pad.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_string-repeat.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/string/pad-end.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.string.pad-end.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/fn/object/values.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/es7.object.values.js","webpack://pdfjs-dist/build/pdf/node_modules/core-js/modules/_object-to-array.js","webpack://pdfjs-dist/build/pdf/src/shared/streams_polyfill.js","webpack://pdfjs-dist/build/pdf/external/streams/streams-lib.js","webpack://pdfjs-dist/build/pdf/src/shared/url_polyfill.js","webpack://pdfjs-dist/build/pdf/external/url/url-lib.js","webpack://pdfjs-dist/build/pdf/src/display/api.js","webpack://pdfjs-dist/build/pdf/node_modules/@babel/runtime/regenerator/index.js","webpack://pdfjs-dist/build/pdf/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js","webpack://pdfjs-dist/build/pdf/node_modules/webpack/buildin/module.js","webpack://pdfjs-dist/build/pdf/src/display/display_utils.js","webpack://pdfjs-dist/build/pdf/src/display/font_loader.js","webpack://pdfjs-dist/build/pdf/src/display/api_compatibility.js","webpack://pdfjs-dist/build/pdf/src/display/canvas.js","webpack://pdfjs-dist/build/pdf/src/display/pattern_helper.js","webpack://pdfjs-dist/build/pdf/src/display/worker_options.js","webpack://pdfjs-dist/build/pdf/src/shared/message_handler.js","webpack://pdfjs-dist/build/pdf/src/display/metadata.js","webpack://pdfjs-dist/build/pdf/src/display/xml_parser.js","webpack://pdfjs-dist/build/pdf/src/display/transport_stream.js","webpack://pdfjs-dist/build/pdf/src/display/webgl.js","webpack://pdfjs-dist/build/pdf/src/display/text_layer.js","webpack://pdfjs-dist/build/pdf/src/display/annotation_layer.js","webpack://pdfjs-dist/build/pdf/src/display/svg.js","webpack://pdfjs-dist/build/pdf/src/display/network.js","webpack://pdfjs-dist/build/pdf/src/display/network_utils.js","webpack://pdfjs-dist/build/pdf/src/display/content_disposition.js","webpack://pdfjs-dist/build/pdf/src/display/fetch_stream.js"],"names":["pdfjsVersion","pdfjsBuild","pdfjsSharedUtil","require","pdfjsDisplayAPI","pdfjsDisplayTextLayer","pdfjsDisplayAnnotationLayer","pdfjsDisplayDisplayUtils","pdfjsDisplaySVG","pdfjsDisplayWorkerOptions","pdfjsDisplayAPICompatibility","isNodeJS","PDFNetworkStream","PDFFetchStream","params","exports","IDENTITY_MATRIX","FONT_IDENTITY_MATRIX","NativeImageDecoding","NONE","DECODE","DISPLAY","PermissionFlag","PRINT","MODIFY_CONTENTS","COPY","MODIFY_ANNOTATIONS","FILL_INTERACTIVE_FORMS","COPY_FOR_ACCESSIBILITY","ASSEMBLE","PRINT_HIGH_QUALITY","TextRenderingMode","FILL","STROKE","FILL_STROKE","INVISIBLE","FILL_ADD_TO_PATH","STROKE_ADD_TO_PATH","FILL_STROKE_ADD_TO_PATH","ADD_TO_PATH","FILL_STROKE_MASK","ADD_TO_PATH_FLAG","ImageKind","GRAYSCALE_1BPP","RGB_24BPP","RGBA_32BPP","AnnotationType","TEXT","LINK","FREETEXT","LINE","SQUARE","CIRCLE","POLYGON","POLYLINE","HIGHLIGHT","UNDERLINE","SQUIGGLY","STRIKEOUT","STAMP","CARET","INK","POPUP","FILEATTACHMENT","SOUND","MOVIE","WIDGET","SCREEN","PRINTERMARK","TRAPNET","WATERMARK","THREED","REDACT","AnnotationFlag","HIDDEN","NOZOOM","NOROTATE","NOVIEW","READONLY","LOCKED","TOGGLENOVIEW","LOCKEDCONTENTS","AnnotationFieldFlag","REQUIRED","NOEXPORT","MULTILINE","PASSWORD","NOTOGGLETOOFF","RADIO","PUSHBUTTON","COMBO","EDIT","SORT","FILESELECT","MULTISELECT","DONOTSPELLCHECK","DONOTSCROLL","COMB","RICHTEXT","RADIOSINUNISON","COMMITONSELCHANGE","AnnotationBorderStyleType","SOLID","DASHED","BEVELED","INSET","StreamType","UNKNOWN","FLATE","LZW","DCT","JPX","JBIG","A85","AHX","CCF","RL","FontType","TYPE1","TYPE1C","CIDFONTTYPE0","CIDFONTTYPE0C","TRUETYPE","CIDFONTTYPE2","TYPE3","OPENTYPE","TYPE0","MMTYPE1","VerbosityLevel","ERRORS","WARNINGS","INFOS","CMapCompressionType","BINARY","STREAM","OPS","dependency","setLineWidth","setLineCap","setLineJoin","setMiterLimit","setDash","setRenderingIntent","setFlatness","setGState","save","restore","transform","moveTo","lineTo","curveTo","curveTo2","curveTo3","closePath","rectangle","stroke","closeStroke","fill","eoFill","fillStroke","eoFillStroke","closeFillStroke","closeEOFillStroke","endPath","clip","eoClip","beginText","endText","setCharSpacing","setWordSpacing","setHScale","setLeading","setFont","setTextRenderingMode","setTextRise","moveText","setLeadingMoveText","setTextMatrix","nextLine","showText","showSpacedText","nextLineShowText","nextLineSetSpacingShowText","setCharWidth","setCharWidthAndBounds","setStrokeColorSpace","setFillColorSpace","setStrokeColor","setStrokeColorN","setFillColor","setFillColorN","setStrokeGray","setFillGray","setStrokeRGBColor","setFillRGBColor","setStrokeCMYKColor","setFillCMYKColor","shadingFill","beginInlineImage","beginImageData","endInlineImage","paintXObject","markPoint","markPointProps","beginMarkedContent","beginMarkedContentProps","endMarkedContent","beginCompat","endCompat","paintFormXObjectBegin","paintFormXObjectEnd","beginGroup","endGroup","beginAnnotations","endAnnotations","beginAnnotation","endAnnotation","paintJpegXObject","paintImageMaskXObject","paintImageMaskXObjectGroup","paintImageXObject","paintInlineImageXObject","paintInlineImageXObjectGroup","paintImageXObjectRepeat","paintImageMaskXObjectRepeat","paintSolidColorImageMask","constructPath","UNSUPPORTED_FEATURES","unknown","forms","javaScript","smask","shadingPattern","font","PasswordResponses","NEED_PASSWORD","INCORRECT_PASSWORD","verbosity","Number","console","unreachable","base","other","url","absoluteUrl","baseUrl","_isValidProtocol","Object","value","enumerable","configurable","writable","PasswordException","UnknownErrorException","InvalidPDFException","MissingPDFException","UnexpectedResponseException","FormatError","AbortException","NullCharactersRegExp","warn","str","assert","bytes","length","MAX_ARGUMENT_COUNT","String","strBuf","i","chunkEnd","Math","chunk","arr","resultLength","ii","item","itemLength","arrayByteLength","pos","data","stringToBytes","x","offset","buffer8","view32","Util","rgbBuf","m1","m2","xt","p","m","yt","d","p1","p2","r","p3","p4","v","transpose","a","b","c","first","second","sx","sy","rect","orderedX","rect1","rect2","orderedY","result","PDFStringTranslateTable","n","code","decodeURIComponent","escape","unescape","encodeURIComponent","arr1","arr2","element","ch","capability","isSettled","get","resolve","reject","createObjectURL","digits","forceDataSchema","URL","blob","type","buffer","b1","b2","b3","d1","d2","d3","d4","globalScope","hasDOM","Buffer","Element","div","document","OriginalDOMTokenListAdd","DOMTokenList","OriginalDOMTokenListRemove","token","force","arguments","Array","module","window","global","self","process","$export","toLength","context","STARTS_WITH","$startsWith","startsWith","that","index","search","core","hide","redefine","ctx","PROTOTYPE","IS_FORCED","IS_GLOBAL","IS_STATIC","IS_PROTO","IS_BIND","target","expProto","source","own","out","exp","Function","__g","version","__e","dP","createDesc","object","anObject","IE8_DOM_DEFINE","toPrimitive","P","TypeError","O","Attributes","isObject","it","exec","is","S","val","fn","has","SRC","$toString","TO_STRING","TPL","isFunction","hasOwnProperty","id","px","key","SHARED","store","mode","copyright","aFunction","toInteger","min","ceil","floor","isNaN","isRegExp","defined","cof","MATCH","toString","uid","Symbol","USE_SYMBOL","$exports","re","ENDS_WITH","$endsWith","endsWith","endPosition","len","end","INCLUDES","includes","$includes","toIObject","toAbsoluteIndex","IS_INCLUDES","el","IObject","max","UNSCOPABLES","ArrayProto","$at","done","point","s","l","LIBRARY","Iterators","$iterCreate","setToStringTag","getPrototypeOf","ITERATOR","BUGGY","FF_ITERATOR","KEYS","VALUES","returnThis","getMethod","kind","proto","TAG","NAME","DEF_VALUES","DEFAULT","VALUES_BUG","Base","$native","$default","$entries","$anyNative","IteratorPrototype","methods","values","keys","IS_SET","entries","create","descriptor","Constructor","next","dPs","enumBugKeys","IE_PROTO","Empty","createDict","iframe","lt","gt","iframeDocument","Properties","getKeys","$keys","arrayIndexOf","names","shared","def","stat","toObject","ObjectProto","call","isArrayIter","createProperty","getIterFn","from","C","aLen","mapfn","mapping","iterFn","iterator","step","ret","$defineProperty","classof","ARG","tryGet","SAFE_CLOSING","riter","safe","iter","assign","DESCRIPTORS","gOPS","pIE","$assign","A","B","K","T","getSymbols","isEnum","j","log2","number","isInteger","isFinite","test","$iterators","wks","TO_STRING_TAG","ArrayValues","DOMIterables","CSSRuleList","CSSStyleDeclaration","CSSValueList","ClientRectList","DOMRectList","DOMStringList","DataTransferItemList","FileList","HTMLAllCollection","HTMLCollection","HTMLFormElement","HTMLSelectElement","MediaList","MimeTypeArray","NamedNodeMap","NodeList","PaintRequestList","Plugin","PluginArray","SVGLengthList","SVGNumberList","SVGPathSegList","SVGPointList","SVGStringList","SVGTransformList","SourceBufferList","StyleSheetList","TextTrackCueList","TextTrackList","TouchList","collections","explicit","Collection","addToUnscopables","anInstance","forOf","speciesConstructor","task","microtask","newPromiseCapabilityModule","perform","userAgent","promiseResolve","PROMISE","versions","v8","$Promise","isNode","empty","newPromiseCapability","newGenericPromiseCapability","USE_NATIVE","promise","FakePromise","isThenable","notify","chain","ok","run","handler","reaction","domain","onHandleUnhandled","exited","then","isReject","onUnhandled","unhandled","isUnhandled","reason","$reject","$resolve","wrapper","_w","_d","Internal","executor","OwnPromiseCapability","Promise","Wrapper","$$reject","all","remaining","$index","alreadyCalled","race","forbiddenField","name","BREAK","RETURN","f","iterable","SPECIES","invoke","html","cel","setTask","clearTask","MessageChannel","Dispatch","counter","queue","ONREADYSTATECHANGE","listener","event","args","defer","channel","port","setTimeout","set","clear","un","macrotask","Observer","flush","parent","head","last","toggle","node","characterData","e","navigator","promiseCapability","src","onFinally","each","meta","weak","validate","NATIVE_WEAK_MAP","IS_IE11","WEAK_MAP","getWeak","isExtensible","uncaughtFrozenStore","$WeakMap","InternalMap","method","asc","IS_MAP","TYPE","IS_FILTER","IS_SOME","IS_EVERY","IS_FIND_INDEX","NO_HOLES","$create","res","isArray","original","META","setDesc","FREEZE","setMeta","w","fastKey","onFreeze","KEY","NEED","redefineAll","createArrayMethod","$has","arrayFind","arrayFindIndex","UncaughtFrozenStore","findUncaughtFrozen","entry","getConstructor","ufstore","fails","$iterDetect","inheritIfRequired","ADDER","fixMethod","IS_WEAK","common","instance","HASNT_CHAINING","THROWS_ON_PRIMITIVES","ACCEPT_ITERABLES","BUGGY_ZERO","$instance","setPrototypeOf","check","buggy","gOPD","of","mapFn","cb","WEAK_SET","add","codePointAt","fromCharCode","$fromCodePoint","fromCodePoint","RangeError","$fails","wksExt","wksDefine","enumKeys","_create","gOPNExt","$GOPD","$GOPS","$DP","gOPN","$Symbol","$JSON","_stringify","TO_PRIMITIVE","SymbolRegistry","AllSymbols","OPSymbols","QObject","setter","setSymbolDesc","protoDesc","wrap","sym","isSymbol","D","$defineProperties","$propertyIsEnumerable","E","$getOwnPropertyDescriptor","$getOwnPropertyNames","$getOwnPropertySymbols","IS_OP","tag","$set","es6Symbols","wellKnownSymbols","k","keyFor","useSetter","useSimple","defineProperty","defineProperties","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","FAILS_ON_PRIMITIVES","stringify","$replacer","replacer","symbols","windowNames","getWindowNames","hiddenKeys","$pad","WEBKIT_BUG","padStart","repeat","stringLength","fillStr","fillString","intMaxLength","fillLen","stringFiller","left","padEnd","$values","isReadableStreamSupported","start","controller","installedModules","modules","__w_pdfjs_require__","getter","_typeof","obj","_require","elements","IsPropertyKey","Call","F","highWaterMark","size","message","AssertionError","Error","rethrowAssertionErrorRejection","_createClass","props","InvokeOrNoop","PromiseInvokeOrNoop","ValidateAndNormalizeQueuingStrategy","typeIsObject","_require2","_require3","DequeueValue","EnqueueValueWithSize","PeekQueueValue","ResetQueue","WritableStream","underlyingSink","_ref","_ref$highWaterMark","_classCallCheck","IsWritableStream","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","AcquireWritableStreamDefaultWriter","WritableStreamDefaultControllerError","WritableStreamDefaultWriterCloseWithErrorPropagation","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamCloseQueuedOrInFlight","stream","state","error","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","writeRequest","WritableStreamFinishErroring","writer","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","WritableStreamDealWithRejection","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseReject","backpressure","defaultWriterReadyPromiseReset","defaultWriterReadyPromiseResolve","WritableStreamDefaultWriter","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseInitializeAsResolved","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterGetDesiredSize","closeRequest","WritableStreamDefaultControllerClose","defaultWriterClosedPromiseResetToRejected","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","WritableStreamDefaultControllerGetDesiredSize","releasedError","WritableStreamDefaultWriterEnsureClosedPromiseRejected","chunkSize","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","WritableStreamDefaultControllerWrite","WritableStreamDefaultController","normalizedStrategy","WritableStreamDefaultControllerGetBackpressure","WritableStreamUpdateBackpressure","IsWritableStreamDefaultController","_this","startResult","WritableStreamDefaultControllerAdvanceQueueIfNeeded","strategySize","WritableStreamDefaultControllerErrorIfNeeded","writeRecord","WritableStreamDefaultControllerProcessClose","WritableStreamDefaultControllerProcessWrite","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","desiredSize","IsFiniteNonNegativeNumber","container","pair","ArrayBufferCopy","CreateIterResultObject","TransferArrayBuffer","ValidateAndNormalizeHighWaterMark","createArrayFromList","createDataProperty","_require4","_require5","ReadableStream","underlyingSource","typeString","IsReadableStream","IsReadableStreamLocked","ReadableStreamCancel","_ref2","AcquireReadableStreamDefaultReader","AcquireReadableStreamBYOBReader","_ref3","readable","ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue","_ref4","preventClose","preventAbort","preventCancel","Boolean","reader","shuttingDown","currentWrite","_ref5","isOrBecomesErrored","shutdownWithAction","shutdown","isOrBecomesClosed","dest","destClosed","pipeLoop","oldCurrentWrite","waitForWritesToFinish","action","doTheRest","finalize","ReadableStreamReaderGenericRelease","branches","ReadableStreamTee","IsReadableStreamDisturbed","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerGetDesiredSize","teeState","closedOrErrored","canceled1","canceled2","reason1","reason2","pull","create_ReadableStreamTeePullFunction","cancel1","create_ReadableStreamTeeBranch1CancelFunction","cancel2","create_ReadableStreamTeeBranch2CancelFunction","underlyingSource1","branch1Stream","underlyingSource2","branch2Stream","branch1","branch2","value1","value2","compositeReason","cancelResult","IsReadableStreamBYOBReader","readIntoRequest","IsReadableStreamDefaultReader","readRequest","ReadableStreamClose","sourceCancelPromise","defaultReaderClosedPromiseResolve","_i","defaultReaderClosedPromiseReject","ReadableStreamDefaultReader","ReadableStreamReaderGenericInitialize","defaultReaderBrandCheckException","readerLockException","ReadableStreamReaderGenericCancel","ReadableStreamDefaultReaderRead","ReadableStreamBYOBReader","IsReadableByteStreamController","byobReaderBrandCheckException","ArrayBuffer","view","ReadableStreamBYOBReaderRead","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","defaultReaderClosedPromiseResetToRejected","ReadableByteStreamControllerPullInto","ReadableStreamDefaultController","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerErrorIfNeeded","IsReadableStreamDefaultController","defaultControllerBrandCheckException","pendingPromise","ReadableStreamAddReadRequest","shouldPull","ReadableStreamDefaultControllerShouldCallPull","pullPromise","ReadableStreamGetNumReadRequests","ReadableStreamFulfillReadRequest","ReadableStreamError","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","ReadableByteStreamControllerRespond","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","ReadableByteStreamControllerClearPendingPullIntos","autoAllocateChunkSize","underlyingByteSource","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerError","byteStreamControllerBrandCheckException","ReadableByteStreamControllerClose","ReadableByteStreamControllerEnqueue","firstDescriptor","ReadableStreamHasDefaultReader","ReadableByteStreamControllerHandleQueueDrain","pullIntoDescriptor","byteOffset","byteLength","bytesFilled","elementSize","ctor","readerType","ReadableByteStreamControllerGetDesiredSize","ReadableByteStreamControllerShouldCallPull","ReadableByteStreamControllerInvalidateBYOBRequest","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","ReadableStreamFulfillReadIntoRequest","currentAlignedBytes","maxBytesToCopy","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","ready","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerCommitPullIntoDescriptor","ReadableStreamAddReadIntoRequest","emptyView","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","remainderSize","remainder","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","bytesWritten","ReadableByteStreamControllerRespondInClosedState","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","transferredView","ReadableByteStreamControllerRespondInternal","transformStream","readableStream","writableStream","PromiseInvokeOrPerformFallback","TransformStreamCloseReadableInternal","TransformStreamErrorIfNeeded","maybeBackpressure","TransformStreamSetBackpressure","TransformStreamErrorInternal","resolution","transformStreamController","TransformStreamEnqueueToReadable","transformer","transformPromise","TransformStreamReadableReadyPromise","TransformStreamSink","TransformStreamTransform","flushPromise","TransformStreamSource","TransformStreamDefaultController","IsTransformStream","IsTransformStreamDefaultController","TransformStreamCloseReadable","TransformStreamError","readableController","TransformStream","readableStrategy","writableStrategy","startPromise_resolve","startPromise","sink","isURLSupported","u","PolyfillURL","OriginalURL","relative","relativePathDotMapping","h","invalid","unicode","ALPHA","ALPHANUMERIC","errors","stateOverride","cursor","seenAt","seenBracket","input","err","isRelativeScheme","percentEscape","nextC","nextNextC","cp","tempC","IDNAToASCII","temp","parseInt","tmp","percentEscapeQuery","parse","JURL","authority","host","DEFAULT_RANGE_CHUNK_SIZE","isWorkerDisabled","fakeWorkerFilesLoader","useRequireEnsure","__non_webpack_require__","requirejs","fallbackWorkerSrc","dynamicLoaderSupported","worker","pdfjsFilePath","createPDFNetworkStream","isArrayBuffer","range","rangeTransport","pdfBytes","NativeImageDecoderValues","apiCompatibilityParams","setVerbosityLevel","workerParams","postMessageTransfers","GlobalWorkerOptions","PDFWorker","docId","networkStream","initialData","progressiveDone","disableRange","disableStream","httpHeaders","withCredentials","rangeChunkSize","messageHandler","transport","pdfDataRangeTransport","apiVersion","password","disableAutoFetch","maxImageSize","disableFontFace","disableCreateObjectURL","docBaseUrl","nativeImageDecoderSupport","ignoreErrors","isEvalSupported","PDFDocumentLoadingTask","nextDocumentId","constructor","transportDestroyed","deprecated","addRangeListener","addProgressListener","addProgressiveReadListener","addProgressiveDoneListener","onDataRange","onDataProgress","onDataProgressiveRead","requestDataRange","getPage","getPageIndex","getDestination","pdfBug","getViewport","rotation","dontFlip","scale","viewBox","getAnnotations","intent","enableWebGL","renderInteractiveForms","imageLayer","canvasFactory","background","render","stats","renderingIntent","canvasFactoryInstance","webGLContext","enable","intentState","fnArray","argsArray","lastChunk","pageIndex","complete","internalRenderTask","callback","canvasContext","viewport","objs","commonObjs","operatorList","pageNumber","useRequestAnimationFrame","renderTask","transparency","opListTask","streamTextContent","normalizeWhitespace","disableCombineTextItems","TEXT_CONTENT_CHUNK_SIZE","combineTextItems","textContent","getTextContent","pump","items","styles","waitOn","renderCompleted","resetStats","cleanup","_tryCleanup","_startRenderPage","_renderPageChunk","operatorListChunk","postMessage","cloned","transferable","transfers","desc","cloneValue","addEventListener","removeEventListener","pdfWorkerPorts","nextFakeWorkerId","fakeWorkerFilesLoadedCapability","mainWorkerMessageHandler","getMainThreadWorkerMessageHandler","loader","getWorkerSrc","_initializeFromPort","workerSrc","isSameOrigin","createCDNWrapper","terminateEarly","onWorkerError","sendTest","testObj","info","setupFakeWorkerGlobal","WorkerMessageHandler","workerHandler","loadingTask","onUnsupportedFeature","isCompressed","page","terminated","evt","loaded","total","headersCapability","fullReader","isStreamingSupported","isRangeSupported","contentLength","rangeReader","pdfInfo","updatePassword","exception","exportedError","exportedData","fontRegistry","registerFont","pageProxy","img","releaseImageResources","MAX_IMAGE_SIZE_TO_STORE","imageData","components","width","rgbaLength","buf","tmpCanvas","tmpCtx","height","_onUnsupportedFeature","pageInfo","ref","results","metadata","contentDispositionFilename","_ensureObj","resolved","InternalRenderTask","canvasInRendering","initializeGraphics","cancel","build","runtime","Op","hasOwn","iteratorSymbol","asyncIteratorSymbol","toStringTagSymbol","protoGenerator","outerFn","generator","tryLocsList","makeInvokeMethod","arg","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","getProto","NativeIteratorPrototype","Gp","GeneratorFunctionPrototype","Generator","GeneratorFunction","prototype","genFun","__await","record","tryCatch","previousPromise","callInvokeWithMethodAndArg","defineIteratorMethods","AsyncIterator","doneResult","delegate","delegateResult","maybeInvokeDelegate","tryLoc","locs","iteratorMethod","Context","reset","stop","rootEntry","rootRecord","dispatchException","handle","hasCatch","hasFinally","abrupt","finallyEntry","finish","resetTryEntry","thrown","delegateYield","resultName","nextLoc","regeneratorRuntime","DEFAULT_LINK_REL","SVG_NS","canvas","canvasAndContext","destroy","compressionType","isFetchSupported","isValidFetchUrl","response","cMapData","request","XMLHttpRequest","svg","createElement","offsetX","offsetY","centerX","centerY","rotateA","rotateB","rotateC","rotateD","offsetCanvasX","offsetCanvasY","clone","convertToViewportPoint","convertToViewportRectangle","topLeft","bottomRight","convertToPdfPoint","RenderingCancelledException","LinkTarget","SELF","BLANK","PARENT","TOP","LinkTargetStringMap","link","removeNullCharacters","LinkTargetValues","targetIndex","anchor","query","time","Date","timeEnd","longest","duration","Response","protocol","script","isString","pdfDateStringRegex","matches","year","month","day","hour","minute","universalTimeRelation","offsetHour","offsetMinute","addNativeFontFace","insertRule","styleElement","styleSheet","nativeFontFace","featureId","rule","_queueLoadingCallback","_prepareFontLoadEvent","FontLoader","requests","nextRequestId","otherRequest","chunk1","chunk2","called","isFontReady","loadTestFontId","COMMENT_OFFSET","spliceString","CFF_CHECKSUM_OFFSET","XXXX_VALUE","checksum","int32","string32","btoa","fonts","span","supported","shadow","getLoadTestFont","atob","IsEvalSupportedCached","translatedData","bytesToString","getPathGenerator","cmds","js","current","compatibilityParams","isIE","isIOSChrome","MIN_FONT_SIZE","MAX_FONT_SIZE","MAX_GROUP_SIZE","MIN_WIDTH_FACTOR","COMPILE_TYPE3_GLYPHS","MAX_SIZE_TO_COMPILE","FULL_CHUNK_HEIGHT","IsLittleEndianCached","ad_bc","bc_ad","old","prev","cosValue","sinValue","CachedCanvases","getCanvas","canvasEntry","addContextCurrentTransform","POINT_TO_PROCESS_LIMIT","imgData","width1","points","POINT_TYPES","lineSize","data0","mask","elem","count","j0","sum","steps","outlines","coords","p0","pp","drawOutline","o","jj","CanvasExtraState","setCurrentPoint","CanvasGraphics","EXECUTION_TIME","EXECUTION_STEPS","partialChunkHeight","fullChunks","totalChunks","chunkImgData","srcPos","srcLength","dest32","dest32DataLength","fullSrcDiff","white","black","thisChunkHeight","destPos","srcDiff","kEnd","kEndUnrolled","srcByte","elemsInThisChunk","properties","property","sourceCtx","destCtx","alpha","alpha_","r0","g0","b0","maskData","transferMap","layerData","y","hasBackdrop","backdrop","subtype","composeFn","PIXELS_TO_PROCESS","row","chunkHeight","maskCtx","layerCtx","composeSMaskBackdrop","composed","layer","genericComposeSMask","LINE_CAP_STYLES","LINE_JOIN_STYLES","NORMAL_CLIP","EO_CLIP","beginDrawing","transparentCanvas","resetCtxToDefault","executeOperatorList","executionStartIdx","argsArrayLen","chunkOperations","endTime","stepper","fnId","objsPool","depObjId","continueCallback","endDrawing","states","beginSMaskGroup","activeSMask","drawnWidth","drawnHeight","cacheId","scratchCanvas","currentCtx","currentTransform","groupCtx","copyCtxState","suspendSMaskGroup","composeSMask","deltaTransform","resumeSMaskGroup","endSMaskGroup","ops","xw","yh","consumePath","strokeColor","fillColor","isPatternFill","needRestore","paths","path","fontObj","bold","italic","typeface","browserFontSize","paintChar","textRenderingMode","fontSize","fillStrokeMode","isAddToPathSet","patternFill","addToPath","enabled","fontSizeScale","charSpacing","wordSpacing","fontDirection","textHScale","glyphsLength","glyphs","vertical","spacingDir","defaultVMetrics","widthAdvanceScale","simpleFillText","pattern","patternTransform","lineWidth","glyph","isNum","restoreNeeded","spacing","character","accent","vmetric","vx","vy","scaledX","scaledY","measuredWidth","characterScaleX","scaledAccentX","scaledAccentY","charWidth","showType3Text","fontMatrix","isTextInvisible","spacingLength","transformed","urx","ury","getColorN_Pattern","IR","color","baseTransform","canvasGraphicsFactory","createCanvasGraphics","getShadingPatternFromIR","inv","bl","br","ul","ur","x0","y0","x1","y1","matrix","bbox","group","bounds","canvasBounds","scaleX","scaleY","startTransformInverse","domImage","position","objId","top","maskCanvas","putBinaryImageMask","positions","images","image","map","widthScale","heightScale","imgToPaint","putBinaryImageData","paintWidth","paintHeight","tmpCanvasId","newWidth","newHeight","getSinglePixelWidth","inverse","getCanvasPosition","ShadingIRs","fromIR","raw","colorStops","r1","getPattern","grad","createMeshCanvas","colors","rowSize","c1","c2","c3","x2","y2","x3","y3","c1r","c1g","c1b","c2r","c2g","c2b","c3r","c3g","c3b","minY","maxY","xa","car","cag","cab","xb","cbr","cbg","cbb","x1_","x2_","ps","figure","cs","verticesPerRow","rows","cols","q","drawTriangle","EXPECTED_SCALE","MAX_PATTERN_SIZE","BORDER_SIZE","boundsWidth","boundsHeight","combinesScale","paddedWidth","paddedHeight","backgroundColor","figures","cachedCanvases","drawFigure","owner","matrixScale","temporaryPatternCanvas","shadingIR","TilingPattern","PaintType","COLORED","UNCOLORED","createPatternCanvas","xstep","ystep","paintType","tilingType","curMatrixScale","combinedScale","dimx","dimy","graphics","getSizeAndScale","maxSize","clipBbox","bboxWidth","bboxHeight","setFillAndStrokeStyleToContext","cssColor","thisArg","callbacksCapabilities","ah","callbackId","wrapReason","sourceName","targetName","comObj","isReply","makeReasonSerializable","MessageHandler","on","send","sendWithPromise","sendWithStream","streamId","startCapability","startCall","isClosed","pullCapability","cancelCapability","_createStreamSink","sendStreamRequest","success","streamSink","enqueue","lastDesiredSize","close","sinkCapability","onPull","onCancel","isCancelled","resolveCall","_processStreamMessage","sendStreamResponse","deleteStreamController","resolveOrReject","parser","xmlDocument","_repair","chars","_parse","rdf","nodeName","children","XMLParserErrorCode","NoError","EndOfDocument","UnterminatedCdat","UnterminatedXmlDeclaration","UnterminatedDoctypeDeclaration","UnterminatedComment","MalformedElement","OutOfMemory","UnterminatedAttributeValue","UnterminatedElement","ElementNeverBegun","isWhitespace","_resolveEntities","entity","_parseContent","attributes","skipWs","attrName","attrValue","attrEndChar","attrEndIndex","parsed","_parseProcessingInstruction","attrStart","parseXml","ch2","pi","q2","complexDoctype","doctypeContent","content","text","onResolveEntity","onPi","onComment","onCdata","onDoctype","onText","onBeginElement","onEndElement","onError","childNodes","child","parseFromString","documentElement","isWhitespaceString","lastElement","begin","_onReceiveData","found","_onProgress","firstReader","_removeRangeReader","queuedChunks","getRangeReader","cancelAllRequests","readers","_enqueue","requestCapability","requestsCapability","WebGLUtils","drawFigures","shader","gl","compiled","errorMsg","loadShader","program","shaders","linked","texture","currentCanvas","currentGL","premultipliedalpha","smaskVertexShaderCode","smaskFragmentShaderCode","smaskCache","generateGL","vertexShader","createVertexShader","fragmentShader","createFragmentShader","cache","texCoordLocation","texLayerLocation","texMaskLocation","texCoordBuffer","initSmaskGL","createTexture","maskTexture","figuresVertexShaderCode","figuresFragmentShaderCode","figuresCache","initFiguresGL","coordsMap","colorsMap","pIndex","cIndex","col","coordsBuffer","colorsBuffer","tryInitGL","renderTextLayer","MAX_TEXT_DIVS_TO_RENDER","NonWhitespaceRegexp","styleBuf","textDiv","textDivProperties","style","angle","canvasWidth","originalTransform","paddingBottom","paddingLeft","paddingRight","paddingTop","isAllWhitespace","geom","tx","fontHeight","fontAscent","angleCos","angleSin","divWidth","divHeight","right","bottom","textDivs","textDivsLength","expanded","expandBounds","divProperties","ts","t","findPositiveMin","boxScale","box","x1New","x2New","expandBoundsLTR","boxes","fakeBoundary","horizon","boundary","maxXNew","horizonPart","affectedBoundary","xNew","changedHorizon","lastBoundary","useBoundary","used","textContentItemsStr","TextLayerRenderTask","clearTimeout","_processItems","appendText","_layoutText","textLayerFrag","fontFamily","_render","styleCache","textItems","textStyles","expandTextDivs","expand","padding","renderParameters","textContentStream","enhanceTextSelection","parameters","fieldType","isRenderable","ignoreBorder","_createContainer","horizontalRadius","verticalRadius","radius","_createPopup","trigger","popupElement","title","modificationDate","contents","hideWrapper","popup","addLinkAttributes","linkService","rel","_bindLink","_bindNamedAction","JSON","TEXT_ALIGNMENT","fieldWidth","combWidth","_setTextStyle","fallbackName","selectElement","option","optionElement","IGNORE_TYPES","selector","parentElement","parentLeft","parseFloat","parentWidth","BACKGROUND_ENLIGHT","g","dateObject","PDFDateString","date","_formatContents","lines","line","pin","_show","unpin","_hide","borderWidth","square","circle","vertices","polyline","inkLists","inkList","getFilenameFromUrl","stringToPDFString","filename","downloadManager","imageResourcesPath","svgFactory","SVGGraphics","opTree","opListElement","pf","SVG_DEFAULTS","fontStyle","fontWeight","XML_NS","XLINK_NS","convertImgDataToPng","PNG_HEADER","CHUNK_WRAPPER_SIZE","crcTable","crc","body","crc32","deflateSyncUncompressed","output","level","literals","maxBlockLength","deflateBlocks","idat","adler","adler32","colorType","bitDepth","offsetLiterals","offsetBytes","ihdr","deflateSync","pngLength","writePngChunk","encode","clipCount","maskCount","shadingCount","loadDependencies","transformMatrix","getSVG","svgElement","convertOpList","operatorIdMapping","opList","opListToTree","executeOpTree","opTreeElement","lineWidthScale","textMatrix","pm","addFontStyle","details","setStrokeAlpha","setFillAlpha","_makeColorN_Pattern","_makeTilingPattern","tilingId","txstep","tystep","tiling","tx1","ty1","_makeShadingPattern","shadingId","point0","point1","gradient","focalPoint","circlePoint","focalRadius","circleRadius","colorStop","op","clipId","clipPath","clipElement","_setStrokeAttributes","dashArray","imgObj","imgEl","imgSrc","cliprect","_initialize","definitions","rootGroup","clipGroup","OK_RESPONSE","PARTIAL_CONTENT_RESPONSE","xhr","array","requestRange","listeners","requestFull","xhrId","pendingRequest","onProgress","onStateChange","xhrStatus","ok_response_on_range_request","getArrayBuffer","rangeHeader","getRequestXhr","isPendingRequest","_onRangeRequestReaderClosed","onHeadersReceived","onDone","manager","fullRequestXhrId","fullRequestXhr","getResponseHeader","isHttp","suggestedLength","extractFilenameFromHeader","_onDone","_onError","createResponseStatusError","returnValues","allowRangeRequests","contentEncoding","contentDisposition","getFilenameFromContentDispositionHeader","status","needsEncodingFixup","toParamRegExp","rfc2616unquote","rfc5987decode","rfc2047decode","fixupEncoding","rfc2231getparam","decoder","fatal","textdecode","parts","part","quotindex","encodingend","extvalue","encoding","langvalue","headers","signal","abortController","credentials","redirect","fetch","createFetchOptions","validateResponseStatus"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kDAA0C,gCAAgC;AAC1E;AACA;;AAEA;AACA;AACA;AACA,gEAAwD,kBAAkB;AAC1E;AACA,yDAAiD,cAAc;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAyC,iCAAiC;AAC1E,wHAAgH,mBAAmB,EAAE;AACrI;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;;AAGA;AACA;;;;;;;;AClFA;;AAkBA,IAAIA,eAlBJ,SAkBA;AAEA,IAAIC,aApBJ,WAoBA;;AAGA,IAAIC,kBAAkBC,oBAvBtB,CAuBsBA,CAAtB;;AACA,IAAIC,kBAAkBD,oBAxBtB,GAwBsBA,CAAtB;;AACA,IAAIE,wBAAwBF,oBAzB5B,GAyB4BA,CAA5B;;AACA,IAAIG,8BAA8BH,oBA1BlC,GA0BkCA,CAAlC;;AACA,IAAII,2BAA2BJ,oBA3B/B,GA2B+BA,CAA/B;;AACA,IAAIK,kBAAkBL,oBA5BtB,GA4BsBA,CAAtB;;AACA,IAAIM,4BAA4BN,oBA7BhC,GA6BgCA,CAAhC;;AACA,IAAIO,+BAA+BP,oBA9BnC,G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AN;AAF2C;;AAI7C,6BAJ6C,OAI7C;;AACA,uBAAe/xB,cAL8B,SAK9BA,EAAf;AANF4zB,gBAOS,qBA/BqB,MAwB9BA;AASA,sBAjC8B,IAiC9B;AAlC4B;;;;;;;;;;;;;;;uBA0CtB,qBADK,O;;;;uBAEoB,aAFpB,IAEoB,E;;;;AAAzB,qB,SAAA,K;AAAA,oB,SAAA,I;;qBACN,I;;;;;kDACS;AAAEr9D,uBAAF,EAAEA,KAAF;AAASgN,sBAAT,EAASA;AAAT,iB;;;AAET,gCAAgBhN,MANL,UAMX;;AACA,oBAAI,KAAJ,YAAqB;AACnB,kCAAgB;AAAEgjC,4BAAQ,KADP;AACH,mBAAhB;AARS;;AAULx9B,sB,GAAS,sBAVJ,M;kDAWJ;AAAExF,yBAAF;AAAiBgN,wBAAjB;AAAA,iB;;;;;;;;;;;;;;;;;;2BAGTs4B,M,EAAe;AACb,UAAI,KAAJ,SAAkB;AAChB,4BADgB,MAChB;AAFW;;AAIb,UAAI,KAAJ,kBAA2B;AACzB,8BADyB,KACzB;AALW;AAvDe;;;wBAqCH;AACzB,aAAO,KADkB,qBACzB;AAtC4B","file":"pdf.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"pdfjs-dist/build/pdf\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"pdfjs-dist/build/pdf\"] = factory();\n\telse\n\t\troot[\"pdfjs-dist/build/pdf\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __w_pdfjs_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__w_pdfjs_require__.m = modules;\n\n \t// expose the module cache\n \t__w_pdfjs_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__w_pdfjs_require__.d = function(exports, name, getter) {\n \t\tif(!__w_pdfjs_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__w_pdfjs_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__w_pdfjs_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __w_pdfjs_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__w_pdfjs_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __w_pdfjs_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__w_pdfjs_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__w_pdfjs_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__w_pdfjs_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__w_pdfjs_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __w_pdfjs_require__(__w_pdfjs_require__.s = 0);\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* eslint-disable no-unused-vars */\n\n'use strict';\n\nvar pdfjsVersion =\n typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_VERSION') : void 0;\nvar pdfjsBuild =\n typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_BUILD') : void 0;\n\nvar pdfjsSharedUtil = require('./shared/util.js');\nvar pdfjsDisplayAPI = require('./display/api.js');\nvar pdfjsDisplayTextLayer = require('./display/text_layer.js');\nvar pdfjsDisplayAnnotationLayer = require('./display/annotation_layer.js');\nvar pdfjsDisplayDisplayUtils = require('./display/display_utils.js');\nvar pdfjsDisplaySVG = require('./display/svg.js');\nlet pdfjsDisplayWorkerOptions = require('./display/worker_options.js');\nlet pdfjsDisplayAPICompatibility = require('./display/api_compatibility.js');\n\nif (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {\n const isNodeJS = require('./shared/is_node.js');\n if (!isNodeJS()) {\n let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;\n let PDFFetchStream;\n if (pdfjsDisplayDisplayUtils.isFetchSupported()) {\n PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;\n }\n pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {\n if (PDFFetchStream &&\n pdfjsDisplayDisplayUtils.isValidFetchUrl(params.url)) {\n return new PDFFetchStream(params);\n }\n return new PDFNetworkStream(params);\n });\n }\n} else if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('CHROME')) {\n let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;\n let PDFFetchStream;\n let isChromeWithFetchCredentials = function() {\n // fetch does not include credentials until Chrome 61.0.3138.0 and later.\n // https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707\n try {\n // Indexed properties on window are read-only in Chrome 61.0.3151.0+\n // https://chromium.googlesource.com/chromium/src.git/+/58ab4a971b06dec13e4edf9de8382ca6847f6190\n window[999] = 123; // should throw. Note: JS strict mode MUST be enabled.\n delete window[999];\n return false;\n } catch (e) {\n return true;\n }\n };\n if (pdfjsDisplayDisplayUtils.isFetchSupported() &&\n isChromeWithFetchCredentials()) {\n PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;\n }\n pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {\n if (PDFFetchStream &&\n pdfjsDisplayDisplayUtils.isValidFetchUrl(params.url)) {\n return new PDFFetchStream(params);\n }\n return new PDFNetworkStream(params);\n });\n}\n\nexports.build = pdfjsDisplayAPI.build;\nexports.version = pdfjsDisplayAPI.version;\nexports.getDocument = pdfjsDisplayAPI.getDocument;\nexports.LoopbackPort = pdfjsDisplayAPI.LoopbackPort;\nexports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport;\nexports.PDFWorker = pdfjsDisplayAPI.PDFWorker;\nexports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer;\nexports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer;\nexports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability;\nexports.PasswordResponses = pdfjsSharedUtil.PasswordResponses;\nexports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException;\nexports.MissingPDFException = pdfjsSharedUtil.MissingPDFException;\nexports.SVGGraphics = pdfjsDisplaySVG.SVGGraphics;\nexports.NativeImageDecoding = pdfjsSharedUtil.NativeImageDecoding;\nexports.CMapCompressionType = pdfjsSharedUtil.CMapCompressionType;\nexports.PermissionFlag = pdfjsSharedUtil.PermissionFlag;\nexports.UnexpectedResponseException =\n pdfjsSharedUtil.UnexpectedResponseException;\nexports.OPS = pdfjsSharedUtil.OPS;\nexports.VerbosityLevel = pdfjsSharedUtil.VerbosityLevel;\nexports.UNSUPPORTED_FEATURES = pdfjsSharedUtil.UNSUPPORTED_FEATURES;\nexports.createValidAbsoluteUrl = pdfjsSharedUtil.createValidAbsoluteUrl;\nexports.createObjectURL = pdfjsSharedUtil.createObjectURL;\nexports.removeNullCharacters = pdfjsSharedUtil.removeNullCharacters;\nexports.shadow = pdfjsSharedUtil.shadow;\nexports.Util = pdfjsSharedUtil.Util;\nexports.ReadableStream = pdfjsSharedUtil.ReadableStream;\nexports.URL = pdfjsSharedUtil.URL;\nexports.RenderingCancelledException =\n pdfjsDisplayDisplayUtils.RenderingCancelledException;\nexports.getFilenameFromUrl = pdfjsDisplayDisplayUtils.getFilenameFromUrl;\nexports.LinkTarget = pdfjsDisplayDisplayUtils.LinkTarget;\nexports.addLinkAttributes = pdfjsDisplayDisplayUtils.addLinkAttributes;\nexports.loadScript = pdfjsDisplayDisplayUtils.loadScript;\nexports.PDFDateString = pdfjsDisplayDisplayUtils.PDFDateString;\nexports.GlobalWorkerOptions = pdfjsDisplayWorkerOptions.GlobalWorkerOptions;\nexports.apiCompatibilityParams =\n pdfjsDisplayAPICompatibility.apiCompatibilityParams;\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport './compatibility';\nimport { ReadableStream } from './streams_polyfill';\nimport { URL } from './url_polyfill';\n\nconst IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];\nconst FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];\n\nconst NativeImageDecoding = {\n NONE: 'none',\n DECODE: 'decode',\n DISPLAY: 'display',\n};\n\n// Permission flags from Table 22, Section 7.6.3.2 of the PDF specification.\nconst PermissionFlag = {\n PRINT: 0x04,\n MODIFY_CONTENTS: 0x08,\n COPY: 0x10,\n MODIFY_ANNOTATIONS: 0x20,\n FILL_INTERACTIVE_FORMS: 0x100,\n COPY_FOR_ACCESSIBILITY: 0x200,\n ASSEMBLE: 0x400,\n PRINT_HIGH_QUALITY: 0x800,\n};\n\nconst TextRenderingMode = {\n FILL: 0,\n STROKE: 1,\n FILL_STROKE: 2,\n INVISIBLE: 3,\n FILL_ADD_TO_PATH: 4,\n STROKE_ADD_TO_PATH: 5,\n FILL_STROKE_ADD_TO_PATH: 6,\n ADD_TO_PATH: 7,\n FILL_STROKE_MASK: 3,\n ADD_TO_PATH_FLAG: 4,\n};\n\nconst ImageKind = {\n GRAYSCALE_1BPP: 1,\n RGB_24BPP: 2,\n RGBA_32BPP: 3,\n};\n\nconst AnnotationType = {\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n REDACT: 26,\n};\n\nconst AnnotationFlag = {\n INVISIBLE: 0x01,\n HIDDEN: 0x02,\n PRINT: 0x04,\n NOZOOM: 0x08,\n NOROTATE: 0x10,\n NOVIEW: 0x20,\n READONLY: 0x40,\n LOCKED: 0x80,\n TOGGLENOVIEW: 0x100,\n LOCKEDCONTENTS: 0x200,\n};\n\nconst AnnotationFieldFlag = {\n READONLY: 0x0000001,\n REQUIRED: 0x0000002,\n NOEXPORT: 0x0000004,\n MULTILINE: 0x0001000,\n PASSWORD: 0x0002000,\n NOTOGGLETOOFF: 0x0004000,\n RADIO: 0x0008000,\n PUSHBUTTON: 0x0010000,\n COMBO: 0x0020000,\n EDIT: 0x0040000,\n SORT: 0x0080000,\n FILESELECT: 0x0100000,\n MULTISELECT: 0x0200000,\n DONOTSPELLCHECK: 0x0400000,\n DONOTSCROLL: 0x0800000,\n COMB: 0x1000000,\n RICHTEXT: 0x2000000,\n RADIOSINUNISON: 0x2000000,\n COMMITONSELCHANGE: 0x4000000,\n};\n\nconst AnnotationBorderStyleType = {\n SOLID: 1,\n DASHED: 2,\n BEVELED: 3,\n INSET: 4,\n UNDERLINE: 5,\n};\n\nconst StreamType = {\n UNKNOWN: 0,\n FLATE: 1,\n LZW: 2,\n DCT: 3,\n JPX: 4,\n JBIG: 5,\n A85: 6,\n AHX: 7,\n CCF: 8,\n RL: 9,\n};\n\nconst FontType = {\n UNKNOWN: 0,\n TYPE1: 1,\n TYPE1C: 2,\n CIDFONTTYPE0: 3,\n CIDFONTTYPE0C: 4,\n TRUETYPE: 5,\n CIDFONTTYPE2: 6,\n TYPE3: 7,\n OPENTYPE: 8,\n TYPE0: 9,\n MMTYPE1: 10,\n};\n\nconst VerbosityLevel = {\n ERRORS: 0,\n WARNINGS: 1,\n INFOS: 5,\n};\n\nconst CMapCompressionType = {\n NONE: 0,\n BINARY: 1,\n STREAM: 2,\n};\n\n// All the possible operations for an operator list.\nconst OPS = {\n // Intentionally start from 1 so it is easy to spot bad operators that will be\n // 0's.\n dependency: 1,\n setLineWidth: 2,\n setLineCap: 3,\n setLineJoin: 4,\n setMiterLimit: 5,\n setDash: 6,\n setRenderingIntent: 7,\n setFlatness: 8,\n setGState: 9,\n save: 10,\n restore: 11,\n transform: 12,\n moveTo: 13,\n lineTo: 14,\n curveTo: 15,\n curveTo2: 16,\n curveTo3: 17,\n closePath: 18,\n rectangle: 19,\n stroke: 20,\n closeStroke: 21,\n fill: 22,\n eoFill: 23,\n fillStroke: 24,\n eoFillStroke: 25,\n closeFillStroke: 26,\n closeEOFillStroke: 27,\n endPath: 28,\n clip: 29,\n eoClip: 30,\n beginText: 31,\n endText: 32,\n setCharSpacing: 33,\n setWordSpacing: 34,\n setHScale: 35,\n setLeading: 36,\n setFont: 37,\n setTextRenderingMode: 38,\n setTextRise: 39,\n moveText: 40,\n setLeadingMoveText: 41,\n setTextMatrix: 42,\n nextLine: 43,\n showText: 44,\n showSpacedText: 45,\n nextLineShowText: 46,\n nextLineSetSpacingShowText: 47,\n setCharWidth: 48,\n setCharWidthAndBounds: 49,\n setStrokeColorSpace: 50,\n setFillColorSpace: 51,\n setStrokeColor: 52,\n setStrokeColorN: 53,\n setFillColor: 54,\n setFillColorN: 55,\n setStrokeGray: 56,\n setFillGray: 57,\n setStrokeRGBColor: 58,\n setFillRGBColor: 59,\n setStrokeCMYKColor: 60,\n setFillCMYKColor: 61,\n shadingFill: 62,\n beginInlineImage: 63,\n beginImageData: 64,\n endInlineImage: 65,\n paintXObject: 66,\n markPoint: 67,\n markPointProps: 68,\n beginMarkedContent: 69,\n beginMarkedContentProps: 70,\n endMarkedContent: 71,\n beginCompat: 72,\n endCompat: 73,\n paintFormXObjectBegin: 74,\n paintFormXObjectEnd: 75,\n beginGroup: 76,\n endGroup: 77,\n beginAnnotations: 78,\n endAnnotations: 79,\n beginAnnotation: 80,\n endAnnotation: 81,\n paintJpegXObject: 82,\n paintImageMaskXObject: 83,\n paintImageMaskXObjectGroup: 84,\n paintImageXObject: 85,\n paintInlineImageXObject: 86,\n paintInlineImageXObjectGroup: 87,\n paintImageXObjectRepeat: 88,\n paintImageMaskXObjectRepeat: 89,\n paintSolidColorImageMask: 90,\n constructPath: 91,\n};\n\nconst UNSUPPORTED_FEATURES = {\n unknown: 'unknown',\n forms: 'forms',\n javaScript: 'javaScript',\n smask: 'smask',\n shadingPattern: 'shadingPattern',\n font: 'font',\n};\n\nconst PasswordResponses = {\n NEED_PASSWORD: 1,\n INCORRECT_PASSWORD: 2,\n};\n\nlet verbosity = VerbosityLevel.WARNINGS;\n\nfunction setVerbosityLevel(level) {\n if (Number.isInteger(level)) {\n verbosity = level;\n }\n}\n\nfunction getVerbosityLevel() {\n return verbosity;\n}\n\n// A notice for devs. These are good for things that are helpful to devs, such\n// as warning that Workers were disabled, which is important to devs but not\n// end users.\nfunction info(msg) {\n if (verbosity >= VerbosityLevel.INFOS) {\n console.log('Info: ' + msg);\n }\n}\n\n// Non-fatal warnings.\nfunction warn(msg) {\n if (verbosity >= VerbosityLevel.WARNINGS) {\n console.log('Warning: ' + msg);\n }\n}\n\nfunction unreachable(msg) {\n throw new Error(msg);\n}\n\nfunction assert(cond, msg) {\n if (!cond) {\n unreachable(msg);\n }\n}\n\n// Checks if URLs have the same origin. For non-HTTP based URLs, returns false.\nfunction isSameOrigin(baseUrl, otherUrl) {\n try {\n var base = new URL(baseUrl);\n if (!base.origin || base.origin === 'null') {\n return false; // non-HTTP url\n }\n } catch (e) {\n return false;\n }\n\n var other = new URL(otherUrl, base);\n return base.origin === other.origin;\n}\n\n// Checks if URLs use one of the whitelisted protocols, e.g. to avoid XSS.\nfunction _isValidProtocol(url) {\n if (!url) {\n return false;\n }\n switch (url.protocol) {\n case 'http:':\n case 'https:':\n case 'ftp:':\n case 'mailto:':\n case 'tel:':\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Attempts to create a valid absolute URL.\n *\n * @param {URL|string} url - An absolute, or relative, URL.\n * @param {URL|string} baseUrl - An absolute URL.\n * @returns Either a valid {URL}, or `null` otherwise.\n */\nfunction createValidAbsoluteUrl(url, baseUrl) {\n if (!url) {\n return null;\n }\n try {\n var absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);\n if (_isValidProtocol(absoluteUrl)) {\n return absoluteUrl;\n }\n } catch (ex) { /* `new URL()` will throw on incorrect data. */ }\n return null;\n}\n\nfunction shadow(obj, prop, value) {\n Object.defineProperty(obj, prop, { value,\n enumerable: true,\n configurable: true,\n writable: false, });\n return value;\n}\n\nvar PasswordException = (function PasswordExceptionClosure() {\n function PasswordException(msg, code) {\n this.name = 'PasswordException';\n this.message = msg;\n this.code = code;\n }\n\n PasswordException.prototype = new Error();\n PasswordException.constructor = PasswordException;\n\n return PasswordException;\n})();\n\nvar UnknownErrorException = (function UnknownErrorExceptionClosure() {\n function UnknownErrorException(msg, details) {\n this.name = 'UnknownErrorException';\n this.message = msg;\n this.details = details;\n }\n\n UnknownErrorException.prototype = new Error();\n UnknownErrorException.constructor = UnknownErrorException;\n\n return UnknownErrorException;\n})();\n\nvar InvalidPDFException = (function InvalidPDFExceptionClosure() {\n function InvalidPDFException(msg) {\n this.name = 'InvalidPDFException';\n this.message = msg;\n }\n\n InvalidPDFException.prototype = new Error();\n InvalidPDFException.constructor = InvalidPDFException;\n\n return InvalidPDFException;\n})();\n\nvar MissingPDFException = (function MissingPDFExceptionClosure() {\n function MissingPDFException(msg) {\n this.name = 'MissingPDFException';\n this.message = msg;\n }\n\n MissingPDFException.prototype = new Error();\n MissingPDFException.constructor = MissingPDFException;\n\n return MissingPDFException;\n})();\n\nvar UnexpectedResponseException =\n (function UnexpectedResponseExceptionClosure() {\n function UnexpectedResponseException(msg, status) {\n this.name = 'UnexpectedResponseException';\n this.message = msg;\n this.status = status;\n }\n\n UnexpectedResponseException.prototype = new Error();\n UnexpectedResponseException.constructor = UnexpectedResponseException;\n\n return UnexpectedResponseException;\n})();\n\n/**\n * Error caused during parsing PDF data.\n */\nlet FormatError = (function FormatErrorClosure() {\n function FormatError(msg) {\n this.message = msg;\n }\n\n FormatError.prototype = new Error();\n FormatError.prototype.name = 'FormatError';\n FormatError.constructor = FormatError;\n\n return FormatError;\n})();\n\n/**\n * Error used to indicate task cancellation.\n */\nlet AbortException = (function AbortExceptionClosure() {\n function AbortException(msg) {\n this.name = 'AbortException';\n this.message = msg;\n }\n\n AbortException.prototype = new Error();\n AbortException.constructor = AbortException;\n\n return AbortException;\n})();\n\nvar NullCharactersRegExp = /\\x00/g;\n\nfunction removeNullCharacters(str) {\n if (typeof str !== 'string') {\n warn('The argument for removeNullCharacters must be a string.');\n return str;\n }\n return str.replace(NullCharactersRegExp, '');\n}\n\nfunction bytesToString(bytes) {\n assert(bytes !== null && typeof bytes === 'object' &&\n bytes.length !== undefined, 'Invalid argument for bytesToString');\n var length = bytes.length;\n var MAX_ARGUMENT_COUNT = 8192;\n if (length < MAX_ARGUMENT_COUNT) {\n return String.fromCharCode.apply(null, bytes);\n }\n var strBuf = [];\n for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {\n var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);\n var chunk = bytes.subarray(i, chunkEnd);\n strBuf.push(String.fromCharCode.apply(null, chunk));\n }\n return strBuf.join('');\n}\n\nfunction stringToBytes(str) {\n assert(typeof str === 'string', 'Invalid argument for stringToBytes');\n var length = str.length;\n var bytes = new Uint8Array(length);\n for (var i = 0; i < length; ++i) {\n bytes[i] = str.charCodeAt(i) & 0xFF;\n }\n return bytes;\n}\n\n/**\n * Gets length of the array (Array, Uint8Array, or string) in bytes.\n * @param {Array|Uint8Array|string} arr\n * @returns {number}\n */\nfunction arrayByteLength(arr) {\n if (arr.length !== undefined) {\n return arr.length;\n }\n assert(arr.byteLength !== undefined);\n return arr.byteLength;\n}\n\n/**\n * Combines array items (arrays) into single Uint8Array object.\n * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).\n * @returns {Uint8Array}\n */\nfunction arraysToBytes(arr) {\n // Shortcut: if first and only item is Uint8Array, return it.\n if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {\n return arr[0];\n }\n var resultLength = 0;\n var i, ii = arr.length;\n var item, itemLength;\n for (i = 0; i < ii; i++) {\n item = arr[i];\n itemLength = arrayByteLength(item);\n resultLength += itemLength;\n }\n var pos = 0;\n var data = new Uint8Array(resultLength);\n for (i = 0; i < ii; i++) {\n item = arr[i];\n if (!(item instanceof Uint8Array)) {\n if (typeof item === 'string') {\n item = stringToBytes(item);\n } else {\n item = new Uint8Array(item);\n }\n }\n itemLength = item.byteLength;\n data.set(item, pos);\n pos += itemLength;\n }\n return data;\n}\n\nfunction string32(value) {\n return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,\n (value >> 8) & 0xff, value & 0xff);\n}\n\n// Calculate the base 2 logarithm of the number `x`. This differs from the\n// native function in the sense that it returns the ceiling value and that it\n// returns 0 instead of `Infinity`/`NaN` for `x` values smaller than/equal to 0.\nfunction log2(x) {\n if (x <= 0) {\n return 0;\n }\n return Math.ceil(Math.log2(x));\n}\n\nfunction readInt8(data, start) {\n return (data[start] << 24) >> 24;\n}\n\nfunction readUint16(data, offset) {\n return (data[offset] << 8) | data[offset + 1];\n}\n\nfunction readUint32(data, offset) {\n return ((data[offset] << 24) | (data[offset + 1] << 16) |\n (data[offset + 2] << 8) | data[offset + 3]) >>> 0;\n}\n\n// Lazy test the endianness of the platform\n// NOTE: This will be 'true' for simulated TypedArrays\nfunction isLittleEndian() {\n var buffer8 = new Uint8Array(4);\n buffer8[0] = 1;\n var view32 = new Uint32Array(buffer8.buffer, 0, 1);\n return (view32[0] === 1);\n}\n\n// Checks if it's possible to eval JS expressions.\nfunction isEvalSupported() {\n try {\n new Function(''); // eslint-disable-line no-new, no-new-func\n return true;\n } catch (e) {\n return false;\n }\n}\n\nvar Util = (function UtilClosure() {\n function Util() {}\n\n var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];\n\n // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids\n // creating many intermediate strings.\n Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {\n rgbBuf[1] = r;\n rgbBuf[3] = g;\n rgbBuf[5] = b;\n return rgbBuf.join('');\n };\n\n // Concatenates two transformation matrices together and returns the result.\n Util.transform = function Util_transform(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5]\n ];\n };\n\n // For 2d affine transforms\n Util.applyTransform = function Util_applyTransform(p, m) {\n var xt = p[0] * m[0] + p[1] * m[2] + m[4];\n var yt = p[0] * m[1] + p[1] * m[3] + m[5];\n return [xt, yt];\n };\n\n Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {\n var d = m[0] * m[3] - m[1] * m[2];\n var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;\n var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;\n return [xt, yt];\n };\n\n // Applies the transform to the rectangle and finds the minimum axially\n // aligned bounding box.\n Util.getAxialAlignedBoundingBox =\n function Util_getAxialAlignedBoundingBox(r, m) {\n\n var p1 = Util.applyTransform(r, m);\n var p2 = Util.applyTransform(r.slice(2, 4), m);\n var p3 = Util.applyTransform([r[0], r[3]], m);\n var p4 = Util.applyTransform([r[2], r[1]], m);\n return [\n Math.min(p1[0], p2[0], p3[0], p4[0]),\n Math.min(p1[1], p2[1], p3[1], p4[1]),\n Math.max(p1[0], p2[0], p3[0], p4[0]),\n Math.max(p1[1], p2[1], p3[1], p4[1])\n ];\n };\n\n Util.inverseTransform = function Util_inverseTransform(m) {\n var d = m[0] * m[3] - m[1] * m[2];\n return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,\n (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];\n };\n\n // Apply a generic 3d matrix M on a 3-vector v:\n // | a b c | | X |\n // | d e f | x | Y |\n // | g h i | | Z |\n // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],\n // with v as [X,Y,Z]\n Util.apply3dTransform = function Util_apply3dTransform(m, v) {\n return [\n m[0] * v[0] + m[1] * v[1] + m[2] * v[2],\n m[3] * v[0] + m[4] * v[1] + m[5] * v[2],\n m[6] * v[0] + m[7] * v[1] + m[8] * v[2]\n ];\n };\n\n // This calculation uses Singular Value Decomposition.\n // The SVD can be represented with formula A = USV. We are interested in the\n // matrix S here because it represents the scale values.\n Util.singularValueDecompose2dScale =\n function Util_singularValueDecompose2dScale(m) {\n\n var transpose = [m[0], m[2], m[1], m[3]];\n\n // Multiply matrix m with its transpose.\n var a = m[0] * transpose[0] + m[1] * transpose[2];\n var b = m[0] * transpose[1] + m[1] * transpose[3];\n var c = m[2] * transpose[0] + m[3] * transpose[2];\n var d = m[2] * transpose[1] + m[3] * transpose[3];\n\n // Solve the second degree polynomial to get roots.\n var first = (a + d) / 2;\n var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;\n var sx = first + second || 1;\n var sy = first - second || 1;\n\n // Scale values are the square roots of the eigenvalues.\n return [Math.sqrt(sx), Math.sqrt(sy)];\n };\n\n // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)\n // For coordinate systems whose origin lies in the bottom-left, this\n // means normalization to (BL,TR) ordering. For systems with origin in the\n // top-left, this means (TL,BR) ordering.\n Util.normalizeRect = function Util_normalizeRect(rect) {\n var r = rect.slice(0); // clone rect\n if (rect[0] > rect[2]) {\n r[0] = rect[2];\n r[2] = rect[0];\n }\n if (rect[1] > rect[3]) {\n r[1] = rect[3];\n r[3] = rect[1];\n }\n return r;\n };\n\n // Returns a rectangle [x1, y1, x2, y2] corresponding to the\n // intersection of rect1 and rect2. If no intersection, returns 'false'\n // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]\n Util.intersect = function Util_intersect(rect1, rect2) {\n function compare(a, b) {\n return a - b;\n }\n\n // Order points along the axes\n var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),\n orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),\n result = [];\n\n rect1 = Util.normalizeRect(rect1);\n rect2 = Util.normalizeRect(rect2);\n\n // X: first and second points belong to different rectangles?\n if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||\n (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {\n // Intersection must be between second and third points\n result[0] = orderedX[1];\n result[2] = orderedX[2];\n } else {\n return false;\n }\n\n // Y: first and second points belong to different rectangles?\n if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||\n (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {\n // Intersection must be between second and third points\n result[1] = orderedY[1];\n result[3] = orderedY[2];\n } else {\n return false;\n }\n\n return result;\n };\n\n return Util;\n})();\n\nconst PDFStringTranslateTable = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,\n 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,\n 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,\n 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC\n];\n\nfunction stringToPDFString(str) {\n var i, n = str.length, strBuf = [];\n if (str[0] === '\\xFE' && str[1] === '\\xFF') {\n // UTF16BE BOM\n for (i = 2; i < n; i += 2) {\n strBuf.push(String.fromCharCode(\n (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));\n }\n } else {\n for (i = 0; i < n; ++i) {\n var code = PDFStringTranslateTable[str.charCodeAt(i)];\n strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));\n }\n }\n return strBuf.join('');\n}\n\nfunction stringToUTF8String(str) {\n return decodeURIComponent(escape(str));\n}\n\nfunction utf8StringToString(str) {\n return unescape(encodeURIComponent(str));\n}\n\nfunction isEmptyObj(obj) {\n for (var key in obj) {\n return false;\n }\n return true;\n}\n\nfunction isBool(v) {\n return typeof v === 'boolean';\n}\n\nfunction isNum(v) {\n return typeof v === 'number';\n}\n\nfunction isString(v) {\n return typeof v === 'string';\n}\n\nfunction isArrayBuffer(v) {\n return typeof v === 'object' && v !== null && v.byteLength !== undefined;\n}\n\nfunction isArrayEqual(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n return arr1.every(function(element, index) {\n return element === arr2[index];\n });\n}\n\n// Checks if ch is one of the following characters: SPACE, TAB, CR or LF.\nfunction isSpace(ch) {\n return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);\n}\n\n/**\n * Promise Capability object.\n *\n * @typedef {Object} PromiseCapability\n * @property {Promise} promise - A Promise object.\n * @property {boolean} settled - If the Promise has been fulfilled/rejected.\n * @property {function} resolve - Fulfills the Promise.\n * @property {function} reject - Rejects the Promise.\n */\n\n/**\n * Creates a promise capability object.\n * @alias createPromiseCapability\n *\n * @return {PromiseCapability}\n */\nfunction createPromiseCapability() {\n const capability = Object.create(null);\n let isSettled = false;\n\n Object.defineProperty(capability, 'settled', {\n get() {\n return isSettled;\n },\n });\n capability.promise = new Promise(function(resolve, reject) {\n capability.resolve = function(data) {\n isSettled = true;\n resolve(data);\n };\n capability.reject = function(reason) {\n isSettled = true;\n reject(reason);\n };\n });\n return capability;\n}\n\nvar createObjectURL = (function createObjectURLClosure() {\n // Blob/createObjectURL is not available, falling back to data schema.\n var digits =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n return function createObjectURL(data, contentType, forceDataSchema = false) {\n if (!forceDataSchema && URL.createObjectURL) {\n const blob = new Blob([data], { type: contentType, });\n return URL.createObjectURL(blob);\n }\n\n var buffer = 'data:' + contentType + ';base64,';\n for (var i = 0, ii = data.length; i < ii; i += 3) {\n var b1 = data[i] & 0xFF;\n var b2 = data[i + 1] & 0xFF;\n var b3 = data[i + 2] & 0xFF;\n var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);\n var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;\n var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;\n buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];\n }\n return buffer;\n };\n})();\n\nexport {\n FONT_IDENTITY_MATRIX,\n IDENTITY_MATRIX,\n OPS,\n VerbosityLevel,\n UNSUPPORTED_FEATURES,\n AnnotationBorderStyleType,\n AnnotationFieldFlag,\n AnnotationFlag,\n AnnotationType,\n FontType,\n ImageKind,\n CMapCompressionType,\n AbortException,\n InvalidPDFException,\n MissingPDFException,\n NativeImageDecoding,\n PasswordException,\n PasswordResponses,\n PermissionFlag,\n StreamType,\n TextRenderingMode,\n UnexpectedResponseException,\n UnknownErrorException,\n Util,\n FormatError,\n arrayByteLength,\n arraysToBytes,\n assert,\n bytesToString,\n createPromiseCapability,\n createObjectURL,\n getVerbosityLevel,\n info,\n isArrayBuffer,\n isArrayEqual,\n isBool,\n isEmptyObj,\n isNum,\n isString,\n isSpace,\n isSameOrigin,\n createValidAbsoluteUrl,\n isLittleEndian,\n isEvalSupported,\n log2,\n readInt8,\n readUint16,\n readUint32,\n removeNullCharacters,\n ReadableStream,\n URL,\n setVerbosityLevel,\n shadow,\n string32,\n stringToBytes,\n stringToPDFString,\n stringToUTF8String,\n utf8StringToString,\n warn,\n unreachable,\n};\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst globalScope = require('./global_scope');\n\n// Skip compatibility checks for the extensions and if we already ran\n// this module.\nif ((typeof PDFJSDev === 'undefined' ||\n !PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&\n !globalScope._pdfjsCompatibilityChecked) {\n\nglobalScope._pdfjsCompatibilityChecked = true;\n\nconst isNodeJS = require('./is_node');\n\nconst hasDOM = typeof window === 'object' && typeof document === 'object';\n\n// Support: Node.js\n(function checkNodeBtoa() {\n if (globalScope.btoa || !isNodeJS()) {\n return;\n }\n globalScope.btoa = function(chars) {\n // eslint-disable-next-line no-undef\n return Buffer.from(chars, 'binary').toString('base64');\n };\n})();\n\n// Support: Node.js\n(function checkNodeAtob() {\n if (globalScope.atob || !isNodeJS()) {\n return;\n }\n globalScope.atob = function(input) {\n // eslint-disable-next-line no-undef\n return Buffer.from(input, 'base64').toString('binary');\n };\n})();\n\n// Provides support for ChildNode.remove in legacy browsers.\n// Support: IE.\n(function checkChildNodeRemove() {\n if (!hasDOM) {\n return;\n }\n if (typeof Element.prototype.remove !== 'undefined') {\n return;\n }\n Element.prototype.remove = function () {\n if (this.parentNode) {\n // eslint-disable-next-line mozilla/avoid-removeChild\n this.parentNode.removeChild(this);\n }\n };\n})();\n\n// Provides support for DOMTokenList.prototype.{add, remove}, with more than\n// one parameter, in legacy browsers.\n// Support: IE\n(function checkDOMTokenListAddRemove() {\n if (!hasDOM || isNodeJS()) {\n return;\n }\n const div = document.createElement('div');\n div.classList.add('testOne', 'testTwo');\n\n if (div.classList.contains('testOne') === true &&\n div.classList.contains('testTwo') === true) {\n return;\n }\n const OriginalDOMTokenListAdd = DOMTokenList.prototype.add;\n const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;\n\n DOMTokenList.prototype.add = function(...tokens) {\n for (let token of tokens) {\n OriginalDOMTokenListAdd.call(this, token);\n }\n };\n DOMTokenList.prototype.remove = function(...tokens) {\n for (let token of tokens) {\n OriginalDOMTokenListRemove.call(this, token);\n }\n };\n})();\n\n// Provides support for DOMTokenList.prototype.toggle, with the optional\n// \"force\" parameter, in legacy browsers.\n// Support: IE\n(function checkDOMTokenListToggle() {\n if (!hasDOM || isNodeJS()) {\n return;\n }\n const div = document.createElement('div');\n if (div.classList.toggle('test', 0) === false) {\n return;\n }\n\n DOMTokenList.prototype.toggle = function(token) {\n let force = (arguments.length > 1 ? !!arguments[1] : !this.contains(token));\n return (this[force ? 'add' : 'remove'](token), force);\n };\n})();\n\n// Provides support for String.prototype.startsWith in legacy browsers.\n// Support: IE, Chrome<41\n(function checkStringStartsWith() {\n if (String.prototype.startsWith) {\n return;\n }\n require('core-js/fn/string/starts-with');\n})();\n\n// Provides support for String.prototype.endsWith in legacy browsers.\n// Support: IE, Chrome<41\n(function checkStringEndsWith() {\n if (String.prototype.endsWith) {\n return;\n }\n require('core-js/fn/string/ends-with');\n})();\n\n// Provides support for String.prototype.includes in legacy browsers.\n// Support: IE, Chrome<41\n(function checkStringIncludes() {\n if (String.prototype.includes) {\n return;\n }\n require('core-js/fn/string/includes');\n})();\n\n// Provides support for Array.prototype.includes in legacy browsers.\n// Support: IE, Chrome<47\n(function checkArrayIncludes() {\n if (Array.prototype.includes) {\n return;\n }\n require('core-js/fn/array/includes');\n})();\n\n// Provides support for Array.from in legacy browsers.\n// Support: IE\n(function checkArrayFrom() {\n if (Array.from) {\n return;\n }\n require('core-js/fn/array/from');\n})();\n\n// Provides support for Object.assign in legacy browsers.\n// Support: IE\n(function checkObjectAssign() {\n if (Object.assign) {\n return;\n }\n require('core-js/fn/object/assign');\n})();\n\n// Provides support for Math.log2 in legacy browsers.\n// Support: IE, Chrome<38\n(function checkMathLog2() {\n if (Math.log2) {\n return;\n }\n Math.log2 = require('core-js/fn/math/log2');\n})();\n\n// Provides support for Number.isNaN in legacy browsers.\n// Support: IE.\n(function checkNumberIsNaN() {\n if (Number.isNaN) {\n return;\n }\n Number.isNaN = require('core-js/fn/number/is-nan');\n})();\n\n// Provides support for Number.isInteger in legacy browsers.\n// Support: IE, Chrome<34\n(function checkNumberIsInteger() {\n if (Number.isInteger) {\n return;\n }\n Number.isInteger = require('core-js/fn/number/is-integer');\n})();\n\n// Support: IE, Safari<11, Chrome<63\n(function checkPromise() {\n if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('IMAGE_DECODERS')) {\n // The current image decoders are synchronous, hence `Promise` shouldn't\n // need to be polyfilled for the IMAGE_DECODERS build target.\n return;\n }\n if (globalScope.Promise && (globalScope.Promise.prototype &&\n globalScope.Promise.prototype.finally)) {\n return;\n }\n globalScope.Promise = require('core-js/fn/promise');\n})();\n\n// Support: IE<11, Safari<8, Chrome<36\n(function checkWeakMap() {\n if (globalScope.WeakMap) {\n return;\n }\n globalScope.WeakMap = require('core-js/fn/weak-map');\n})();\n\n// Support: IE11\n(function checkWeakSet() {\n if (globalScope.WeakSet) {\n return;\n }\n globalScope.WeakSet = require('core-js/fn/weak-set');\n})();\n\n// Provides support for String.codePointAt in legacy browsers.\n// Support: IE11.\n(function checkStringCodePointAt() {\n if (String.codePointAt) {\n return;\n }\n String.codePointAt = require('core-js/fn/string/code-point-at');\n})();\n\n// Provides support for String.fromCodePoint in legacy browsers.\n// Support: IE11.\n(function checkStringFromCodePoint() {\n if (String.fromCodePoint) {\n return;\n }\n String.fromCodePoint = require('core-js/fn/string/from-code-point');\n})();\n\n// Support: IE\n(function checkSymbol() {\n if (globalScope.Symbol) {\n return;\n }\n require('core-js/es6/symbol');\n})();\n\n// Provides support for String.prototype.padStart in legacy browsers.\n// Support: IE, Chrome<57\n(function checkStringPadStart() {\n if (String.prototype.padStart) {\n return;\n }\n require('core-js/fn/string/pad-start');\n})();\n\n// Provides support for String.prototype.padEnd in legacy browsers.\n// Support: IE, Chrome<57\n(function checkStringPadEnd() {\n if (String.prototype.padEnd) {\n return;\n }\n require('core-js/fn/string/pad-end');\n})();\n\n// Provides support for Object.values in legacy browsers.\n// Support: IE, Chrome<54\n(function checkObjectValues() {\n if (Object.values) {\n return;\n }\n Object.values = require('core-js/fn/object/values');\n})();\n\n}\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals module */\n\nmodule.exports =\n (typeof window !== 'undefined' && window.Math === Math) ? window :\n // eslint-disable-next-line no-undef\n (typeof global !== 'undefined' && global.Math === Math) ? global :\n (typeof self !== 'undefined' && self.Math === Math) ? self : {};\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals module, process */\n\nmodule.exports = function isNodeJS() {\n // NW.js / Electron is a browser context, but copies some Node.js objects; see\n // http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context\n // https://electronjs.org/docs/api/process#processversionselectron\n return typeof process === 'object' &&\n process + '' === '[object process]' &&\n !process.versions['nw'] && !process.versions['electron'];\n};\n","require('../../modules/es6.string.starts-with');\nmodule.exports = require('../../modules/_core').String.startsWith;\n","// 21.1.3.18 String.prototype.startsWith(searchString [, position ])\n'use strict';\nvar $export = require('./_export');\nvar toLength = require('./_to-length');\nvar context = require('./_string-context');\nvar STARTS_WITH = 'startsWith';\nvar $startsWith = ''[STARTS_WITH];\n\n$export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'String', {\n startsWith: function startsWith(searchString /* , position = 0 */) {\n var that = context(this, searchString, STARTS_WITH);\n var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));\n var search = String(searchString);\n return $startsWith\n ? $startsWith.call(that, search, index)\n : that.slice(index, index + search.length) === search;\n }\n});\n","var global = require('./_global');\nvar core = require('./_core');\nvar hide = require('./_hide');\nvar redefine = require('./_redefine');\nvar ctx = require('./_ctx');\nvar PROTOTYPE = 'prototype';\n\nvar $export = function (type, name, source) {\n var IS_FORCED = type & $export.F;\n var IS_GLOBAL = type & $export.G;\n var IS_STATIC = type & $export.S;\n var IS_PROTO = type & $export.P;\n var IS_BIND = type & $export.B;\n var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];\n var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});\n var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});\n var key, own, out, exp;\n if (IS_GLOBAL) source = name;\n for (key in source) {\n // contains in native\n own = !IS_FORCED && target && target[key] !== undefined;\n // export native or passed\n out = (own ? target : source)[key];\n // bind timers to global for call from export context\n exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;\n // extend global\n if (target) redefine(target, key, out, type & $export.U);\n // export\n if (exports[key] != out) hide(exports, key, exp);\n if (IS_PROTO && expProto[key] != out) expProto[key] = out;\n }\n};\nglobal.core = core;\n// type bitmap\n$export.F = 1; // forced\n$export.G = 2; // global\n$export.S = 4; // static\n$export.P = 8; // proto\n$export.B = 16; // bind\n$export.W = 32; // wrap\n$export.U = 64; // safe\n$export.R = 128; // real proto method for `library`\nmodule.exports = $export;\n","// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nvar global = module.exports = typeof window != 'undefined' && window.Math == Math\n ? window : typeof self != 'undefined' && self.Math == Math ? self\n // eslint-disable-next-line no-new-func\n : Function('return this')();\nif (typeof __g == 'number') __g = global; // eslint-disable-line no-undef\n","var core = module.exports = { version: '2.6.9' };\nif (typeof __e == 'number') __e = core; // eslint-disable-line no-undef\n","var dP = require('./_object-dp');\nvar createDesc = require('./_property-desc');\nmodule.exports = require('./_descriptors') ? function (object, key, value) {\n return dP.f(object, key, createDesc(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var anObject = require('./_an-object');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar toPrimitive = require('./_to-primitive');\nvar dP = Object.defineProperty;\n\nexports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return dP(O, P, Attributes);\n } catch (e) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n","var isObject = require('./_is-object');\nmodule.exports = function (it) {\n if (!isObject(it)) throw TypeError(it + ' is not an object!');\n return it;\n};\n","module.exports = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n","module.exports = !require('./_descriptors') && !require('./_fails')(function () {\n return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;\n});\n","// Thank's IE8 for his funny defineProperty\nmodule.exports = !require('./_fails')(function () {\n return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;\n});\n","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (e) {\n return true;\n }\n};\n","var isObject = require('./_is-object');\nvar document = require('./_global').document;\n// typeof document.createElement is 'object' in old IE\nvar is = isObject(document) && isObject(document.createElement);\nmodule.exports = function (it) {\n return is ? document.createElement(it) : {};\n};\n","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var global = require('./_global');\nvar hide = require('./_hide');\nvar has = require('./_has');\nvar SRC = require('./_uid')('src');\nvar $toString = require('./_function-to-string');\nvar TO_STRING = 'toString';\nvar TPL = ('' + $toString).split(TO_STRING);\n\nrequire('./_core').inspectSource = function (it) {\n return $toString.call(it);\n};\n\n(module.exports = function (O, key, val, safe) {\n var isFunction = typeof val == 'function';\n if (isFunction) has(val, 'name') || hide(val, 'name', key);\n if (O[key] === val) return;\n if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));\n if (O === global) {\n O[key] = val;\n } else if (!safe) {\n delete O[key];\n hide(O, key, val);\n } else if (O[key]) {\n O[key] = val;\n } else {\n hide(O, key, val);\n }\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, TO_STRING, function toString() {\n return typeof this == 'function' && this[SRC] || $toString.call(this);\n});\n","var hasOwnProperty = {}.hasOwnProperty;\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","module.exports = require('./_shared')('native-function-to-string', Function.toString);\n","var core = require('./_core');\nvar global = require('./_global');\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || (global[SHARED] = {});\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: core.version,\n mode: require('./_library') ? 'pure' : 'global',\n copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n});\n","module.exports = false;\n","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n","// 7.1.15 ToLength\nvar toInteger = require('./_to-integer');\nvar min = Math.min;\nmodule.exports = function (it) {\n return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991\n};\n","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n","// helper for String#{startsWith, endsWith, includes}\nvar isRegExp = require('./_is-regexp');\nvar defined = require('./_defined');\n\nmodule.exports = function (that, searchString, NAME) {\n if (isRegExp(searchString)) throw TypeError('String#' + NAME + \" doesn't accept regex!\");\n return String(defined(that));\n};\n","// 7.2.8 IsRegExp(argument)\nvar isObject = require('./_is-object');\nvar cof = require('./_cof');\nvar MATCH = require('./_wks')('match');\nmodule.exports = function (it) {\n var isRegExp;\n return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var store = require('./_shared')('wks');\nvar uid = require('./_uid');\nvar Symbol = require('./_global').Symbol;\nvar USE_SYMBOL = typeof Symbol == 'function';\n\nvar $exports = module.exports = function (name) {\n return store[name] || (store[name] =\n USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));\n};\n\n$exports.store = store;\n","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","var MATCH = require('./_wks')('match');\nmodule.exports = function (KEY) {\n var re = /./;\n try {\n '/./'[KEY](re);\n } catch (e) {\n try {\n re[MATCH] = false;\n return !'/./'[KEY](re);\n } catch (f) { /* empty */ }\n } return true;\n};\n","require('../../modules/es6.string.ends-with');\nmodule.exports = require('../../modules/_core').String.endsWith;\n","// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])\n'use strict';\nvar $export = require('./_export');\nvar toLength = require('./_to-length');\nvar context = require('./_string-context');\nvar ENDS_WITH = 'endsWith';\nvar $endsWith = ''[ENDS_WITH];\n\n$export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'String', {\n endsWith: function endsWith(searchString /* , endPosition = @length */) {\n var that = context(this, searchString, ENDS_WITH);\n var endPosition = arguments.length > 1 ? arguments[1] : undefined;\n var len = toLength(that.length);\n var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);\n var search = String(searchString);\n return $endsWith\n ? $endsWith.call(that, search, end)\n : that.slice(end - search.length, end) === search;\n }\n});\n","require('../../modules/es6.string.includes');\nmodule.exports = require('../../modules/_core').String.includes;\n","// 21.1.3.7 String.prototype.includes(searchString, position = 0)\n'use strict';\nvar $export = require('./_export');\nvar context = require('./_string-context');\nvar INCLUDES = 'includes';\n\n$export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String', {\n includes: function includes(searchString /* , position = 0 */) {\n return !!~context(this, searchString, INCLUDES)\n .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","require('../../modules/es7.array.includes');\nmodule.exports = require('../../modules/_core').Array.includes;\n","'use strict';\n// https://github.com/tc39/Array.prototype.includes\nvar $export = require('./_export');\nvar $includes = require('./_array-includes')(true);\n\n$export($export.P, 'Array', {\n includes: function includes(el /* , fromIndex = 0 */) {\n return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n\nrequire('./_add-to-unscopables')('includes');\n","// false -> Array#indexOf\n// true -> Array#includes\nvar toIObject = require('./_to-iobject');\nvar toLength = require('./_to-length');\nvar toAbsoluteIndex = require('./_to-absolute-index');\nmodule.exports = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) if (IS_INCLUDES || index in O) {\n if (O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n","// to indexed object, toObject with fallback for non-array-like ES3 strings\nvar IObject = require('./_iobject');\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return IObject(defined(it));\n};\n","// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar cof = require('./_cof');\n// eslint-disable-next-line no-prototype-builtins\nmodule.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {\n return cof(it) == 'String' ? it.split('') : Object(it);\n};\n","var toInteger = require('./_to-integer');\nvar max = Math.max;\nvar min = Math.min;\nmodule.exports = function (index, length) {\n index = toInteger(index);\n return index < 0 ? max(index + length, 0) : min(index, length);\n};\n","// 22.1.3.31 Array.prototype[@@unscopables]\nvar UNSCOPABLES = require('./_wks')('unscopables');\nvar ArrayProto = Array.prototype;\nif (ArrayProto[UNSCOPABLES] == undefined) require('./_hide')(ArrayProto, UNSCOPABLES, {});\nmodule.exports = function (key) {\n ArrayProto[UNSCOPABLES][key] = true;\n};\n","require('../../modules/es6.string.iterator');\nrequire('../../modules/es6.array.from');\nmodule.exports = require('../../modules/_core').Array.from;\n","'use strict';\nvar $at = require('./_string-at')(true);\n\n// 21.1.3.27 String.prototype[@@iterator]()\nrequire('./_iter-define')(String, 'String', function (iterated) {\n this._t = String(iterated); // target\n this._i = 0; // next index\n// 21.1.5.2.1 %StringIteratorPrototype%.next()\n}, function () {\n var O = this._t;\n var index = this._i;\n var point;\n if (index >= O.length) return { value: undefined, done: true };\n point = $at(O, index);\n this._i += point.length;\n return { value: point, done: false };\n});\n","var toInteger = require('./_to-integer');\nvar defined = require('./_defined');\n// true -> String#at\n// false -> String#codePointAt\nmodule.exports = function (TO_STRING) {\n return function (that, pos) {\n var s = String(defined(that));\n var i = toInteger(pos);\n var l = s.length;\n var a, b;\n if (i < 0 || i >= l) return TO_STRING ? '' : undefined;\n a = s.charCodeAt(i);\n return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff\n ? TO_STRING ? s.charAt(i) : a\n : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;\n };\n};\n","'use strict';\nvar LIBRARY = require('./_library');\nvar $export = require('./_export');\nvar redefine = require('./_redefine');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar $iterCreate = require('./_iter-create');\nvar setToStringTag = require('./_set-to-string-tag');\nvar getPrototypeOf = require('./_object-gpo');\nvar ITERATOR = require('./_wks')('iterator');\nvar BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`\nvar FF_ITERATOR = '@@iterator';\nvar KEYS = 'keys';\nvar VALUES = 'values';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {\n $iterCreate(Constructor, NAME, next);\n var getMethod = function (kind) {\n if (!BUGGY && kind in proto) return proto[kind];\n switch (kind) {\n case KEYS: return function keys() { return new Constructor(this, kind); };\n case VALUES: return function values() { return new Constructor(this, kind); };\n } return function entries() { return new Constructor(this, kind); };\n };\n var TAG = NAME + ' Iterator';\n var DEF_VALUES = DEFAULT == VALUES;\n var VALUES_BUG = false;\n var proto = Base.prototype;\n var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];\n var $default = $native || getMethod(DEFAULT);\n var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;\n var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;\n var methods, key, IteratorPrototype;\n // Fix native\n if ($anyNative) {\n IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));\n if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {\n // Set @@toStringTag to native iterators\n setToStringTag(IteratorPrototype, TAG, true);\n // fix for some old engines\n if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);\n }\n }\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEF_VALUES && $native && $native.name !== VALUES) {\n VALUES_BUG = true;\n $default = function values() { return $native.call(this); };\n }\n // Define iterator\n if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {\n hide(proto, ITERATOR, $default);\n }\n // Plug for library\n Iterators[NAME] = $default;\n Iterators[TAG] = returnThis;\n if (DEFAULT) {\n methods = {\n values: DEF_VALUES ? $default : getMethod(VALUES),\n keys: IS_SET ? $default : getMethod(KEYS),\n entries: $entries\n };\n if (FORCED) for (key in methods) {\n if (!(key in proto)) redefine(proto, key, methods[key]);\n } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);\n }\n return methods;\n};\n","module.exports = {};\n","'use strict';\nvar create = require('./_object-create');\nvar descriptor = require('./_property-desc');\nvar setToStringTag = require('./_set-to-string-tag');\nvar IteratorPrototype = {};\n\n// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()\nrequire('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function () { return this; });\n\nmodule.exports = function (Constructor, NAME, next) {\n Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });\n setToStringTag(Constructor, NAME + ' Iterator');\n};\n","// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])\nvar anObject = require('./_an-object');\nvar dPs = require('./_object-dps');\nvar enumBugKeys = require('./_enum-bug-keys');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar Empty = function () { /* empty */ };\nvar PROTOTYPE = 'prototype';\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar createDict = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = require('./_dom-create')('iframe');\n var i = enumBugKeys.length;\n var lt = '<';\n var gt = '>';\n var iframeDocument;\n iframe.style.display = 'none';\n require('./_html').appendChild(iframe);\n iframe.src = 'javascript:'; // eslint-disable-line no-script-url\n // createDict = iframe.contentWindow.Object;\n // html.removeChild(iframe);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);\n iframeDocument.close();\n createDict = iframeDocument.F;\n while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];\n return createDict();\n};\n\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n Empty[PROTOTYPE] = anObject(O);\n result = new Empty();\n Empty[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = createDict();\n return Properties === undefined ? result : dPs(result, Properties);\n};\n","var dP = require('./_object-dp');\nvar anObject = require('./_an-object');\nvar getKeys = require('./_object-keys');\n\nmodule.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = getKeys(Properties);\n var length = keys.length;\n var i = 0;\n var P;\n while (length > i) dP.f(O, P = keys[i++], Properties[P]);\n return O;\n};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","var has = require('./_has');\nvar toIObject = require('./_to-iobject');\nvar arrayIndexOf = require('./_array-includes')(false);\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\n\nmodule.exports = function (object, names) {\n var O = toIObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~arrayIndexOf(result, key) || result.push(key);\n }\n return result;\n};\n","var shared = require('./_shared')('keys');\nvar uid = require('./_uid');\nmodule.exports = function (key) {\n return shared[key] || (shared[key] = uid(key));\n};\n","// IE 8- don't enum bug keys\nmodule.exports = (\n 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'\n).split(',');\n","var document = require('./_global').document;\nmodule.exports = document && document.documentElement;\n","var def = require('./_object-dp').f;\nvar has = require('./_has');\nvar TAG = require('./_wks')('toStringTag');\n\nmodule.exports = function (it, tag, stat) {\n if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });\n};\n","// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)\nvar has = require('./_has');\nvar toObject = require('./_to-object');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar ObjectProto = Object.prototype;\n\nmodule.exports = Object.getPrototypeOf || function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectProto : null;\n};\n","// 7.1.13 ToObject(argument)\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return Object(defined(it));\n};\n","'use strict';\nvar ctx = require('./_ctx');\nvar $export = require('./_export');\nvar toObject = require('./_to-object');\nvar call = require('./_iter-call');\nvar isArrayIter = require('./_is-array-iter');\nvar toLength = require('./_to-length');\nvar createProperty = require('./_create-property');\nvar getIterFn = require('./core.get-iterator-method');\n\n$export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', {\n // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)\n from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {\n var O = toObject(arrayLike);\n var C = typeof this == 'function' ? this : Array;\n var aLen = arguments.length;\n var mapfn = aLen > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var index = 0;\n var iterFn = getIterFn(O);\n var length, result, step, iterator;\n if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);\n // if object isn't iterable or it's array with default iterator - use simple case\n if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {\n for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {\n createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);\n }\n } else {\n length = toLength(O.length);\n for (result = new C(length); length > index; index++) {\n createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);\n }\n }\n result.length = index;\n return result;\n }\n});\n","// call something on iterator step with safe closing on error\nvar anObject = require('./_an-object');\nmodule.exports = function (iterator, fn, value, entries) {\n try {\n return entries ? fn(anObject(value)[0], value[1]) : fn(value);\n // 7.4.6 IteratorClose(iterator, completion)\n } catch (e) {\n var ret = iterator['return'];\n if (ret !== undefined) anObject(ret.call(iterator));\n throw e;\n }\n};\n","// check on default Array iterator\nvar Iterators = require('./_iterators');\nvar ITERATOR = require('./_wks')('iterator');\nvar ArrayProto = Array.prototype;\n\nmodule.exports = function (it) {\n return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);\n};\n","'use strict';\nvar $defineProperty = require('./_object-dp');\nvar createDesc = require('./_property-desc');\n\nmodule.exports = function (object, index, value) {\n if (index in object) $defineProperty.f(object, index, createDesc(0, value));\n else object[index] = value;\n};\n","var classof = require('./_classof');\nvar ITERATOR = require('./_wks')('iterator');\nvar Iterators = require('./_iterators');\nmodule.exports = require('./_core').getIteratorMethod = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","// getting tag from 19.1.3.6 Object.prototype.toString()\nvar cof = require('./_cof');\nvar TAG = require('./_wks')('toStringTag');\n// ES3 wrong here\nvar ARG = cof(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (e) { /* empty */ }\n};\n\nmodule.exports = function (it) {\n var O, T, B;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T\n // builtinTag case\n : ARG ? cof(O)\n // ES3 arguments fallback\n : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;\n};\n","var ITERATOR = require('./_wks')('iterator');\nvar SAFE_CLOSING = false;\n\ntry {\n var riter = [7][ITERATOR]();\n riter['return'] = function () { SAFE_CLOSING = true; };\n // eslint-disable-next-line no-throw-literal\n Array.from(riter, function () { throw 2; });\n} catch (e) { /* empty */ }\n\nmodule.exports = function (exec, skipClosing) {\n if (!skipClosing && !SAFE_CLOSING) return false;\n var safe = false;\n try {\n var arr = [7];\n var iter = arr[ITERATOR]();\n iter.next = function () { return { done: safe = true }; };\n arr[ITERATOR] = function () { return iter; };\n exec(arr);\n } catch (e) { /* empty */ }\n return safe;\n};\n","require('../../modules/es6.object.assign');\nmodule.exports = require('../../modules/_core').Object.assign;\n","// 19.1.3.1 Object.assign(target, source)\nvar $export = require('./_export');\n\n$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') });\n","'use strict';\n// 19.1.2.1 Object.assign(target, source, ...)\nvar DESCRIPTORS = require('./_descriptors');\nvar getKeys = require('./_object-keys');\nvar gOPS = require('./_object-gops');\nvar pIE = require('./_object-pie');\nvar toObject = require('./_to-object');\nvar IObject = require('./_iobject');\nvar $assign = Object.assign;\n\n// should work with symbols and should have deterministic property order (V8 bug)\nmodule.exports = !$assign || require('./_fails')(function () {\n var A = {};\n var B = {};\n // eslint-disable-next-line no-undef\n var S = Symbol();\n var K = 'abcdefghijklmnopqrst';\n A[S] = 7;\n K.split('').forEach(function (k) { B[k] = k; });\n return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;\n}) ? function assign(target, source) { // eslint-disable-line no-unused-vars\n var T = toObject(target);\n var aLen = arguments.length;\n var index = 1;\n var getSymbols = gOPS.f;\n var isEnum = pIE.f;\n while (aLen > index) {\n var S = IObject(arguments[index++]);\n var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);\n var length = keys.length;\n var j = 0;\n var key;\n while (length > j) {\n key = keys[j++];\n if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];\n }\n } return T;\n} : $assign;\n","exports.f = Object.getOwnPropertySymbols;\n","exports.f = {}.propertyIsEnumerable;\n","require('../../modules/es6.math.log2');\nmodule.exports = require('../../modules/_core').Math.log2;\n","// 20.2.2.22 Math.log2(x)\nvar $export = require('./_export');\n\n$export($export.S, 'Math', {\n log2: function log2(x) {\n return Math.log(x) / Math.LN2;\n }\n});\n","require('../../modules/es6.number.is-nan');\nmodule.exports = require('../../modules/_core').Number.isNaN;\n","// 20.1.2.4 Number.isNaN(number)\nvar $export = require('./_export');\n\n$export($export.S, 'Number', {\n isNaN: function isNaN(number) {\n // eslint-disable-next-line no-self-compare\n return number != number;\n }\n});\n","require('../../modules/es6.number.is-integer');\nmodule.exports = require('../../modules/_core').Number.isInteger;\n","// 20.1.2.3 Number.isInteger(number)\nvar $export = require('./_export');\n\n$export($export.S, 'Number', { isInteger: require('./_is-integer') });\n","// 20.1.2.3 Number.isInteger(number)\nvar isObject = require('./_is-object');\nvar floor = Math.floor;\nmodule.exports = function isInteger(it) {\n return !isObject(it) && isFinite(it) && floor(it) === it;\n};\n","require('../modules/es6.object.to-string');\nrequire('../modules/es6.string.iterator');\nrequire('../modules/web.dom.iterable');\nrequire('../modules/es6.promise');\nrequire('../modules/es7.promise.finally');\nrequire('../modules/es7.promise.try');\nmodule.exports = require('../modules/_core').Promise;\n","'use strict';\n// 19.1.3.6 Object.prototype.toString()\nvar classof = require('./_classof');\nvar test = {};\ntest[require('./_wks')('toStringTag')] = 'z';\nif (test + '' != '[object z]') {\n require('./_redefine')(Object.prototype, 'toString', function toString() {\n return '[object ' + classof(this) + ']';\n }, true);\n}\n","var $iterators = require('./es6.array.iterator');\nvar getKeys = require('./_object-keys');\nvar redefine = require('./_redefine');\nvar global = require('./_global');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar wks = require('./_wks');\nvar ITERATOR = wks('iterator');\nvar TO_STRING_TAG = wks('toStringTag');\nvar ArrayValues = Iterators.Array;\n\nvar DOMIterables = {\n CSSRuleList: true, // TODO: Not spec compliant, should be false.\n CSSStyleDeclaration: false,\n CSSValueList: false,\n ClientRectList: false,\n DOMRectList: false,\n DOMStringList: false,\n DOMTokenList: true,\n DataTransferItemList: false,\n FileList: false,\n HTMLAllCollection: false,\n HTMLCollection: false,\n HTMLFormElement: false,\n HTMLSelectElement: false,\n MediaList: true, // TODO: Not spec compliant, should be false.\n MimeTypeArray: false,\n NamedNodeMap: false,\n NodeList: true,\n PaintRequestList: false,\n Plugin: false,\n PluginArray: false,\n SVGLengthList: false,\n SVGNumberList: false,\n SVGPathSegList: false,\n SVGPointList: false,\n SVGStringList: false,\n SVGTransformList: false,\n SourceBufferList: false,\n StyleSheetList: true, // TODO: Not spec compliant, should be false.\n TextTrackCueList: false,\n TextTrackList: false,\n TouchList: false\n};\n\nfor (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {\n var NAME = collections[i];\n var explicit = DOMIterables[NAME];\n var Collection = global[NAME];\n var proto = Collection && Collection.prototype;\n var key;\n if (proto) {\n if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);\n if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);\n Iterators[NAME] = ArrayValues;\n if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);\n }\n}\n","'use strict';\nvar addToUnscopables = require('./_add-to-unscopables');\nvar step = require('./_iter-step');\nvar Iterators = require('./_iterators');\nvar toIObject = require('./_to-iobject');\n\n// 22.1.3.4 Array.prototype.entries()\n// 22.1.3.13 Array.prototype.keys()\n// 22.1.3.29 Array.prototype.values()\n// 22.1.3.30 Array.prototype[@@iterator]()\nmodule.exports = require('./_iter-define')(Array, 'Array', function (iterated, kind) {\n this._t = toIObject(iterated); // target\n this._i = 0; // next index\n this._k = kind; // kind\n// 22.1.5.2.1 %ArrayIteratorPrototype%.next()\n}, function () {\n var O = this._t;\n var kind = this._k;\n var index = this._i++;\n if (!O || index >= O.length) {\n this._t = undefined;\n return step(1);\n }\n if (kind == 'keys') return step(0, index);\n if (kind == 'values') return step(0, O[index]);\n return step(0, [index, O[index]]);\n}, 'values');\n\n// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)\nIterators.Arguments = Iterators.Array;\n\naddToUnscopables('keys');\naddToUnscopables('values');\naddToUnscopables('entries');\n","module.exports = function (done, value) {\n return { value: value, done: !!done };\n};\n","'use strict';\nvar LIBRARY = require('./_library');\nvar global = require('./_global');\nvar ctx = require('./_ctx');\nvar classof = require('./_classof');\nvar $export = require('./_export');\nvar isObject = require('./_is-object');\nvar aFunction = require('./_a-function');\nvar anInstance = require('./_an-instance');\nvar forOf = require('./_for-of');\nvar speciesConstructor = require('./_species-constructor');\nvar task = require('./_task').set;\nvar microtask = require('./_microtask')();\nvar newPromiseCapabilityModule = require('./_new-promise-capability');\nvar perform = require('./_perform');\nvar userAgent = require('./_user-agent');\nvar promiseResolve = require('./_promise-resolve');\nvar PROMISE = 'Promise';\nvar TypeError = global.TypeError;\nvar process = global.process;\nvar versions = process && process.versions;\nvar v8 = versions && versions.v8 || '';\nvar $Promise = global[PROMISE];\nvar isNode = classof(process) == 'process';\nvar empty = function () { /* empty */ };\nvar Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;\nvar newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;\n\nvar USE_NATIVE = !!function () {\n try {\n // correct subclassing with @@species support\n var promise = $Promise.resolve(1);\n var FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function (exec) {\n exec(empty, empty);\n };\n // unhandled rejections tracking support, NodeJS Promise without it fails @@species test\n return (isNode || typeof PromiseRejectionEvent == 'function')\n && promise.then(empty) instanceof FakePromise\n // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables\n // https://bugs.chromium.org/p/chromium/issues/detail?id=830565\n // we can't detect it synchronously, so just check versions\n && v8.indexOf('6.6') !== 0\n && userAgent.indexOf('Chrome/66') === -1;\n } catch (e) { /* empty */ }\n}();\n\n// helpers\nvar isThenable = function (it) {\n var then;\n return isObject(it) && typeof (then = it.then) == 'function' ? then : false;\n};\nvar notify = function (promise, isReject) {\n if (promise._n) return;\n promise._n = true;\n var chain = promise._c;\n microtask(function () {\n var value = promise._v;\n var ok = promise._s == 1;\n var i = 0;\n var run = function (reaction) {\n var handler = ok ? reaction.ok : reaction.fail;\n var resolve = reaction.resolve;\n var reject = reaction.reject;\n var domain = reaction.domain;\n var result, then, exited;\n try {\n if (handler) {\n if (!ok) {\n if (promise._h == 2) onHandleUnhandled(promise);\n promise._h = 1;\n }\n if (handler === true) result = value;\n else {\n if (domain) domain.enter();\n result = handler(value); // may throw\n if (domain) {\n domain.exit();\n exited = true;\n }\n }\n if (result === reaction.promise) {\n reject(TypeError('Promise-chain cycle'));\n } else if (then = isThenable(result)) {\n then.call(result, resolve, reject);\n } else resolve(result);\n } else reject(value);\n } catch (e) {\n if (domain && !exited) domain.exit();\n reject(e);\n }\n };\n while (chain.length > i) run(chain[i++]); // variable length - can't use forEach\n promise._c = [];\n promise._n = false;\n if (isReject && !promise._h) onUnhandled(promise);\n });\n};\nvar onUnhandled = function (promise) {\n task.call(global, function () {\n var value = promise._v;\n var unhandled = isUnhandled(promise);\n var result, handler, console;\n if (unhandled) {\n result = perform(function () {\n if (isNode) {\n process.emit('unhandledRejection', value, promise);\n } else if (handler = global.onunhandledrejection) {\n handler({ promise: promise, reason: value });\n } else if ((console = global.console) && console.error) {\n console.error('Unhandled promise rejection', value);\n }\n });\n // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should\n promise._h = isNode || isUnhandled(promise) ? 2 : 1;\n } promise._a = undefined;\n if (unhandled && result.e) throw result.v;\n });\n};\nvar isUnhandled = function (promise) {\n return promise._h !== 1 && (promise._a || promise._c).length === 0;\n};\nvar onHandleUnhandled = function (promise) {\n task.call(global, function () {\n var handler;\n if (isNode) {\n process.emit('rejectionHandled', promise);\n } else if (handler = global.onrejectionhandled) {\n handler({ promise: promise, reason: promise._v });\n }\n });\n};\nvar $reject = function (value) {\n var promise = this;\n if (promise._d) return;\n promise._d = true;\n promise = promise._w || promise; // unwrap\n promise._v = value;\n promise._s = 2;\n if (!promise._a) promise._a = promise._c.slice();\n notify(promise, true);\n};\nvar $resolve = function (value) {\n var promise = this;\n var then;\n if (promise._d) return;\n promise._d = true;\n promise = promise._w || promise; // unwrap\n try {\n if (promise === value) throw TypeError(\"Promise can't be resolved itself\");\n if (then = isThenable(value)) {\n microtask(function () {\n var wrapper = { _w: promise, _d: false }; // wrap\n try {\n then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));\n } catch (e) {\n $reject.call(wrapper, e);\n }\n });\n } else {\n promise._v = value;\n promise._s = 1;\n notify(promise, false);\n }\n } catch (e) {\n $reject.call({ _w: promise, _d: false }, e); // wrap\n }\n};\n\n// constructor polyfill\nif (!USE_NATIVE) {\n // 25.4.3.1 Promise(executor)\n $Promise = function Promise(executor) {\n anInstance(this, $Promise, PROMISE, '_h');\n aFunction(executor);\n Internal.call(this);\n try {\n executor(ctx($resolve, this, 1), ctx($reject, this, 1));\n } catch (err) {\n $reject.call(this, err);\n }\n };\n // eslint-disable-next-line no-unused-vars\n Internal = function Promise(executor) {\n this._c = []; // <- awaiting reactions\n this._a = undefined; // <- checked in isUnhandled reactions\n this._s = 0; // <- state\n this._d = false; // <- done\n this._v = undefined; // <- value\n this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled\n this._n = false; // <- notify\n };\n Internal.prototype = require('./_redefine-all')($Promise.prototype, {\n // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)\n then: function then(onFulfilled, onRejected) {\n var reaction = newPromiseCapability(speciesConstructor(this, $Promise));\n reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;\n reaction.fail = typeof onRejected == 'function' && onRejected;\n reaction.domain = isNode ? process.domain : undefined;\n this._c.push(reaction);\n if (this._a) this._a.push(reaction);\n if (this._s) notify(this, false);\n return reaction.promise;\n },\n // 25.4.5.1 Promise.prototype.catch(onRejected)\n 'catch': function (onRejected) {\n return this.then(undefined, onRejected);\n }\n });\n OwnPromiseCapability = function () {\n var promise = new Internal();\n this.promise = promise;\n this.resolve = ctx($resolve, promise, 1);\n this.reject = ctx($reject, promise, 1);\n };\n newPromiseCapabilityModule.f = newPromiseCapability = function (C) {\n return C === $Promise || C === Wrapper\n ? new OwnPromiseCapability(C)\n : newGenericPromiseCapability(C);\n };\n}\n\n$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });\nrequire('./_set-to-string-tag')($Promise, PROMISE);\nrequire('./_set-species')(PROMISE);\nWrapper = require('./_core')[PROMISE];\n\n// statics\n$export($export.S + $export.F * !USE_NATIVE, PROMISE, {\n // 25.4.4.5 Promise.reject(r)\n reject: function reject(r) {\n var capability = newPromiseCapability(this);\n var $$reject = capability.reject;\n $$reject(r);\n return capability.promise;\n }\n});\n$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {\n // 25.4.4.6 Promise.resolve(x)\n resolve: function resolve(x) {\n return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);\n }\n});\n$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function (iter) {\n $Promise.all(iter)['catch'](empty);\n})), PROMISE, {\n // 25.4.4.1 Promise.all(iterable)\n all: function all(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var values = [];\n var index = 0;\n var remaining = 1;\n forOf(iterable, false, function (promise) {\n var $index = index++;\n var alreadyCalled = false;\n values.push(undefined);\n remaining++;\n C.resolve(promise).then(function (value) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[$index] = value;\n --remaining || resolve(values);\n }, reject);\n });\n --remaining || resolve(values);\n });\n if (result.e) reject(result.v);\n return capability.promise;\n },\n // 25.4.4.4 Promise.race(iterable)\n race: function race(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var reject = capability.reject;\n var result = perform(function () {\n forOf(iterable, false, function (promise) {\n C.resolve(promise).then(capability.resolve, reject);\n });\n });\n if (result.e) reject(result.v);\n return capability.promise;\n }\n});\n","module.exports = function (it, Constructor, name, forbiddenField) {\n if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {\n throw TypeError(name + ': incorrect invocation!');\n } return it;\n};\n","var ctx = require('./_ctx');\nvar call = require('./_iter-call');\nvar isArrayIter = require('./_is-array-iter');\nvar anObject = require('./_an-object');\nvar toLength = require('./_to-length');\nvar getIterFn = require('./core.get-iterator-method');\nvar BREAK = {};\nvar RETURN = {};\nvar exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {\n var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);\n var f = ctx(fn, that, entries ? 2 : 1);\n var index = 0;\n var length, step, iterator, result;\n if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');\n // fast case for arrays with default iterator\n if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {\n result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);\n if (result === BREAK || result === RETURN) return result;\n } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {\n result = call(iterator, f, step.value, entries);\n if (result === BREAK || result === RETURN) return result;\n }\n};\nexports.BREAK = BREAK;\nexports.RETURN = RETURN;\n","// 7.3.20 SpeciesConstructor(O, defaultConstructor)\nvar anObject = require('./_an-object');\nvar aFunction = require('./_a-function');\nvar SPECIES = require('./_wks')('species');\nmodule.exports = function (O, D) {\n var C = anObject(O).constructor;\n var S;\n return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);\n};\n","var ctx = require('./_ctx');\nvar invoke = require('./_invoke');\nvar html = require('./_html');\nvar cel = require('./_dom-create');\nvar global = require('./_global');\nvar process = global.process;\nvar setTask = global.setImmediate;\nvar clearTask = global.clearImmediate;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\nvar run = function () {\n var id = +this;\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\nvar listener = function (event) {\n run.call(event.data);\n};\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!setTask || !clearTask) {\n setTask = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n invoke(typeof fn == 'function' ? fn : Function(fn), args);\n };\n defer(counter);\n return counter;\n };\n clearTask = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (require('./_cof')(process) == 'process') {\n defer = function (id) {\n process.nextTick(ctx(run, id, 1));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(ctx(run, id, 1));\n };\n // Browsers with MessageChannel, includes WebWorkers\n } else if (MessageChannel) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = ctx(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {\n defer = function (id) {\n global.postMessage(id + '', '*');\n };\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in cel('script')) {\n defer = function (id) {\n html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run.call(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(ctx(run, id, 1), 0);\n };\n }\n}\nmodule.exports = {\n set: setTask,\n clear: clearTask\n};\n","// fast apply, http://jsperf.lnkit.com/fast-apply/5\nmodule.exports = function (fn, args, that) {\n var un = that === undefined;\n switch (args.length) {\n case 0: return un ? fn()\n : fn.call(that);\n case 1: return un ? fn(args[0])\n : fn.call(that, args[0]);\n case 2: return un ? fn(args[0], args[1])\n : fn.call(that, args[0], args[1]);\n case 3: return un ? fn(args[0], args[1], args[2])\n : fn.call(that, args[0], args[1], args[2]);\n case 4: return un ? fn(args[0], args[1], args[2], args[3])\n : fn.call(that, args[0], args[1], args[2], args[3]);\n } return fn.apply(that, args);\n};\n","var global = require('./_global');\nvar macrotask = require('./_task').set;\nvar Observer = global.MutationObserver || global.WebKitMutationObserver;\nvar process = global.process;\nvar Promise = global.Promise;\nvar isNode = require('./_cof')(process) == 'process';\n\nmodule.exports = function () {\n var head, last, notify;\n\n var flush = function () {\n var parent, fn;\n if (isNode && (parent = process.domain)) parent.exit();\n while (head) {\n fn = head.fn;\n head = head.next;\n try {\n fn();\n } catch (e) {\n if (head) notify();\n else last = undefined;\n throw e;\n }\n } last = undefined;\n if (parent) parent.enter();\n };\n\n // Node.js\n if (isNode) {\n notify = function () {\n process.nextTick(flush);\n };\n // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339\n } else if (Observer && !(global.navigator && global.navigator.standalone)) {\n var toggle = true;\n var node = document.createTextNode('');\n new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new\n notify = function () {\n node.data = toggle = !toggle;\n };\n // environments with maybe non-completely correct, but existent Promise\n } else if (Promise && Promise.resolve) {\n // Promise.resolve without an argument throws an error in LG WebOS 2\n var promise = Promise.resolve(undefined);\n notify = function () {\n promise.then(flush);\n };\n // for other environments - macrotask based on:\n // - setImmediate\n // - MessageChannel\n // - window.postMessag\n // - onreadystatechange\n // - setTimeout\n } else {\n notify = function () {\n // strange IE + webpack dev server bug - use .call(global)\n macrotask.call(global, flush);\n };\n }\n\n return function (fn) {\n var task = { fn: fn, next: undefined };\n if (last) last.next = task;\n if (!head) {\n head = task;\n notify();\n } last = task;\n };\n};\n","'use strict';\n// 25.4.1.5 NewPromiseCapability(C)\nvar aFunction = require('./_a-function');\n\nfunction PromiseCapability(C) {\n var resolve, reject;\n this.promise = new C(function ($$resolve, $$reject) {\n if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');\n resolve = $$resolve;\n reject = $$reject;\n });\n this.resolve = aFunction(resolve);\n this.reject = aFunction(reject);\n}\n\nmodule.exports.f = function (C) {\n return new PromiseCapability(C);\n};\n","module.exports = function (exec) {\n try {\n return { e: false, v: exec() };\n } catch (e) {\n return { e: true, v: e };\n }\n};\n","var global = require('./_global');\nvar navigator = global.navigator;\n\nmodule.exports = navigator && navigator.userAgent || '';\n","var anObject = require('./_an-object');\nvar isObject = require('./_is-object');\nvar newPromiseCapability = require('./_new-promise-capability');\n\nmodule.exports = function (C, x) {\n anObject(C);\n if (isObject(x) && x.constructor === C) return x;\n var promiseCapability = newPromiseCapability.f(C);\n var resolve = promiseCapability.resolve;\n resolve(x);\n return promiseCapability.promise;\n};\n","var redefine = require('./_redefine');\nmodule.exports = function (target, src, safe) {\n for (var key in src) redefine(target, key, src[key], safe);\n return target;\n};\n","'use strict';\nvar global = require('./_global');\nvar dP = require('./_object-dp');\nvar DESCRIPTORS = require('./_descriptors');\nvar SPECIES = require('./_wks')('species');\n\nmodule.exports = function (KEY) {\n var C = global[KEY];\n if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n};\n","// https://github.com/tc39/proposal-promise-finally\n'use strict';\nvar $export = require('./_export');\nvar core = require('./_core');\nvar global = require('./_global');\nvar speciesConstructor = require('./_species-constructor');\nvar promiseResolve = require('./_promise-resolve');\n\n$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {\n var C = speciesConstructor(this, core.Promise || global.Promise);\n var isFunction = typeof onFinally == 'function';\n return this.then(\n isFunction ? function (x) {\n return promiseResolve(C, onFinally()).then(function () { return x; });\n } : onFinally,\n isFunction ? function (e) {\n return promiseResolve(C, onFinally()).then(function () { throw e; });\n } : onFinally\n );\n} });\n","'use strict';\n// https://github.com/tc39/proposal-promise-try\nvar $export = require('./_export');\nvar newPromiseCapability = require('./_new-promise-capability');\nvar perform = require('./_perform');\n\n$export($export.S, 'Promise', { 'try': function (callbackfn) {\n var promiseCapability = newPromiseCapability.f(this);\n var result = perform(callbackfn);\n (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);\n return promiseCapability.promise;\n} });\n","require('../modules/es6.object.to-string');\nrequire('../modules/web.dom.iterable');\nrequire('../modules/es6.weak-map');\nrequire('../modules/es7.weak-map.of');\nrequire('../modules/es7.weak-map.from');\nmodule.exports = require('../modules/_core').WeakMap;\n","'use strict';\nvar global = require('./_global');\nvar each = require('./_array-methods')(0);\nvar redefine = require('./_redefine');\nvar meta = require('./_meta');\nvar assign = require('./_object-assign');\nvar weak = require('./_collection-weak');\nvar isObject = require('./_is-object');\nvar validate = require('./_validate-collection');\nvar NATIVE_WEAK_MAP = require('./_validate-collection');\nvar IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;\nvar WEAK_MAP = 'WeakMap';\nvar getWeak = meta.getWeak;\nvar isExtensible = Object.isExtensible;\nvar uncaughtFrozenStore = weak.ufstore;\nvar InternalMap;\n\nvar wrapper = function (get) {\n return function WeakMap() {\n return get(this, arguments.length > 0 ? arguments[0] : undefined);\n };\n};\n\nvar methods = {\n // 23.3.3.3 WeakMap.prototype.get(key)\n get: function get(key) {\n if (isObject(key)) {\n var data = getWeak(key);\n if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);\n return data ? data[this._i] : undefined;\n }\n },\n // 23.3.3.5 WeakMap.prototype.set(key, value)\n set: function set(key, value) {\n return weak.def(validate(this, WEAK_MAP), key, value);\n }\n};\n\n// 23.3 WeakMap Objects\nvar $WeakMap = module.exports = require('./_collection')(WEAK_MAP, wrapper, methods, weak, true, true);\n\n// IE11 WeakMap frozen keys fix\nif (NATIVE_WEAK_MAP && IS_IE11) {\n InternalMap = weak.getConstructor(wrapper, WEAK_MAP);\n assign(InternalMap.prototype, methods);\n meta.NEED = true;\n each(['delete', 'has', 'get', 'set'], function (key) {\n var proto = $WeakMap.prototype;\n var method = proto[key];\n redefine(proto, key, function (a, b) {\n // store frozen objects on internal weakmap shim\n if (isObject(a) && !isExtensible(a)) {\n if (!this._f) this._f = new InternalMap();\n var result = this._f[key](a, b);\n return key == 'set' ? this : result;\n // store all the rest on native weakmap\n } return method.call(this, a, b);\n });\n });\n}\n","// 0 -> Array#forEach\n// 1 -> Array#map\n// 2 -> Array#filter\n// 3 -> Array#some\n// 4 -> Array#every\n// 5 -> Array#find\n// 6 -> Array#findIndex\nvar ctx = require('./_ctx');\nvar IObject = require('./_iobject');\nvar toObject = require('./_to-object');\nvar toLength = require('./_to-length');\nvar asc = require('./_array-species-create');\nmodule.exports = function (TYPE, $create) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n var create = $create || asc;\n return function ($this, callbackfn, that) {\n var O = toObject($this);\n var self = IObject(O);\n var f = ctx(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;\n var val, res;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n val = self[index];\n res = f(val, index, O);\n if (TYPE) {\n if (IS_MAP) result[index] = res; // map\n else if (res) switch (TYPE) {\n case 3: return true; // some\n case 5: return val; // find\n case 6: return index; // findIndex\n case 2: result.push(val); // filter\n } else if (IS_EVERY) return false; // every\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;\n };\n};\n","// 9.4.2.3 ArraySpeciesCreate(originalArray, length)\nvar speciesConstructor = require('./_array-species-constructor');\n\nmodule.exports = function (original, length) {\n return new (speciesConstructor(original))(length);\n};\n","var isObject = require('./_is-object');\nvar isArray = require('./_is-array');\nvar SPECIES = require('./_wks')('species');\n\nmodule.exports = function (original) {\n var C;\n if (isArray(original)) {\n C = original.constructor;\n // cross-realm fallback\n if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;\n if (isObject(C)) {\n C = C[SPECIES];\n if (C === null) C = undefined;\n }\n } return C === undefined ? Array : C;\n};\n","// 7.2.2 IsArray(argument)\nvar cof = require('./_cof');\nmodule.exports = Array.isArray || function isArray(arg) {\n return cof(arg) == 'Array';\n};\n","var META = require('./_uid')('meta');\nvar isObject = require('./_is-object');\nvar has = require('./_has');\nvar setDesc = require('./_object-dp').f;\nvar id = 0;\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\nvar FREEZE = !require('./_fails')(function () {\n return isExtensible(Object.preventExtensions({}));\n});\nvar setMeta = function (it) {\n setDesc(it, META, { value: {\n i: 'O' + ++id, // object ID\n w: {} // weak collections IDs\n } });\n};\nvar fastKey = function (it, create) {\n // return primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMeta(it);\n // return object ID\n } return it[META].i;\n};\nvar getWeak = function (it, create) {\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMeta(it);\n // return hash weak collections IDs\n } return it[META].w;\n};\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);\n return it;\n};\nvar meta = module.exports = {\n KEY: META,\n NEED: false,\n fastKey: fastKey,\n getWeak: getWeak,\n onFreeze: onFreeze\n};\n","'use strict';\nvar redefineAll = require('./_redefine-all');\nvar getWeak = require('./_meta').getWeak;\nvar anObject = require('./_an-object');\nvar isObject = require('./_is-object');\nvar anInstance = require('./_an-instance');\nvar forOf = require('./_for-of');\nvar createArrayMethod = require('./_array-methods');\nvar $has = require('./_has');\nvar validate = require('./_validate-collection');\nvar arrayFind = createArrayMethod(5);\nvar arrayFindIndex = createArrayMethod(6);\nvar id = 0;\n\n// fallback for uncaught frozen keys\nvar uncaughtFrozenStore = function (that) {\n return that._l || (that._l = new UncaughtFrozenStore());\n};\nvar UncaughtFrozenStore = function () {\n this.a = [];\n};\nvar findUncaughtFrozen = function (store, key) {\n return arrayFind(store.a, function (it) {\n return it[0] === key;\n });\n};\nUncaughtFrozenStore.prototype = {\n get: function (key) {\n var entry = findUncaughtFrozen(this, key);\n if (entry) return entry[1];\n },\n has: function (key) {\n return !!findUncaughtFrozen(this, key);\n },\n set: function (key, value) {\n var entry = findUncaughtFrozen(this, key);\n if (entry) entry[1] = value;\n else this.a.push([key, value]);\n },\n 'delete': function (key) {\n var index = arrayFindIndex(this.a, function (it) {\n return it[0] === key;\n });\n if (~index) this.a.splice(index, 1);\n return !!~index;\n }\n};\n\nmodule.exports = {\n getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {\n var C = wrapper(function (that, iterable) {\n anInstance(that, C, NAME, '_i');\n that._t = NAME; // collection type\n that._i = id++; // collection id\n that._l = undefined; // leak store for uncaught frozen objects\n if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);\n });\n redefineAll(C.prototype, {\n // 23.3.3.2 WeakMap.prototype.delete(key)\n // 23.4.3.3 WeakSet.prototype.delete(value)\n 'delete': function (key) {\n if (!isObject(key)) return false;\n var data = getWeak(key);\n if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);\n return data && $has(data, this._i) && delete data[this._i];\n },\n // 23.3.3.4 WeakMap.prototype.has(key)\n // 23.4.3.4 WeakSet.prototype.has(value)\n has: function has(key) {\n if (!isObject(key)) return false;\n var data = getWeak(key);\n if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);\n return data && $has(data, this._i);\n }\n });\n return C;\n },\n def: function (that, key, value) {\n var data = getWeak(anObject(key), true);\n if (data === true) uncaughtFrozenStore(that).set(key, value);\n else data[that._i] = value;\n return that;\n },\n ufstore: uncaughtFrozenStore\n};\n","var isObject = require('./_is-object');\nmodule.exports = function (it, TYPE) {\n if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');\n return it;\n};\n","'use strict';\nvar global = require('./_global');\nvar $export = require('./_export');\nvar redefine = require('./_redefine');\nvar redefineAll = require('./_redefine-all');\nvar meta = require('./_meta');\nvar forOf = require('./_for-of');\nvar anInstance = require('./_an-instance');\nvar isObject = require('./_is-object');\nvar fails = require('./_fails');\nvar $iterDetect = require('./_iter-detect');\nvar setToStringTag = require('./_set-to-string-tag');\nvar inheritIfRequired = require('./_inherit-if-required');\n\nmodule.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {\n var Base = global[NAME];\n var C = Base;\n var ADDER = IS_MAP ? 'set' : 'add';\n var proto = C && C.prototype;\n var O = {};\n var fixMethod = function (KEY) {\n var fn = proto[KEY];\n redefine(proto, KEY,\n KEY == 'delete' ? function (a) {\n return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);\n } : KEY == 'has' ? function has(a) {\n return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);\n } : KEY == 'get' ? function get(a) {\n return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);\n } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }\n : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }\n );\n };\n if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {\n new C().entries().next();\n }))) {\n // create collection constructor\n C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);\n redefineAll(C.prototype, methods);\n meta.NEED = true;\n } else {\n var instance = new C();\n // early implementations not supports chaining\n var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;\n // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false\n var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });\n // most early implementations doesn't supports iterables, most modern - not close it correctly\n var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new\n // for early implementations -0 and +0 not the same\n var BUGGY_ZERO = !IS_WEAK && fails(function () {\n // V8 ~ Chromium 42- fails only with 5+ elements\n var $instance = new C();\n var index = 5;\n while (index--) $instance[ADDER](index, index);\n return !$instance.has(-0);\n });\n if (!ACCEPT_ITERABLES) {\n C = wrapper(function (target, iterable) {\n anInstance(target, C, NAME);\n var that = inheritIfRequired(new Base(), target, C);\n if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);\n return that;\n });\n C.prototype = proto;\n proto.constructor = C;\n }\n if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {\n fixMethod('delete');\n fixMethod('has');\n IS_MAP && fixMethod('get');\n }\n if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);\n // weak collections should not contains .clear method\n if (IS_WEAK && proto.clear) delete proto.clear;\n }\n\n setToStringTag(C, NAME);\n\n O[NAME] = C;\n $export($export.G + $export.W + $export.F * (C != Base), O);\n\n if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);\n\n return C;\n};\n","var isObject = require('./_is-object');\nvar setPrototypeOf = require('./_set-proto').set;\nmodule.exports = function (that, target, C) {\n var S = target.constructor;\n var P;\n if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {\n setPrototypeOf(that, P);\n } return that;\n};\n","// Works with __proto__ only. Old v8 can't work with null proto objects.\n/* eslint-disable no-proto */\nvar isObject = require('./_is-object');\nvar anObject = require('./_an-object');\nvar check = function (O, proto) {\n anObject(O);\n if (!isObject(proto) && proto !== null) throw TypeError(proto + \": can't set as prototype!\");\n};\nmodule.exports = {\n set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line\n function (test, buggy, set) {\n try {\n set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2);\n set(test, []);\n buggy = !(test instanceof Array);\n } catch (e) { buggy = true; }\n return function setPrototypeOf(O, proto) {\n check(O, proto);\n if (buggy) O.__proto__ = proto;\n else set(O, proto);\n return O;\n };\n }({}, false) : undefined),\n check: check\n};\n","var pIE = require('./_object-pie');\nvar createDesc = require('./_property-desc');\nvar toIObject = require('./_to-iobject');\nvar toPrimitive = require('./_to-primitive');\nvar has = require('./_has');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nexports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) {\n O = toIObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return gOPD(O, P);\n } catch (e) { /* empty */ }\n if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);\n};\n","// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of\nrequire('./_set-collection-of')('WeakMap');\n","'use strict';\n// https://tc39.github.io/proposal-setmap-offrom/\nvar $export = require('./_export');\n\nmodule.exports = function (COLLECTION) {\n $export($export.S, COLLECTION, { of: function of() {\n var length = arguments.length;\n var A = new Array(length);\n while (length--) A[length] = arguments[length];\n return new this(A);\n } });\n};\n","// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from\nrequire('./_set-collection-from')('WeakMap');\n","'use strict';\n// https://tc39.github.io/proposal-setmap-offrom/\nvar $export = require('./_export');\nvar aFunction = require('./_a-function');\nvar ctx = require('./_ctx');\nvar forOf = require('./_for-of');\n\nmodule.exports = function (COLLECTION) {\n $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {\n var mapFn = arguments[1];\n var mapping, A, n, cb;\n aFunction(this);\n mapping = mapFn !== undefined;\n if (mapping) aFunction(mapFn);\n if (source == undefined) return new this();\n A = [];\n if (mapping) {\n n = 0;\n cb = ctx(mapFn, arguments[2], 2);\n forOf(source, false, function (nextItem) {\n A.push(cb(nextItem, n++));\n });\n } else {\n forOf(source, false, A.push, A);\n }\n return new this(A);\n } });\n};\n","require('../modules/es6.object.to-string');\nrequire('../modules/web.dom.iterable');\nrequire('../modules/es6.weak-set');\nrequire('../modules/es7.weak-set.of');\nrequire('../modules/es7.weak-set.from');\nmodule.exports = require('../modules/_core').WeakSet;\n","'use strict';\nvar weak = require('./_collection-weak');\nvar validate = require('./_validate-collection');\nvar WEAK_SET = 'WeakSet';\n\n// 23.4 WeakSet Objects\nrequire('./_collection')(WEAK_SET, function (get) {\n return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };\n}, {\n // 23.4.3.1 WeakSet.prototype.add(value)\n add: function add(value) {\n return weak.def(validate(this, WEAK_SET), value, true);\n }\n}, weak, false, true);\n","// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of\nrequire('./_set-collection-of')('WeakSet');\n","// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from\nrequire('./_set-collection-from')('WeakSet');\n","require('../../modules/es6.string.code-point-at');\nmodule.exports = require('../../modules/_core').String.codePointAt;\n","'use strict';\nvar $export = require('./_export');\nvar $at = require('./_string-at')(false);\n$export($export.P, 'String', {\n // 21.1.3.3 String.prototype.codePointAt(pos)\n codePointAt: function codePointAt(pos) {\n return $at(this, pos);\n }\n});\n","require('../../modules/es6.string.from-code-point');\nmodule.exports = require('../../modules/_core').String.fromCodePoint;\n","var $export = require('./_export');\nvar toAbsoluteIndex = require('./_to-absolute-index');\nvar fromCharCode = String.fromCharCode;\nvar $fromCodePoint = String.fromCodePoint;\n\n// length should be 1, old FF problem\n$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {\n // 21.1.2.2 String.fromCodePoint(...codePoints)\n fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars\n var res = [];\n var aLen = arguments.length;\n var i = 0;\n var code;\n while (aLen > i) {\n code = +arguments[i++];\n if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');\n res.push(code < 0x10000\n ? fromCharCode(code)\n : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)\n );\n } return res.join('');\n }\n});\n","require('../modules/es6.symbol');\nrequire('../modules/es6.object.to-string');\nmodule.exports = require('../modules/_core').Symbol;\n","'use strict';\n// ECMAScript 6 symbols shim\nvar global = require('./_global');\nvar has = require('./_has');\nvar DESCRIPTORS = require('./_descriptors');\nvar $export = require('./_export');\nvar redefine = require('./_redefine');\nvar META = require('./_meta').KEY;\nvar $fails = require('./_fails');\nvar shared = require('./_shared');\nvar setToStringTag = require('./_set-to-string-tag');\nvar uid = require('./_uid');\nvar wks = require('./_wks');\nvar wksExt = require('./_wks-ext');\nvar wksDefine = require('./_wks-define');\nvar enumKeys = require('./_enum-keys');\nvar isArray = require('./_is-array');\nvar anObject = require('./_an-object');\nvar isObject = require('./_is-object');\nvar toObject = require('./_to-object');\nvar toIObject = require('./_to-iobject');\nvar toPrimitive = require('./_to-primitive');\nvar createDesc = require('./_property-desc');\nvar _create = require('./_object-create');\nvar gOPNExt = require('./_object-gopn-ext');\nvar $GOPD = require('./_object-gopd');\nvar $GOPS = require('./_object-gops');\nvar $DP = require('./_object-dp');\nvar $keys = require('./_object-keys');\nvar gOPD = $GOPD.f;\nvar dP = $DP.f;\nvar gOPN = gOPNExt.f;\nvar $Symbol = global.Symbol;\nvar $JSON = global.JSON;\nvar _stringify = $JSON && $JSON.stringify;\nvar PROTOTYPE = 'prototype';\nvar HIDDEN = wks('_hidden');\nvar TO_PRIMITIVE = wks('toPrimitive');\nvar isEnum = {}.propertyIsEnumerable;\nvar SymbolRegistry = shared('symbol-registry');\nvar AllSymbols = shared('symbols');\nvar OPSymbols = shared('op-symbols');\nvar ObjectProto = Object[PROTOTYPE];\nvar USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;\nvar QObject = global.QObject;\n// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173\nvar setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;\n\n// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687\nvar setSymbolDesc = DESCRIPTORS && $fails(function () {\n return _create(dP({}, 'a', {\n get: function () { return dP(this, 'a', { value: 7 }).a; }\n })).a != 7;\n}) ? function (it, key, D) {\n var protoDesc = gOPD(ObjectProto, key);\n if (protoDesc) delete ObjectProto[key];\n dP(it, key, D);\n if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);\n} : dP;\n\nvar wrap = function (tag) {\n var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);\n sym._k = tag;\n return sym;\n};\n\nvar isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {\n return typeof it == 'symbol';\n} : function (it) {\n return it instanceof $Symbol;\n};\n\nvar $defineProperty = function defineProperty(it, key, D) {\n if (it === ObjectProto) $defineProperty(OPSymbols, key, D);\n anObject(it);\n key = toPrimitive(key, true);\n anObject(D);\n if (has(AllSymbols, key)) {\n if (!D.enumerable) {\n if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));\n it[HIDDEN][key] = true;\n } else {\n if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;\n D = _create(D, { enumerable: createDesc(0, false) });\n } return setSymbolDesc(it, key, D);\n } return dP(it, key, D);\n};\nvar $defineProperties = function defineProperties(it, P) {\n anObject(it);\n var keys = enumKeys(P = toIObject(P));\n var i = 0;\n var l = keys.length;\n var key;\n while (l > i) $defineProperty(it, key = keys[i++], P[key]);\n return it;\n};\nvar $create = function create(it, P) {\n return P === undefined ? _create(it) : $defineProperties(_create(it), P);\n};\nvar $propertyIsEnumerable = function propertyIsEnumerable(key) {\n var E = isEnum.call(this, key = toPrimitive(key, true));\n if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;\n return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;\n};\nvar $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {\n it = toIObject(it);\n key = toPrimitive(key, true);\n if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;\n var D = gOPD(it, key);\n if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;\n return D;\n};\nvar $getOwnPropertyNames = function getOwnPropertyNames(it) {\n var names = gOPN(toIObject(it));\n var result = [];\n var i = 0;\n var key;\n while (names.length > i) {\n if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);\n } return result;\n};\nvar $getOwnPropertySymbols = function getOwnPropertySymbols(it) {\n var IS_OP = it === ObjectProto;\n var names = gOPN(IS_OP ? OPSymbols : toIObject(it));\n var result = [];\n var i = 0;\n var key;\n while (names.length > i) {\n if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);\n } return result;\n};\n\n// 19.4.1.1 Symbol([description])\nif (!USE_NATIVE) {\n $Symbol = function Symbol() {\n if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');\n var tag = uid(arguments.length > 0 ? arguments[0] : undefined);\n var $set = function (value) {\n if (this === ObjectProto) $set.call(OPSymbols, value);\n if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;\n setSymbolDesc(this, tag, createDesc(1, value));\n };\n if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });\n return wrap(tag);\n };\n redefine($Symbol[PROTOTYPE], 'toString', function toString() {\n return this._k;\n });\n\n $GOPD.f = $getOwnPropertyDescriptor;\n $DP.f = $defineProperty;\n require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;\n require('./_object-pie').f = $propertyIsEnumerable;\n $GOPS.f = $getOwnPropertySymbols;\n\n if (DESCRIPTORS && !require('./_library')) {\n redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);\n }\n\n wksExt.f = function (name) {\n return wrap(wks(name));\n };\n}\n\n$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });\n\nfor (var es6Symbols = (\n // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14\n 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'\n).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);\n\nfor (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);\n\n$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {\n // 19.4.2.1 Symbol.for(key)\n 'for': function (key) {\n return has(SymbolRegistry, key += '')\n ? SymbolRegistry[key]\n : SymbolRegistry[key] = $Symbol(key);\n },\n // 19.4.2.5 Symbol.keyFor(sym)\n keyFor: function keyFor(sym) {\n if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');\n for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;\n },\n useSetter: function () { setter = true; },\n useSimple: function () { setter = false; }\n});\n\n$export($export.S + $export.F * !USE_NATIVE, 'Object', {\n // 19.1.2.2 Object.create(O [, Properties])\n create: $create,\n // 19.1.2.4 Object.defineProperty(O, P, Attributes)\n defineProperty: $defineProperty,\n // 19.1.2.3 Object.defineProperties(O, Properties)\n defineProperties: $defineProperties,\n // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)\n getOwnPropertyDescriptor: $getOwnPropertyDescriptor,\n // 19.1.2.7 Object.getOwnPropertyNames(O)\n getOwnPropertyNames: $getOwnPropertyNames,\n // 19.1.2.8 Object.getOwnPropertySymbols(O)\n getOwnPropertySymbols: $getOwnPropertySymbols\n});\n\n// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives\n// https://bugs.chromium.org/p/v8/issues/detail?id=3443\nvar FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });\n\n$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {\n getOwnPropertySymbols: function getOwnPropertySymbols(it) {\n return $GOPS.f(toObject(it));\n }\n});\n\n// 24.3.2 JSON.stringify(value [, replacer [, space]])\n$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {\n var S = $Symbol();\n // MS Edge converts symbol values to JSON as {}\n // WebKit converts symbol values to JSON as null\n // V8 throws on boxed symbols\n return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';\n})), 'JSON', {\n stringify: function stringify(it) {\n var args = [it];\n var i = 1;\n var replacer, $replacer;\n while (arguments.length > i) args.push(arguments[i++]);\n $replacer = replacer = args[1];\n if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined\n if (!isArray(replacer)) replacer = function (key, value) {\n if (typeof $replacer == 'function') value = $replacer.call(this, key, value);\n if (!isSymbol(value)) return value;\n };\n args[1] = replacer;\n return _stringify.apply($JSON, args);\n }\n});\n\n// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)\n$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);\n// 19.4.3.5 Symbol.prototype[@@toStringTag]\nsetToStringTag($Symbol, 'Symbol');\n// 20.2.1.9 Math[@@toStringTag]\nsetToStringTag(Math, 'Math', true);\n// 24.3.3 JSON[@@toStringTag]\nsetToStringTag(global.JSON, 'JSON', true);\n","exports.f = require('./_wks');\n","var global = require('./_global');\nvar core = require('./_core');\nvar LIBRARY = require('./_library');\nvar wksExt = require('./_wks-ext');\nvar defineProperty = require('./_object-dp').f;\nmodule.exports = function (name) {\n var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});\n if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });\n};\n","// all enumerable object keys, includes symbols\nvar getKeys = require('./_object-keys');\nvar gOPS = require('./_object-gops');\nvar pIE = require('./_object-pie');\nmodule.exports = function (it) {\n var result = getKeys(it);\n var getSymbols = gOPS.f;\n if (getSymbols) {\n var symbols = getSymbols(it);\n var isEnum = pIE.f;\n var i = 0;\n var key;\n while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);\n } return result;\n};\n","// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window\nvar toIObject = require('./_to-iobject');\nvar gOPN = require('./_object-gopn').f;\nvar toString = {}.toString;\n\nvar windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames\n ? Object.getOwnPropertyNames(window) : [];\n\nvar getWindowNames = function (it) {\n try {\n return gOPN(it);\n } catch (e) {\n return windowNames.slice();\n }\n};\n\nmodule.exports.f = function getOwnPropertyNames(it) {\n return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));\n};\n","// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)\nvar $keys = require('./_object-keys-internal');\nvar hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');\n\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return $keys(O, hiddenKeys);\n};\n","require('../../modules/es7.string.pad-start');\nmodule.exports = require('../../modules/_core').String.padStart;\n","'use strict';\n// https://github.com/tc39/proposal-string-pad-start-end\nvar $export = require('./_export');\nvar $pad = require('./_string-pad');\nvar userAgent = require('./_user-agent');\n\n// https://github.com/zloirock/core-js/issues/280\nvar WEBKIT_BUG = /Version\\/10\\.\\d+(\\.\\d+)?( Mobile\\/\\w+)? Safari\\//.test(userAgent);\n\n$export($export.P + $export.F * WEBKIT_BUG, 'String', {\n padStart: function padStart(maxLength /* , fillString = ' ' */) {\n return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);\n }\n});\n","// https://github.com/tc39/proposal-string-pad-start-end\nvar toLength = require('./_to-length');\nvar repeat = require('./_string-repeat');\nvar defined = require('./_defined');\n\nmodule.exports = function (that, maxLength, fillString, left) {\n var S = String(defined(that));\n var stringLength = S.length;\n var fillStr = fillString === undefined ? ' ' : String(fillString);\n var intMaxLength = toLength(maxLength);\n if (intMaxLength <= stringLength || fillStr == '') return S;\n var fillLen = intMaxLength - stringLength;\n var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));\n if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);\n return left ? stringFiller + S : S + stringFiller;\n};\n","'use strict';\nvar toInteger = require('./_to-integer');\nvar defined = require('./_defined');\n\nmodule.exports = function repeat(count) {\n var str = String(defined(this));\n var res = '';\n var n = toInteger(count);\n if (n < 0 || n == Infinity) throw RangeError(\"Count can't be negative\");\n for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;\n return res;\n};\n","require('../../modules/es7.string.pad-end');\nmodule.exports = require('../../modules/_core').String.padEnd;\n","'use strict';\n// https://github.com/tc39/proposal-string-pad-start-end\nvar $export = require('./_export');\nvar $pad = require('./_string-pad');\nvar userAgent = require('./_user-agent');\n\n// https://github.com/zloirock/core-js/issues/280\nvar WEBKIT_BUG = /Version\\/10\\.\\d+(\\.\\d+)?( Mobile\\/\\w+)? Safari\\//.test(userAgent);\n\n$export($export.P + $export.F * WEBKIT_BUG, 'String', {\n padEnd: function padEnd(maxLength /* , fillString = ' ' */) {\n return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);\n }\n});\n","require('../../modules/es7.object.values');\nmodule.exports = require('../../modules/_core').Object.values;\n","// https://github.com/tc39/proposal-object-values-entries\nvar $export = require('./_export');\nvar $values = require('./_object-to-array')(false);\n\n$export($export.S, 'Object', {\n values: function values(it) {\n return $values(it);\n }\n});\n","var DESCRIPTORS = require('./_descriptors');\nvar getKeys = require('./_object-keys');\nvar toIObject = require('./_to-iobject');\nvar isEnum = require('./_object-pie').f;\nmodule.exports = function (isEntries) {\n return function (it) {\n var O = toIObject(it);\n var keys = getKeys(O);\n var length = keys.length;\n var i = 0;\n var result = [];\n var key;\n while (length > i) {\n key = keys[i++];\n if (!DESCRIPTORS || isEnum.call(O, key)) {\n result.push(isEntries ? [key, O[key]] : O[key]);\n }\n }\n return result;\n };\n};\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* eslint-disable no-restricted-globals */\n\nif (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('MOZCENTRAL')) {\n if (typeof ReadableStream === 'undefined') {\n throw new Error('Please enable ReadableStream support by resetting the ' +\n '\"javascript.options.streams\" preference to \"true\" in about:config.');\n }\n exports.ReadableStream = ReadableStream;\n} else {\n let isReadableStreamSupported = false;\n if (typeof ReadableStream !== 'undefined') {\n // MS Edge may say it has ReadableStream but they are not up to spec yet.\n try {\n // eslint-disable-next-line no-new\n new ReadableStream({\n start(controller) {\n controller.close();\n },\n });\n isReadableStreamSupported = true;\n } catch (e) {\n // The ReadableStream constructor cannot be used.\n }\n }\n if (isReadableStreamSupported) {\n exports.ReadableStream = ReadableStream;\n } else if (typeof PDFJSDev !== 'undefined' &&\n PDFJSDev.test('IMAGE_DECODERS')) {\n class DummyReadableStream {\n constructor() {\n throw new Error('The current image decoders are synchronous, ' +\n 'hence `ReadableStream` shouldn\\'t need to be ' +\n 'polyfilled for the IMAGE_DECODERS build target.');\n }\n }\n exports.ReadableStream = DummyReadableStream;\n } else {\n exports.ReadableStream =\n require('../../external/streams/streams-lib').ReadableStream;\n }\n}\n","/*\n * To the extent possible under law, the authors have dedicated all copyright\n * and related and neighboring rights to this software to the public\n * domain worldwide. This software is distributed without any warranty.\n *\n * You should have received a copy of the CC0 Public Domain Dedication along\n * with this software. If not, see https://creativecommons.org/publicdomain/zero/1.0/.\n */\n\n(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap\n/******/ // The module cache\n/******/ var installedModules = {};\n/******/\n/******/ // The require function\n/******/ function __w_pdfjs_require__(moduleId) {\n/******/\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId])\n/******/ return installedModules[moduleId].exports;\n/******/\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n/******/\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__);\n/******/\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n/******/\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n/******/\n/******/\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __w_pdfjs_require__.m = modules;\n/******/\n/******/ // expose the module cache\n/******/ __w_pdfjs_require__.c = installedModules;\n/******/\n/******/ // identity function for calling harmony imports with the correct context\n/******/ __w_pdfjs_require__.i = function(value) { return value; };\n/******/\n/******/ // define getter function for harmony exports\n/******/ __w_pdfjs_require__.d = function(exports, name, getter) {\n/******/ if(!__w_pdfjs_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, {\n/******/ configurable: false,\n/******/ enumerable: true,\n/******/ get: getter\n/******/ });\n/******/ }\n/******/ };\n/******/\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __w_pdfjs_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __w_pdfjs_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n/******/\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __w_pdfjs_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ // __webpack_public_path__\n/******/ __w_pdfjs_require__.p = \"\";\n/******/\n/******/ // Load entry module and return exports\n/******/ return __w_pdfjs_require__(__w_pdfjs_require__.s = 7);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar _require = __w_pdfjs_require__(1),\n assert = _require.assert;\n\nfunction IsPropertyKey(argument) {\n return typeof argument === 'string' || (typeof argument === 'undefined' ? 'undefined' : _typeof(argument)) === 'symbol';\n}\n\nexports.typeIsObject = function (x) {\n return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x !== null || typeof x === 'function';\n};\n\nexports.createDataProperty = function (o, p, v) {\n assert(exports.typeIsObject(o));\n Object.defineProperty(o, p, { value: v, writable: true, enumerable: true, configurable: true });\n};\n\nexports.createArrayFromList = function (elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n};\n\nexports.ArrayBufferCopy = function (dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n};\n\nexports.CreateIterResultObject = function (value, done) {\n assert(typeof done === 'boolean');\n var obj = {};\n Object.defineProperty(obj, 'value', { value: value, enumerable: true, writable: true, configurable: true });\n Object.defineProperty(obj, 'done', { value: done, enumerable: true, writable: true, configurable: true });\n return obj;\n};\n\nexports.IsFiniteNonNegativeNumber = function (v) {\n if (Number.isNaN(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n\n return true;\n};\n\nfunction Call(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n\n return Function.prototype.apply.call(F, V, args);\n}\n\nexports.InvokeOrNoop = function (O, P, args) {\n assert(O !== undefined);\n assert(IsPropertyKey(P));\n assert(Array.isArray(args));\n\n var method = O[P];\n if (method === undefined) {\n return undefined;\n }\n\n return Call(method, O, args);\n};\n\nexports.PromiseInvokeOrNoop = function (O, P, args) {\n assert(O !== undefined);\n assert(IsPropertyKey(P));\n assert(Array.isArray(args));\n try {\n return Promise.resolve(exports.InvokeOrNoop(O, P, args));\n } catch (returnValueE) {\n return Promise.reject(returnValueE);\n }\n};\n\nexports.PromiseInvokeOrPerformFallback = function (O, P, args, F, argsF) {\n assert(O !== undefined);\n assert(IsPropertyKey(P));\n assert(Array.isArray(args));\n assert(Array.isArray(argsF));\n\n var method = void 0;\n try {\n method = O[P];\n } catch (methodE) {\n return Promise.reject(methodE);\n }\n\n if (method === undefined) {\n return F.apply(null, argsF);\n }\n\n try {\n return Promise.resolve(Call(method, O, args));\n } catch (e) {\n return Promise.reject(e);\n }\n};\n\n// Not implemented correctly\nexports.TransferArrayBuffer = function (O) {\n return O.slice();\n};\n\nexports.ValidateAndNormalizeHighWaterMark = function (highWaterMark) {\n highWaterMark = Number(highWaterMark);\n if (Number.isNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('highWaterMark property of a queuing strategy must be non-negative and non-NaN');\n }\n\n return highWaterMark;\n};\n\nexports.ValidateAndNormalizeQueuingStrategy = function (size, highWaterMark) {\n if (size !== undefined && typeof size !== 'function') {\n throw new TypeError('size property of a queuing strategy must be a function');\n }\n\n highWaterMark = exports.ValidateAndNormalizeHighWaterMark(highWaterMark);\n\n return { size: size, highWaterMark: highWaterMark };\n};\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nfunction rethrowAssertionErrorRejection(e) {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e.constructor === AssertionError) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n};\n\nfunction AssertionError(message) {\n this.name = 'AssertionError';\n this.message = message || '';\n this.stack = new Error().stack;\n}\nAssertionError.prototype = Object.create(Error.prototype);\nAssertionError.prototype.constructor = AssertionError;\n\nfunction assert(value, message) {\n if (!value) {\n throw new AssertionError(message);\n }\n}\n\nmodule.exports = {\n rethrowAssertionErrorRejection: rethrowAssertionErrorRejection,\n AssertionError: AssertionError,\n assert: assert\n};\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar _require = __w_pdfjs_require__(0),\n InvokeOrNoop = _require.InvokeOrNoop,\n PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop,\n ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy,\n typeIsObject = _require.typeIsObject;\n\nvar _require2 = __w_pdfjs_require__(1),\n assert = _require2.assert,\n rethrowAssertionErrorRejection = _require2.rethrowAssertionErrorRejection;\n\nvar _require3 = __w_pdfjs_require__(3),\n DequeueValue = _require3.DequeueValue,\n EnqueueValueWithSize = _require3.EnqueueValueWithSize,\n PeekQueueValue = _require3.PeekQueueValue,\n ResetQueue = _require3.ResetQueue;\n\nvar WritableStream = function () {\n function WritableStream() {\n var underlyingSink = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n size = _ref.size,\n _ref$highWaterMark = _ref.highWaterMark,\n highWaterMark = _ref$highWaterMark === undefined ? 1 : _ref$highWaterMark;\n\n _classCallCheck(this, WritableStream);\n\n this._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n this._storedError = undefined;\n\n this._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n this._writableStreamController = undefined;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n this._writeRequests = [];\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n this._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n this._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n this._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n this._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n this._backpressure = false;\n\n var type = underlyingSink.type;\n\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n this._writableStreamController = new WritableStreamDefaultController(this, underlyingSink, size, highWaterMark);\n this._writableStreamController.__startSteps();\n }\n\n _createClass(WritableStream, [{\n key: 'abort',\n value: function abort(reason) {\n if (IsWritableStream(this) === false) {\n return Promise.reject(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this) === true) {\n return Promise.reject(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n }, {\n key: 'getWriter',\n value: function getWriter() {\n if (IsWritableStream(this) === false) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n }, {\n key: 'locked',\n get: function get() {\n if (IsWritableStream(this) === false) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n }]);\n\n return WritableStream;\n}();\n\nmodule.exports = {\n AcquireWritableStreamDefaultWriter: AcquireWritableStreamDefaultWriter,\n IsWritableStream: IsWritableStream,\n IsWritableStreamLocked: IsWritableStreamLocked,\n WritableStream: WritableStream,\n WritableStreamAbort: WritableStreamAbort,\n WritableStreamDefaultControllerError: WritableStreamDefaultControllerError,\n WritableStreamDefaultWriterCloseWithErrorPropagation: WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease: WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite: WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight: WritableStreamCloseQueuedOrInFlight\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return true;\n}\n\nfunction IsWritableStreamLocked(stream) {\n assert(IsWritableStream(stream) === true, 'IsWritableStreamLocked should only be used on known writable streams');\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream, reason) {\n var state = stream._state;\n if (state === 'closed') {\n return Promise.resolve(undefined);\n }\n if (state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n var error = new TypeError('Requested to abort');\n if (stream._pendingAbortRequest !== undefined) {\n return Promise.reject(error);\n }\n\n assert(state === 'writable' || state === 'erroring', 'state must be writable or erroring');\n\n var wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n var promise = new Promise(function (resolve, reject) {\n stream._pendingAbortRequest = {\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n\n if (wasAlreadyErroring === false) {\n WritableStreamStartErroring(stream, error);\n }\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream) {\n assert(IsWritableStreamLocked(stream) === true);\n assert(stream._state === 'writable');\n\n var promise = new Promise(function (resolve, reject) {\n var writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream, error) {\n var state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream, reason) {\n assert(stream._storedError === undefined, 'stream._storedError === undefined');\n assert(stream._state === 'writable', 'state must be writable');\n\n var controller = stream._writableStreamController;\n assert(controller !== undefined, 'controller must not be undefined');\n\n stream._state = 'erroring';\n stream._storedError = reason;\n var writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (WritableStreamHasOperationMarkedInFlight(stream) === false && controller._started === true) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream) {\n assert(stream._state === 'erroring', 'stream._state === erroring');\n assert(WritableStreamHasOperationMarkedInFlight(stream) === false, 'WritableStreamHasOperationMarkedInFlight(stream) === false');\n stream._state = 'errored';\n stream._writableStreamController.__errorSteps();\n\n var storedError = stream._storedError;\n for (var i = 0; i < stream._writeRequests.length; i++) {\n var writeRequest = stream._writeRequests[i];\n writeRequest._reject(storedError);\n }\n stream._writeRequests = [];\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n var abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring === true) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n var promise = stream._writableStreamController.__abortSteps(abortRequest._reason);\n promise.then(function () {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, function (reason) {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n var state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n var writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined, 'stream._pendingAbortRequest === undefined');\n assert(stream._storedError === undefined, 'stream._storedError === undefined');\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n assert(stream._inFlightWriteRequest === undefined, 'there must be no pending write request');\n assert(stream._writeRequests.length !== 0, 'writeRequests must not be empty');\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n assert(stream._state === 'errored', '_stream_.[[state]] is `\"errored\"`');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n var writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n writer._closedPromise.catch(function () {});\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n assert(stream._state === 'writable');\n assert(WritableStreamCloseQueuedOrInFlight(stream) === false);\n\n var writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure === true) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(backpressure === false);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\nvar WritableStreamDefaultWriter = function () {\n function WritableStreamDefaultWriter(stream) {\n _classCallCheck(this, WritableStreamDefaultWriter);\n\n if (IsWritableStream(stream) === false) {\n throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance');\n }\n if (IsWritableStreamLocked(stream) === true) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n var state = stream._state;\n\n if (state === 'writable') {\n if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._backpressure === true) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n this._readyPromise.catch(function () {});\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored', 'state must be errored');\n\n var storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n this._readyPromise.catch(function () {});\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n this._closedPromise.catch(function () {});\n }\n }\n\n _createClass(WritableStreamDefaultWriter, [{\n key: 'abort',\n value: function abort(reason) {\n if (IsWritableStreamDefaultWriter(this) === false) {\n return Promise.reject(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return Promise.reject(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n }, {\n key: 'close',\n value: function close() {\n if (IsWritableStreamDefaultWriter(this) === false) {\n return Promise.reject(defaultWriterBrandCheckException('close'));\n }\n\n var stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return Promise.reject(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream) === true) {\n return Promise.reject(new TypeError('cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n }, {\n key: 'releaseLock',\n value: function releaseLock() {\n if (IsWritableStreamDefaultWriter(this) === false) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n var stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n }, {\n key: 'write',\n value: function write(chunk) {\n if (IsWritableStreamDefaultWriter(this) === false) {\n return Promise.reject(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return Promise.reject(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n }, {\n key: 'closed',\n get: function get() {\n if (IsWritableStreamDefaultWriter(this) === false) {\n return Promise.reject(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n }, {\n key: 'desiredSize',\n get: function get() {\n if (IsWritableStreamDefaultWriter(this) === false) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n }, {\n key: 'ready',\n get: function get() {\n if (IsWritableStreamDefaultWriter(this) === false) {\n return Promise.reject(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n }]);\n\n return WritableStreamDefaultWriter;\n}();\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return true;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n var stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer) {\n var stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n var state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return Promise.reject(new TypeError('The stream (in ' + state + ' state) is not in the writable state and cannot be closed'));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(WritableStreamCloseQueuedOrInFlight(stream) === false);\n\n var promise = new Promise(function (resolve, reject) {\n var closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n if (stream._backpressure === true && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n var stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n var state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {\n return Promise.resolve();\n }\n\n if (state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n writer._closedPromise.catch(function () {});\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n writer._readyPromise.catch(function () {});\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n var stream = writer._ownerWritableStream;\n var state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer) {\n var stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n var releasedError = new TypeError('Writer was released and can no longer be used to monitor the stream\\'s closedness');\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n var stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n var controller = stream._writableStreamController;\n\n var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return Promise.reject(defaultWriterLockException('write to'));\n }\n\n var state = stream._state;\n if (state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {\n return Promise.reject(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return Promise.reject(stream._storedError);\n }\n\n assert(state === 'writable');\n\n var promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nvar WritableStreamDefaultController = function () {\n function WritableStreamDefaultController(stream, underlyingSink, size, highWaterMark) {\n _classCallCheck(this, WritableStreamDefaultController);\n\n if (IsWritableStream(stream) === false) {\n throw new TypeError('WritableStreamDefaultController can only be constructed with a WritableStream instance');\n }\n\n if (stream._writableStreamController !== undefined) {\n throw new TypeError('WritableStreamDefaultController instances can only be created by the WritableStream constructor');\n }\n\n this._controlledWritableStream = stream;\n\n this._underlyingSink = underlyingSink;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n this._queue = undefined;\n this._queueTotalSize = undefined;\n ResetQueue(this);\n\n this._started = false;\n\n var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);\n this._strategySize = normalizedStrategy.size;\n this._strategyHWM = normalizedStrategy.highWaterMark;\n\n var backpressure = WritableStreamDefaultControllerGetBackpressure(this);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n _createClass(WritableStreamDefaultController, [{\n key: 'error',\n value: function error(e) {\n if (IsWritableStreamDefaultController(this) === false) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n var state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n }, {\n key: '__abortSteps',\n value: function __abortSteps(reason) {\n return PromiseInvokeOrNoop(this._underlyingSink, 'abort', [reason]);\n }\n }, {\n key: '__errorSteps',\n value: function __errorSteps() {\n ResetQueue(this);\n }\n }, {\n key: '__startSteps',\n value: function __startSteps() {\n var _this = this;\n\n var startResult = InvokeOrNoop(this._underlyingSink, 'start', [this]);\n var stream = this._controlledWritableStream;\n\n Promise.resolve(startResult).then(function () {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n _this._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(_this);\n }, function (r) {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n _this._started = true;\n WritableStreamDealWithRejection(stream, r);\n }).catch(rethrowAssertionErrorRejection);\n }\n }]);\n\n return WritableStreamDefaultController;\n}();\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, 'close', 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n var strategySize = controller._strategySize;\n\n if (strategySize === undefined) {\n return 1;\n }\n\n try {\n return strategySize(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n var writeRecord = { chunk: chunk };\n\n try {\n EnqueueValueWithSize(controller, writeRecord, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n var stream = controller._controlledWritableStream;\n if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') {\n var backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSink')) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n var stream = controller._controlledWritableStream;\n\n if (controller._started === false) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n var state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return;\n }\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n var writeRecord = PeekQueueValue(controller);\n if (writeRecord === 'close') {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n var stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0, 'queue must be empty once the final write record is dequeued');\n\n var sinkClosePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'close', []);\n sinkClosePromise.then(function () {\n WritableStreamFinishInFlightClose(stream);\n }, function (reason) {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }).catch(rethrowAssertionErrorRejection);\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n var stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n var sinkWritePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'write', [chunk, controller]);\n sinkWritePromise.then(function () {\n WritableStreamFinishInFlightWrite(stream);\n\n var state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') {\n var backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, function (reason) {\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }).catch(rethrowAssertionErrorRejection);\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller, error) {\n var stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name) {\n return new TypeError('WritableStream.prototype.' + name + ' can only be used on a WritableStream');\n}\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError('WritableStreamDefaultWriter.prototype.' + name + ' can only be used on a WritableStreamDefaultWriter');\n}\n\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = new Promise(function (resolve, reject) {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n writer._closedPromise = Promise.reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n writer._closedPromise = Promise.resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined');\n assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined');\n assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending');\n\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n assert(writer._closedPromise_resolve === undefined, 'writer._closedPromise_resolve === undefined');\n assert(writer._closedPromise_reject === undefined, 'writer._closedPromise_reject === undefined');\n assert(writer._closedPromiseState !== 'pending', 'writer._closedPromiseState is not pending');\n\n writer._closedPromise = Promise.reject(reason);\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResolve(writer) {\n assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined');\n assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined');\n assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = new Promise(function (resolve, reject) {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n writer._readyPromise = Promise.reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n writer._readyPromise = Promise.resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined');\n assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined');\n\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer) {\n assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined');\n assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined');\n\n writer._readyPromise = new Promise(function (resolve, reject) {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined');\n assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined');\n\n writer._readyPromise = Promise.reject(reason);\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseResolve(writer) {\n assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined');\n assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined');\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar _require = __w_pdfjs_require__(0),\n IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber;\n\nvar _require2 = __w_pdfjs_require__(1),\n assert = _require2.assert;\n\nexports.DequeueValue = function (container) {\n assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]].');\n assert(container._queue.length > 0, 'Spec-level failure: should never dequeue from an empty queue.');\n\n var pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n};\n\nexports.EnqueueValueWithSize = function (container, value, size) {\n assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and ' + '[[queueTotalSize]].');\n\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value: value, size: size });\n container._queueTotalSize += size;\n};\n\nexports.PeekQueueValue = function (container) {\n assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]].');\n assert(container._queue.length > 0, 'Spec-level failure: should never peek at an empty queue.');\n\n var pair = container._queue[0];\n return pair.value;\n};\n\nexports.ResetQueue = function (container) {\n assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]].');\n\n container._queue = [];\n container._queueTotalSize = 0;\n};\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar _require = __w_pdfjs_require__(0),\n ArrayBufferCopy = _require.ArrayBufferCopy,\n CreateIterResultObject = _require.CreateIterResultObject,\n IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber,\n InvokeOrNoop = _require.InvokeOrNoop,\n PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop,\n TransferArrayBuffer = _require.TransferArrayBuffer,\n ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy,\n ValidateAndNormalizeHighWaterMark = _require.ValidateAndNormalizeHighWaterMark;\n\nvar _require2 = __w_pdfjs_require__(0),\n createArrayFromList = _require2.createArrayFromList,\n createDataProperty = _require2.createDataProperty,\n typeIsObject = _require2.typeIsObject;\n\nvar _require3 = __w_pdfjs_require__(1),\n assert = _require3.assert,\n rethrowAssertionErrorRejection = _require3.rethrowAssertionErrorRejection;\n\nvar _require4 = __w_pdfjs_require__(3),\n DequeueValue = _require4.DequeueValue,\n EnqueueValueWithSize = _require4.EnqueueValueWithSize,\n ResetQueue = _require4.ResetQueue;\n\nvar _require5 = __w_pdfjs_require__(2),\n AcquireWritableStreamDefaultWriter = _require5.AcquireWritableStreamDefaultWriter,\n IsWritableStream = _require5.IsWritableStream,\n IsWritableStreamLocked = _require5.IsWritableStreamLocked,\n WritableStreamAbort = _require5.WritableStreamAbort,\n WritableStreamDefaultWriterCloseWithErrorPropagation = _require5.WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease = _require5.WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite = _require5.WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight = _require5.WritableStreamCloseQueuedOrInFlight;\n\nvar ReadableStream = function () {\n function ReadableStream() {\n var underlyingSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n size = _ref.size,\n highWaterMark = _ref.highWaterMark;\n\n _classCallCheck(this, ReadableStream);\n\n // Exposed to controllers.\n this._state = 'readable';\n\n this._reader = undefined;\n this._storedError = undefined;\n\n this._disturbed = false;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n this._readableStreamController = undefined;\n var type = underlyingSource.type;\n var typeString = String(type);\n if (typeString === 'bytes') {\n if (highWaterMark === undefined) {\n highWaterMark = 0;\n }\n this._readableStreamController = new ReadableByteStreamController(this, underlyingSource, highWaterMark);\n } else if (type === undefined) {\n if (highWaterMark === undefined) {\n highWaterMark = 1;\n }\n this._readableStreamController = new ReadableStreamDefaultController(this, underlyingSource, size, highWaterMark);\n } else {\n throw new RangeError('Invalid type is specified');\n }\n }\n\n _createClass(ReadableStream, [{\n key: 'cancel',\n value: function cancel(reason) {\n if (IsReadableStream(this) === false) {\n return Promise.reject(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this) === true) {\n return Promise.reject(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n }, {\n key: 'getReader',\n value: function getReader() {\n var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n mode = _ref2.mode;\n\n if (IsReadableStream(this) === false) {\n throw streamBrandCheckException('getReader');\n }\n\n if (mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n mode = String(mode);\n\n if (mode === 'byob') {\n return AcquireReadableStreamBYOBReader(this);\n }\n\n throw new RangeError('Invalid mode is specified');\n }\n }, {\n key: 'pipeThrough',\n value: function pipeThrough(_ref3, options) {\n var writable = _ref3.writable,\n readable = _ref3.readable;\n\n var promise = this.pipeTo(writable, options);\n\n ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);\n\n return readable;\n }\n }, {\n key: 'pipeTo',\n value: function pipeTo(dest) {\n var _this = this;\n\n var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n preventClose = _ref4.preventClose,\n preventAbort = _ref4.preventAbort,\n preventCancel = _ref4.preventCancel;\n\n if (IsReadableStream(this) === false) {\n return Promise.reject(streamBrandCheckException('pipeTo'));\n }\n if (IsWritableStream(dest) === false) {\n return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo\\'s first argument must be a WritableStream'));\n }\n\n preventClose = Boolean(preventClose);\n preventAbort = Boolean(preventAbort);\n preventCancel = Boolean(preventCancel);\n\n if (IsReadableStreamLocked(this) === true) {\n return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(dest) === true) {\n return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n\n var reader = AcquireReadableStreamDefaultReader(this);\n var writer = AcquireWritableStreamDefaultWriter(dest);\n\n var shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n var currentWrite = Promise.resolve();\n\n return new Promise(function (resolve, reject) {\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n currentWrite = Promise.resolve();\n\n if (shuttingDown === true) {\n return Promise.resolve();\n }\n\n return writer._readyPromise.then(function () {\n return ReadableStreamDefaultReaderRead(reader).then(function (_ref5) {\n var value = _ref5.value,\n done = _ref5.done;\n\n if (done === true) {\n return;\n }\n\n currentWrite = WritableStreamDefaultWriterWrite(writer, value).catch(function () {});\n });\n }).then(pipeLoop);\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(_this, reader._closedPromise, function (storedError) {\n if (preventAbort === false) {\n shutdownWithAction(function () {\n return WritableStreamAbort(dest, storedError);\n }, true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, function (storedError) {\n if (preventCancel === false) {\n shutdownWithAction(function () {\n return ReadableStreamCancel(_this, storedError);\n }, true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(_this, reader._closedPromise, function () {\n if (preventClose === false) {\n shutdownWithAction(function () {\n return WritableStreamDefaultWriterCloseWithErrorPropagation(writer);\n });\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') {\n var destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (preventCancel === false) {\n shutdownWithAction(function () {\n return ReadableStreamCancel(_this, destClosed);\n }, true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n pipeLoop().catch(function (err) {\n currentWrite = Promise.resolve();\n rethrowAssertionErrorRejection(err);\n });\n\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n var oldCurrentWrite = currentWrite;\n return currentWrite.then(function () {\n return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined;\n });\n }\n\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n promise.catch(action).catch(rethrowAssertionErrorRejection);\n }\n }\n\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n } else {\n promise.then(action).catch(rethrowAssertionErrorRejection);\n }\n }\n\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown === true) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {\n waitForWritesToFinish().then(doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n action().then(function () {\n return finalize(originalIsError, originalError);\n }, function (newError) {\n return finalize(true, newError);\n }).catch(rethrowAssertionErrorRejection);\n }\n }\n\n function shutdown(isError, error) {\n if (shuttingDown === true) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {\n waitForWritesToFinish().then(function () {\n return finalize(isError, error);\n }).catch(rethrowAssertionErrorRejection);\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n }\n }, {\n key: 'tee',\n value: function tee() {\n if (IsReadableStream(this) === false) {\n throw streamBrandCheckException('tee');\n }\n\n var branches = ReadableStreamTee(this, false);\n return createArrayFromList(branches);\n }\n }, {\n key: 'locked',\n get: function get() {\n if (IsReadableStream(this) === false) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n }]);\n\n return ReadableStream;\n}();\n\nmodule.exports = {\n ReadableStream: ReadableStream,\n IsReadableStreamDisturbed: IsReadableStreamDisturbed,\n ReadableStreamDefaultControllerClose: ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue: ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError: ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize: ReadableStreamDefaultControllerGetDesiredSize\n};\n\n// Abstract operations for the ReadableStream.\n\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return true;\n}\n\nfunction IsReadableStreamDisturbed(stream) {\n assert(IsReadableStream(stream) === true, 'IsReadableStreamDisturbed should only be used on known readable streams');\n\n return stream._disturbed;\n}\n\nfunction IsReadableStreamLocked(stream) {\n assert(IsReadableStream(stream) === true, 'IsReadableStreamLocked should only be used on known readable streams');\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n assert(IsReadableStream(stream) === true);\n assert(typeof cloneForBranch2 === 'boolean');\n\n var reader = AcquireReadableStreamDefaultReader(stream);\n\n var teeState = {\n closedOrErrored: false,\n canceled1: false,\n canceled2: false,\n reason1: undefined,\n reason2: undefined\n };\n teeState.promise = new Promise(function (resolve) {\n teeState._resolve = resolve;\n });\n\n var pull = create_ReadableStreamTeePullFunction();\n pull._reader = reader;\n pull._teeState = teeState;\n pull._cloneForBranch2 = cloneForBranch2;\n\n var cancel1 = create_ReadableStreamTeeBranch1CancelFunction();\n cancel1._stream = stream;\n cancel1._teeState = teeState;\n\n var cancel2 = create_ReadableStreamTeeBranch2CancelFunction();\n cancel2._stream = stream;\n cancel2._teeState = teeState;\n\n var underlyingSource1 = Object.create(Object.prototype);\n createDataProperty(underlyingSource1, 'pull', pull);\n createDataProperty(underlyingSource1, 'cancel', cancel1);\n var branch1Stream = new ReadableStream(underlyingSource1);\n\n var underlyingSource2 = Object.create(Object.prototype);\n createDataProperty(underlyingSource2, 'pull', pull);\n createDataProperty(underlyingSource2, 'cancel', cancel2);\n var branch2Stream = new ReadableStream(underlyingSource2);\n\n pull._branch1 = branch1Stream._readableStreamController;\n pull._branch2 = branch2Stream._readableStreamController;\n\n reader._closedPromise.catch(function (r) {\n if (teeState.closedOrErrored === true) {\n return;\n }\n\n ReadableStreamDefaultControllerError(pull._branch1, r);\n ReadableStreamDefaultControllerError(pull._branch2, r);\n teeState.closedOrErrored = true;\n });\n\n return [branch1Stream, branch2Stream];\n}\n\nfunction create_ReadableStreamTeePullFunction() {\n function f() {\n var reader = f._reader,\n branch1 = f._branch1,\n branch2 = f._branch2,\n teeState = f._teeState;\n\n\n return ReadableStreamDefaultReaderRead(reader).then(function (result) {\n assert(typeIsObject(result));\n var value = result.value;\n var done = result.done;\n assert(typeof done === 'boolean');\n\n if (done === true && teeState.closedOrErrored === false) {\n if (teeState.canceled1 === false) {\n ReadableStreamDefaultControllerClose(branch1);\n }\n if (teeState.canceled2 === false) {\n ReadableStreamDefaultControllerClose(branch2);\n }\n teeState.closedOrErrored = true;\n }\n\n if (teeState.closedOrErrored === true) {\n return;\n }\n\n var value1 = value;\n var value2 = value;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (teeState.canceled2 === false && cloneForBranch2 === true) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n\n if (teeState.canceled1 === false) {\n ReadableStreamDefaultControllerEnqueue(branch1, value1);\n }\n\n if (teeState.canceled2 === false) {\n ReadableStreamDefaultControllerEnqueue(branch2, value2);\n }\n });\n }\n return f;\n}\n\nfunction create_ReadableStreamTeeBranch1CancelFunction() {\n function f(reason) {\n var stream = f._stream,\n teeState = f._teeState;\n\n\n teeState.canceled1 = true;\n teeState.reason1 = reason;\n if (teeState.canceled2 === true) {\n var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);\n var cancelResult = ReadableStreamCancel(stream, compositeReason);\n teeState._resolve(cancelResult);\n }\n return teeState.promise;\n }\n return f;\n}\n\nfunction create_ReadableStreamTeeBranch2CancelFunction() {\n function f(reason) {\n var stream = f._stream,\n teeState = f._teeState;\n\n\n teeState.canceled2 = true;\n teeState.reason2 = reason;\n if (teeState.canceled1 === true) {\n var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);\n var cancelResult = ReadableStreamCancel(stream, compositeReason);\n teeState._resolve(cancelResult);\n }\n return teeState.promise;\n }\n return f;\n}\n\n// ReadableStream API exposed for controllers.\n\nfunction ReadableStreamAddReadIntoRequest(stream) {\n assert(IsReadableStreamBYOBReader(stream._reader) === true);\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n var promise = new Promise(function (resolve, reject) {\n var readIntoRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._reader._readIntoRequests.push(readIntoRequest);\n });\n\n return promise;\n}\n\nfunction ReadableStreamAddReadRequest(stream) {\n assert(IsReadableStreamDefaultReader(stream._reader) === true);\n assert(stream._state === 'readable');\n\n var promise = new Promise(function (resolve, reject) {\n var readRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._reader._readRequests.push(readRequest);\n });\n\n return promise;\n}\n\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return Promise.resolve(undefined);\n }\n if (stream._state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n var sourceCancelPromise = stream._readableStreamController.__cancelSteps(reason);\n return sourceCancelPromise.then(function () {\n return undefined;\n });\n}\n\nfunction ReadableStreamClose(stream) {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n var reader = stream._reader;\n\n if (reader === undefined) {\n return undefined;\n }\n\n if (IsReadableStreamDefaultReader(reader) === true) {\n for (var i = 0; i < reader._readRequests.length; i++) {\n var _resolve = reader._readRequests[i]._resolve;\n\n _resolve(CreateIterResultObject(undefined, true));\n }\n reader._readRequests = [];\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n return undefined;\n}\n\nfunction ReadableStreamError(stream, e) {\n assert(IsReadableStream(stream) === true, 'stream must be ReadableStream');\n assert(stream._state === 'readable', 'state must be readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n var reader = stream._reader;\n\n if (reader === undefined) {\n return undefined;\n }\n\n if (IsReadableStreamDefaultReader(reader) === true) {\n for (var i = 0; i < reader._readRequests.length; i++) {\n var readRequest = reader._readRequests[i];\n readRequest._reject(e);\n }\n\n reader._readRequests = [];\n } else {\n assert(IsReadableStreamBYOBReader(reader), 'reader must be ReadableStreamBYOBReader');\n\n for (var _i = 0; _i < reader._readIntoRequests.length; _i++) {\n var readIntoRequest = reader._readIntoRequests[_i];\n readIntoRequest._reject(e);\n }\n\n reader._readIntoRequests = [];\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n reader._closedPromise.catch(function () {});\n}\n\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n var reader = stream._reader;\n\n assert(reader._readIntoRequests.length > 0);\n\n var readIntoRequest = reader._readIntoRequests.shift();\n readIntoRequest._resolve(CreateIterResultObject(chunk, done));\n}\n\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n var reader = stream._reader;\n\n assert(reader._readRequests.length > 0);\n\n var readRequest = reader._readRequests.shift();\n readRequest._resolve(CreateIterResultObject(chunk, done));\n}\n\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\n\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\n\nfunction ReadableStreamHasBYOBReader(stream) {\n var reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (IsReadableStreamBYOBReader(reader) === false) {\n return false;\n }\n\n return true;\n}\n\nfunction ReadableStreamHasDefaultReader(stream) {\n var reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (IsReadableStreamDefaultReader(reader) === false) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nvar ReadableStreamDefaultReader = function () {\n function ReadableStreamDefaultReader(stream) {\n _classCallCheck(this, ReadableStreamDefaultReader);\n\n if (IsReadableStream(stream) === false) {\n throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance');\n }\n if (IsReadableStreamLocked(stream) === true) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = [];\n }\n\n _createClass(ReadableStreamDefaultReader, [{\n key: 'cancel',\n value: function cancel(reason) {\n if (IsReadableStreamDefaultReader(this) === false) {\n return Promise.reject(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return Promise.reject(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n }, {\n key: 'read',\n value: function read() {\n if (IsReadableStreamDefaultReader(this) === false) {\n return Promise.reject(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return Promise.reject(readerLockException('read from'));\n }\n\n return ReadableStreamDefaultReaderRead(this);\n }\n }, {\n key: 'releaseLock',\n value: function releaseLock() {\n if (IsReadableStreamDefaultReader(this) === false) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n }, {\n key: 'closed',\n get: function get() {\n if (IsReadableStreamDefaultReader(this) === false) {\n return Promise.reject(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n }]);\n\n return ReadableStreamDefaultReader;\n}();\n\nvar ReadableStreamBYOBReader = function () {\n function ReadableStreamBYOBReader(stream) {\n _classCallCheck(this, ReadableStreamBYOBReader);\n\n if (!IsReadableStream(stream)) {\n throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' + 'byte source');\n }\n if (IsReadableByteStreamController(stream._readableStreamController) === false) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + 'source');\n }\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = [];\n }\n\n _createClass(ReadableStreamBYOBReader, [{\n key: 'cancel',\n value: function cancel(reason) {\n if (!IsReadableStreamBYOBReader(this)) {\n return Promise.reject(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return Promise.reject(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n }, {\n key: 'read',\n value: function read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return Promise.reject(byobReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return Promise.reject(readerLockException('read from'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return Promise.reject(new TypeError('view must be an array buffer view'));\n }\n\n if (view.byteLength === 0) {\n return Promise.reject(new TypeError('view must have non-zero byteLength'));\n }\n\n return ReadableStreamBYOBReaderRead(this, view);\n }\n }, {\n key: 'releaseLock',\n value: function releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n }, {\n key: 'closed',\n get: function get() {\n if (!IsReadableStreamBYOBReader(this)) {\n return Promise.reject(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n }]);\n\n return ReadableStreamBYOBReader;\n}();\n\n// Abstract operations for the readers.\n\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return true;\n}\n\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return true;\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored', 'state must be errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n reader._closedPromise.catch(function () {});\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n var stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nfunction ReadableStreamReaderGenericRelease(reader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\\'s closedness'));\n } else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\\'s closedness'));\n }\n reader._closedPromise.catch(function () {});\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n\nfunction ReadableStreamBYOBReaderRead(reader, view) {\n var stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n\n // Controllers must implement this.\n return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);\n}\n\nfunction ReadableStreamDefaultReaderRead(reader) {\n var stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return Promise.resolve(CreateIterResultObject(undefined, true));\n }\n\n if (stream._state === 'errored') {\n return Promise.reject(stream._storedError);\n }\n\n assert(stream._state === 'readable');\n\n return stream._readableStreamController.__pullSteps();\n}\n\n// Controllers\n\nvar ReadableStreamDefaultController = function () {\n function ReadableStreamDefaultController(stream, underlyingSource, size, highWaterMark) {\n _classCallCheck(this, ReadableStreamDefaultController);\n\n if (IsReadableStream(stream) === false) {\n throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance');\n }\n\n if (stream._readableStreamController !== undefined) {\n throw new TypeError('ReadableStreamDefaultController instances can only be created by the ReadableStream constructor');\n }\n\n this._controlledReadableStream = stream;\n\n this._underlyingSource = underlyingSource;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n this._queue = undefined;\n this._queueTotalSize = undefined;\n ResetQueue(this);\n\n this._started = false;\n this._closeRequested = false;\n this._pullAgain = false;\n this._pulling = false;\n\n var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);\n this._strategySize = normalizedStrategy.size;\n this._strategyHWM = normalizedStrategy.highWaterMark;\n\n var controller = this;\n\n var startResult = InvokeOrNoop(underlyingSource, 'start', [this]);\n Promise.resolve(startResult).then(function () {\n controller._started = true;\n\n assert(controller._pulling === false);\n assert(controller._pullAgain === false);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, function (r) {\n ReadableStreamDefaultControllerErrorIfNeeded(controller, r);\n }).catch(rethrowAssertionErrorRejection);\n }\n\n _createClass(ReadableStreamDefaultController, [{\n key: 'close',\n value: function close() {\n if (IsReadableStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (this._closeRequested === true) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n var state = this._controlledReadableStream._state;\n if (state !== 'readable') {\n throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n }, {\n key: 'enqueue',\n value: function enqueue(chunk) {\n if (IsReadableStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (this._closeRequested === true) {\n throw new TypeError('stream is closed or draining');\n }\n\n var state = this._controlledReadableStream._state;\n if (state !== 'readable') {\n throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n }, {\n key: 'error',\n value: function error(e) {\n if (IsReadableStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('error');\n }\n\n var stream = this._controlledReadableStream;\n if (stream._state !== 'readable') {\n throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n }, {\n key: '__cancelSteps',\n value: function __cancelSteps(reason) {\n ResetQueue(this);\n return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]);\n }\n }, {\n key: '__pullSteps',\n value: function __pullSteps() {\n var stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n var chunk = DequeueValue(this);\n\n if (this._closeRequested === true && this._queue.length === 0) {\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n return Promise.resolve(CreateIterResultObject(chunk, false));\n }\n\n var pendingPromise = ReadableStreamAddReadRequest(stream);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n return pendingPromise;\n }\n }, {\n key: 'desiredSize',\n get: function get() {\n if (IsReadableStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n }]);\n\n return ReadableStreamDefaultController;\n}();\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) {\n return false;\n }\n\n return true;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (shouldPull === false) {\n return undefined;\n }\n\n if (controller._pulling === true) {\n controller._pullAgain = true;\n return undefined;\n }\n\n assert(controller._pullAgain === false);\n\n controller._pulling = true;\n\n var pullPromise = PromiseInvokeOrNoop(controller._underlyingSource, 'pull', [controller]);\n pullPromise.then(function () {\n controller._pulling = false;\n\n if (controller._pullAgain === true) {\n controller._pullAgain = false;\n return ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n return undefined;\n }, function (e) {\n ReadableStreamDefaultControllerErrorIfNeeded(controller, e);\n }).catch(rethrowAssertionErrorRejection);\n\n return undefined;\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n var stream = controller._controlledReadableStream;\n\n if (stream._state === 'closed' || stream._state === 'errored') {\n return false;\n }\n\n if (controller._closeRequested === true) {\n return false;\n }\n\n if (controller._started === false) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n\n return false;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction ReadableStreamDefaultControllerClose(controller) {\n var stream = controller._controlledReadableStream;\n\n assert(controller._closeRequested === false);\n assert(stream._state === 'readable');\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamClose(stream);\n }\n}\n\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n var stream = controller._controlledReadableStream;\n\n assert(controller._closeRequested === false);\n assert(stream._state === 'readable');\n\n if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n var chunkSize = 1;\n\n if (controller._strategySize !== undefined) {\n var strategySize = controller._strategySize;\n try {\n chunkSize = strategySize(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n throw chunkSizeE;\n }\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n\n return undefined;\n}\n\nfunction ReadableStreamDefaultControllerError(controller, e) {\n var stream = controller._controlledReadableStream;\n\n assert(stream._state === 'readable');\n\n ResetQueue(controller);\n\n ReadableStreamError(stream, e);\n}\n\nfunction ReadableStreamDefaultControllerErrorIfNeeded(controller, e) {\n if (controller._controlledReadableStream._state === 'readable') {\n ReadableStreamDefaultControllerError(controller, e);\n }\n}\n\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n var stream = controller._controlledReadableStream;\n var state = stream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nvar ReadableStreamBYOBRequest = function () {\n function ReadableStreamBYOBRequest(controller, view) {\n _classCallCheck(this, ReadableStreamBYOBRequest);\n\n this._associatedReadableByteStreamController = controller;\n this._view = view;\n }\n\n _createClass(ReadableStreamBYOBRequest, [{\n key: 'respond',\n value: function respond(bytesWritten) {\n if (IsReadableStreamBYOBRequest(this) === false) {\n throw byobRequestBrandCheckException('respond');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n }, {\n key: 'respondWithNewView',\n value: function respondWithNewView(view) {\n if (IsReadableStreamBYOBRequest(this) === false) {\n throw byobRequestBrandCheckException('respond');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n }, {\n key: 'view',\n get: function get() {\n return this._view;\n }\n }]);\n\n return ReadableStreamBYOBRequest;\n}();\n\nvar ReadableByteStreamController = function () {\n function ReadableByteStreamController(stream, underlyingByteSource, highWaterMark) {\n _classCallCheck(this, ReadableByteStreamController);\n\n if (IsReadableStream(stream) === false) {\n throw new TypeError('ReadableByteStreamController can only be constructed with a ReadableStream instance given ' + 'a byte source');\n }\n\n if (stream._readableStreamController !== undefined) {\n throw new TypeError('ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte ' + 'source');\n }\n\n this._controlledReadableStream = stream;\n\n this._underlyingByteSource = underlyingByteSource;\n\n this._pullAgain = false;\n this._pulling = false;\n\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n this._queue = this._queueTotalSize = undefined;\n ResetQueue(this);\n\n this._closeRequested = false;\n this._started = false;\n\n this._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark);\n\n var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n if (Number.isInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) {\n throw new RangeError('autoAllocateChunkSize must be a positive integer');\n }\n }\n this._autoAllocateChunkSize = autoAllocateChunkSize;\n\n this._pendingPullIntos = [];\n\n var controller = this;\n\n var startResult = InvokeOrNoop(underlyingByteSource, 'start', [this]);\n Promise.resolve(startResult).then(function () {\n controller._started = true;\n\n assert(controller._pulling === false);\n assert(controller._pullAgain === false);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, function (r) {\n if (stream._state === 'readable') {\n ReadableByteStreamControllerError(controller, r);\n }\n }).catch(rethrowAssertionErrorRejection);\n }\n\n _createClass(ReadableByteStreamController, [{\n key: 'close',\n value: function close() {\n if (IsReadableByteStreamController(this) === false) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested === true) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n var state = this._controlledReadableStream._state;\n if (state !== 'readable') {\n throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed');\n }\n\n ReadableByteStreamControllerClose(this);\n }\n }, {\n key: 'enqueue',\n value: function enqueue(chunk) {\n if (IsReadableByteStreamController(this) === false) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n if (this._closeRequested === true) {\n throw new TypeError('stream is closed or draining');\n }\n\n var state = this._controlledReadableStream._state;\n if (state !== 'readable') {\n throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to');\n }\n\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n }, {\n key: 'error',\n value: function error(e) {\n if (IsReadableByteStreamController(this) === false) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n var stream = this._controlledReadableStream;\n if (stream._state !== 'readable') {\n throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n }, {\n key: '__cancelSteps',\n value: function __cancelSteps(reason) {\n if (this._pendingPullIntos.length > 0) {\n var firstDescriptor = this._pendingPullIntos[0];\n firstDescriptor.bytesFilled = 0;\n }\n\n ResetQueue(this);\n\n return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]);\n }\n }, {\n key: '__pullSteps',\n value: function __pullSteps() {\n var stream = this._controlledReadableStream;\n assert(ReadableStreamHasDefaultReader(stream) === true);\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n var entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n var view = void 0;\n try {\n view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n } catch (viewE) {\n return Promise.reject(viewE);\n }\n\n return Promise.resolve(CreateIterResultObject(view, false));\n }\n\n var autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n var buffer = void 0;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n return Promise.reject(bufferE);\n }\n\n var pullIntoDescriptor = {\n buffer: buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n ctor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n var promise = ReadableStreamAddReadRequest(stream);\n\n ReadableByteStreamControllerCallPullIfNeeded(this);\n\n return promise;\n }\n }, {\n key: 'byobRequest',\n get: function get() {\n if (IsReadableByteStreamController(this) === false) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {\n var firstDescriptor = this._pendingPullIntos[0];\n var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n this._byobRequest = new ReadableStreamBYOBRequest(this, view);\n }\n\n return this._byobRequest;\n }\n }, {\n key: 'desiredSize',\n get: function get() {\n if (IsReadableByteStreamController(this) === false) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n }]);\n\n return ReadableByteStreamController;\n}();\n\n// Abstract operations for the ReadableByteStreamController.\n\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) {\n return false;\n }\n\n return true;\n}\n\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return true;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n var shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (shouldPull === false) {\n return undefined;\n }\n\n if (controller._pulling === true) {\n controller._pullAgain = true;\n return undefined;\n }\n\n assert(controller._pullAgain === false);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n var pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]);\n pullPromise.then(function () {\n controller._pulling = false;\n\n if (controller._pullAgain === true) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, function (e) {\n if (controller._controlledReadableStream._state === 'readable') {\n ReadableByteStreamControllerError(controller, e);\n }\n }).catch(rethrowAssertionErrorRejection);\n\n return undefined;\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = [];\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n assert(stream._state !== 'errored', 'state must not be errored');\n\n var done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n var bytesFilled = pullIntoDescriptor.bytesFilled;\n var elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n var elementSize = pullIntoDescriptor.elementSize;\n\n var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n var totalBytesToCopyRemaining = maxBytesToCopy;\n var ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n var queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n var headOfQueue = queue[0];\n\n var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (ready === false) {\n assert(controller._queueTotalSize === 0, 'queue must be empty');\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor);\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n assert(controller._controlledReadableStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested === true) {\n ReadableStreamClose(controller._controlledReadableStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === undefined) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = undefined;\n controller._byobRequest = undefined;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n assert(controller._closeRequested === false);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n var pullIntoDescriptor = controller._pendingPullIntos[0];\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerPullInto(controller, view) {\n var stream = controller._controlledReadableStream;\n\n var elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n\n var ctor = view.constructor;\n\n var pullIntoDescriptor = {\n buffer: view.buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize: elementSize,\n ctor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n return ReadableStreamAddReadIntoRequest(stream);\n }\n\n if (stream._state === 'closed') {\n var emptyView = new view.constructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n return Promise.resolve(CreateIterResultObject(emptyView, true));\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {\n var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n return Promise.resolve(CreateIterResultObject(filledView, false));\n }\n\n if (controller._closeRequested === true) {\n var e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n return Promise.reject(e);\n }\n }\n\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n var promise = ReadableStreamAddReadIntoRequest(stream);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n\n return promise;\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0');\n\n var stream = controller._controlledReadableStream;\n if (ReadableStreamHasBYOBReader(stream) === true) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n var remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n var firstDescriptor = controller._pendingPullIntos[0];\n\n var stream = controller._controlledReadableStream;\n\n if (stream._state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(stream._state === 'readable');\n\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n var descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n var stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested === true) {\n return false;\n }\n\n if (controller._started === false) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) === true && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) {\n return true;\n }\n\n return false;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nfunction ReadableByteStreamControllerClose(controller) {\n var stream = controller._controlledReadableStream;\n\n assert(controller._closeRequested === false);\n assert(stream._state === 'readable');\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n var firstPendingPullInto = controller._pendingPullIntos[0];\n if (firstPendingPullInto.bytesFilled > 0) {\n var e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableStreamClose(stream);\n}\n\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n var stream = controller._controlledReadableStream;\n\n assert(controller._closeRequested === false);\n assert(stream._state === 'readable');\n\n var buffer = chunk.buffer;\n var byteOffset = chunk.byteOffset;\n var byteLength = chunk.byteLength;\n var transferredBuffer = TransferArrayBuffer(buffer);\n\n if (ReadableStreamHasDefaultReader(stream) === true) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n\n var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream) === true) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked');\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n}\n\nfunction ReadableByteStreamControllerError(controller, e) {\n var stream = controller._controlledReadableStream;\n\n assert(stream._state === 'readable');\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableStreamError(stream, e);\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n var stream = controller._controlledReadableStream;\n var state = stream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (IsFiniteNonNegativeNumber(bytesWritten) === false) {\n throw new RangeError('bytesWritten must be a finite');\n }\n\n assert(controller._pendingPullIntos.length > 0);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n assert(controller._pendingPullIntos.length > 0);\n\n var firstDescriptor = controller._pendingPullIntos[0];\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n\n firstDescriptor.buffer = view.buffer;\n\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name) {\n return new TypeError('ReadableStream.prototype.' + name + ' can only be used on a ReadableStream');\n}\n\n// Helper functions for the readers.\n\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError('ReadableStreamDefaultReader.prototype.' + name + ' can only be used on a ReadableStreamDefaultReader');\n}\n\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = new Promise(function (resolve, reject) {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n reader._closedPromise = Promise.reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n reader._closedPromise = Promise.resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n assert(reader._closedPromise_resolve !== undefined);\n assert(reader._closedPromise_reject !== undefined);\n\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n reader._closedPromise = Promise.reject(reason);\n}\n\nfunction defaultReaderClosedPromiseResolve(reader) {\n assert(reader._closedPromise_resolve !== undefined);\n assert(reader._closedPromise_reject !== undefined);\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction byobReaderBrandCheckException(name) {\n return new TypeError('ReadableStreamBYOBReader.prototype.' + name + ' can only be used on a ReadableStreamBYOBReader');\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError('ReadableStreamDefaultController.prototype.' + name + ' can only be used on a ReadableStreamDefaultController');\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name) {\n return new TypeError('ReadableStreamBYOBRequest.prototype.' + name + ' can only be used on a ReadableStreamBYOBRequest');\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError('ReadableByteStreamController.prototype.' + name + ' can only be used on a ReadableByteStreamController');\n}\n\n// Helper function for ReadableStream pipeThrough\n\nfunction ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise) {\n try {\n // This relies on the brand-check that is enforced by Promise.prototype.then(). As with the rest of the reference\n // implementation, it doesn't attempt to do the right thing if someone has modified the global environment.\n Promise.prototype.then.call(promise, undefined, function () {});\n } catch (e) {\n // The brand check failed, therefore the internal slot is not present and there's nothing further to do.\n }\n}\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar transformStream = __w_pdfjs_require__(6);\nvar readableStream = __w_pdfjs_require__(4);\nvar writableStream = __w_pdfjs_require__(2);\n\nexports.TransformStream = transformStream.TransformStream;\nexports.ReadableStream = readableStream.ReadableStream;\nexports.IsReadableStreamDisturbed = readableStream.IsReadableStreamDisturbed;\nexports.ReadableStreamDefaultControllerClose = readableStream.ReadableStreamDefaultControllerClose;\nexports.ReadableStreamDefaultControllerEnqueue = readableStream.ReadableStreamDefaultControllerEnqueue;\nexports.ReadableStreamDefaultControllerError = readableStream.ReadableStreamDefaultControllerError;\nexports.ReadableStreamDefaultControllerGetDesiredSize = readableStream.ReadableStreamDefaultControllerGetDesiredSize;\nexports.AcquireWritableStreamDefaultWriter = writableStream.AcquireWritableStreamDefaultWriter;\nexports.IsWritableStream = writableStream.IsWritableStream;\nexports.IsWritableStreamLocked = writableStream.IsWritableStreamLocked;\nexports.WritableStream = writableStream.WritableStream;\nexports.WritableStreamAbort = writableStream.WritableStreamAbort;\nexports.WritableStreamDefaultControllerError = writableStream.WritableStreamDefaultControllerError;\nexports.WritableStreamDefaultWriterCloseWithErrorPropagation = writableStream.WritableStreamDefaultWriterCloseWithErrorPropagation;\nexports.WritableStreamDefaultWriterRelease = writableStream.WritableStreamDefaultWriterRelease;\nexports.WritableStreamDefaultWriterWrite = writableStream.WritableStreamDefaultWriterWrite;\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar _require = __w_pdfjs_require__(1),\n assert = _require.assert;\n\nvar _require2 = __w_pdfjs_require__(0),\n InvokeOrNoop = _require2.InvokeOrNoop,\n PromiseInvokeOrPerformFallback = _require2.PromiseInvokeOrPerformFallback,\n PromiseInvokeOrNoop = _require2.PromiseInvokeOrNoop,\n typeIsObject = _require2.typeIsObject;\n\nvar _require3 = __w_pdfjs_require__(4),\n ReadableStream = _require3.ReadableStream,\n ReadableStreamDefaultControllerClose = _require3.ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue = _require3.ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError = _require3.ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize = _require3.ReadableStreamDefaultControllerGetDesiredSize;\n\nvar _require4 = __w_pdfjs_require__(2),\n WritableStream = _require4.WritableStream,\n WritableStreamDefaultControllerError = _require4.WritableStreamDefaultControllerError;\n\n// Methods on the transform stream controller object\n\nfunction TransformStreamCloseReadable(transformStream) {\n // console.log('TransformStreamCloseReadable()');\n\n if (transformStream._errored === true) {\n throw new TypeError('TransformStream is already errored');\n }\n\n if (transformStream._readableClosed === true) {\n throw new TypeError('Readable side is already closed');\n }\n\n TransformStreamCloseReadableInternal(transformStream);\n}\n\nfunction TransformStreamEnqueueToReadable(transformStream, chunk) {\n // console.log('TransformStreamEnqueueToReadable()');\n\n if (transformStream._errored === true) {\n throw new TypeError('TransformStream is already errored');\n }\n\n if (transformStream._readableClosed === true) {\n throw new TypeError('Readable side is already closed');\n }\n\n // We throttle transformer.transform invocation based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamEnqueueToReadable() calls.\n\n var controller = transformStream._readableController;\n\n try {\n ReadableStreamDefaultControllerEnqueue(controller, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n // The ReadableStream has already errored itself.\n transformStream._readableClosed = true;\n TransformStreamErrorIfNeeded(transformStream, e);\n\n throw transformStream._storedError;\n }\n\n var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n var maybeBackpressure = desiredSize <= 0;\n\n if (maybeBackpressure === true && transformStream._backpressure === false) {\n // This allows pull() again. When desiredSize is 0, it's possible that a pull() will happen immediately (but\n // asynchronously) after this because of pending read()s and set _backpressure back to false.\n //\n // If pull() could be called from inside enqueue(), then this logic would be wrong. This cannot happen\n // because there is always a promise pending from start() or pull() when _backpressure is false.\n TransformStreamSetBackpressure(transformStream, true);\n }\n}\n\nfunction TransformStreamError(transformStream, e) {\n if (transformStream._errored === true) {\n throw new TypeError('TransformStream is already errored');\n }\n\n TransformStreamErrorInternal(transformStream, e);\n}\n\n// Abstract operations.\n\nfunction TransformStreamCloseReadableInternal(transformStream) {\n assert(transformStream._errored === false);\n assert(transformStream._readableClosed === false);\n\n try {\n ReadableStreamDefaultControllerClose(transformStream._readableController);\n } catch (e) {\n assert(false);\n }\n\n transformStream._readableClosed = true;\n}\n\nfunction TransformStreamErrorIfNeeded(transformStream, e) {\n if (transformStream._errored === false) {\n TransformStreamErrorInternal(transformStream, e);\n }\n}\n\nfunction TransformStreamErrorInternal(transformStream, e) {\n // console.log('TransformStreamErrorInternal()');\n\n assert(transformStream._errored === false);\n\n transformStream._errored = true;\n transformStream._storedError = e;\n\n if (transformStream._writableDone === false) {\n WritableStreamDefaultControllerError(transformStream._writableController, e);\n }\n if (transformStream._readableClosed === false) {\n ReadableStreamDefaultControllerError(transformStream._readableController, e);\n }\n}\n\n// Used for preventing the next write() call on TransformStreamSink until there\n// is no longer backpressure.\nfunction TransformStreamReadableReadyPromise(transformStream) {\n assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');\n\n if (transformStream._backpressure === false) {\n return Promise.resolve();\n }\n\n assert(transformStream._backpressure === true, '_backpressure should have been initialized');\n\n return transformStream._backpressureChangePromise;\n}\n\nfunction TransformStreamSetBackpressure(transformStream, backpressure) {\n // console.log(`TransformStreamSetBackpressure(${backpressure})`);\n\n // Passes also when called during construction.\n assert(transformStream._backpressure !== backpressure, 'TransformStreamSetBackpressure() should be called only when backpressure is changed');\n\n if (transformStream._backpressureChangePromise !== undefined) {\n // The fulfillment value is just for a sanity check.\n transformStream._backpressureChangePromise_resolve(backpressure);\n }\n\n transformStream._backpressureChangePromise = new Promise(function (resolve) {\n transformStream._backpressureChangePromise_resolve = resolve;\n });\n\n transformStream._backpressureChangePromise.then(function (resolution) {\n assert(resolution !== backpressure, '_backpressureChangePromise should be fulfilled only when backpressure is changed');\n });\n\n transformStream._backpressure = backpressure;\n}\n\nfunction TransformStreamDefaultTransform(chunk, transformStreamController) {\n var transformStream = transformStreamController._controlledTransformStream;\n TransformStreamEnqueueToReadable(transformStream, chunk);\n return Promise.resolve();\n}\n\nfunction TransformStreamTransform(transformStream, chunk) {\n // console.log('TransformStreamTransform()');\n\n assert(transformStream._errored === false);\n assert(transformStream._transforming === false);\n assert(transformStream._backpressure === false);\n\n transformStream._transforming = true;\n\n var transformer = transformStream._transformer;\n var controller = transformStream._transformStreamController;\n\n var transformPromise = PromiseInvokeOrPerformFallback(transformer, 'transform', [chunk, controller], TransformStreamDefaultTransform, [chunk, controller]);\n\n return transformPromise.then(function () {\n transformStream._transforming = false;\n\n return TransformStreamReadableReadyPromise(transformStream);\n }, function (e) {\n TransformStreamErrorIfNeeded(transformStream, e);\n return Promise.reject(e);\n });\n}\n\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return true;\n}\n\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return true;\n}\n\nvar TransformStreamSink = function () {\n function TransformStreamSink(transformStream, startPromise) {\n _classCallCheck(this, TransformStreamSink);\n\n this._transformStream = transformStream;\n this._startPromise = startPromise;\n }\n\n _createClass(TransformStreamSink, [{\n key: 'start',\n value: function start(c) {\n var transformStream = this._transformStream;\n\n transformStream._writableController = c;\n\n return this._startPromise.then(function () {\n return TransformStreamReadableReadyPromise(transformStream);\n });\n }\n }, {\n key: 'write',\n value: function write(chunk) {\n // console.log('TransformStreamSink.write()');\n\n var transformStream = this._transformStream;\n\n return TransformStreamTransform(transformStream, chunk);\n }\n }, {\n key: 'abort',\n value: function abort() {\n var transformStream = this._transformStream;\n transformStream._writableDone = true;\n TransformStreamErrorInternal(transformStream, new TypeError('Writable side aborted'));\n }\n }, {\n key: 'close',\n value: function close() {\n // console.log('TransformStreamSink.close()');\n\n var transformStream = this._transformStream;\n\n assert(transformStream._transforming === false);\n\n transformStream._writableDone = true;\n\n var flushPromise = PromiseInvokeOrNoop(transformStream._transformer, 'flush', [transformStream._transformStreamController]);\n // Return a promise that is fulfilled with undefined on success.\n return flushPromise.then(function () {\n if (transformStream._errored === true) {\n return Promise.reject(transformStream._storedError);\n }\n if (transformStream._readableClosed === false) {\n TransformStreamCloseReadableInternal(transformStream);\n }\n return Promise.resolve();\n }).catch(function (r) {\n TransformStreamErrorIfNeeded(transformStream, r);\n return Promise.reject(transformStream._storedError);\n });\n }\n }]);\n\n return TransformStreamSink;\n}();\n\nvar TransformStreamSource = function () {\n function TransformStreamSource(transformStream, startPromise) {\n _classCallCheck(this, TransformStreamSource);\n\n this._transformStream = transformStream;\n this._startPromise = startPromise;\n }\n\n _createClass(TransformStreamSource, [{\n key: 'start',\n value: function start(c) {\n var transformStream = this._transformStream;\n\n transformStream._readableController = c;\n\n return this._startPromise.then(function () {\n // Prevent the first pull() call until there is backpressure.\n\n assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');\n\n if (transformStream._backpressure === true) {\n return Promise.resolve();\n }\n\n assert(transformStream._backpressure === false, '_backpressure should have been initialized');\n\n return transformStream._backpressureChangePromise;\n });\n }\n }, {\n key: 'pull',\n value: function pull() {\n // console.log('TransformStreamSource.pull()');\n\n var transformStream = this._transformStream;\n\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(transformStream._backpressure === true, 'pull() should be never called while _backpressure is false');\n\n assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized');\n\n TransformStreamSetBackpressure(transformStream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return transformStream._backpressureChangePromise;\n }\n }, {\n key: 'cancel',\n value: function cancel() {\n var transformStream = this._transformStream;\n transformStream._readableClosed = true;\n TransformStreamErrorInternal(transformStream, new TypeError('Readable side canceled'));\n }\n }]);\n\n return TransformStreamSource;\n}();\n\nvar TransformStreamDefaultController = function () {\n function TransformStreamDefaultController(transformStream) {\n _classCallCheck(this, TransformStreamDefaultController);\n\n if (IsTransformStream(transformStream) === false) {\n throw new TypeError('TransformStreamDefaultController can only be ' + 'constructed with a TransformStream instance');\n }\n\n if (transformStream._transformStreamController !== undefined) {\n throw new TypeError('TransformStreamDefaultController instances can ' + 'only be created by the TransformStream constructor');\n }\n\n this._controlledTransformStream = transformStream;\n }\n\n _createClass(TransformStreamDefaultController, [{\n key: 'enqueue',\n value: function enqueue(chunk) {\n if (IsTransformStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamEnqueueToReadable(this._controlledTransformStream, chunk);\n }\n }, {\n key: 'close',\n value: function close() {\n if (IsTransformStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('close');\n }\n\n TransformStreamCloseReadable(this._controlledTransformStream);\n }\n }, {\n key: 'error',\n value: function error(reason) {\n if (IsTransformStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamError(this._controlledTransformStream, reason);\n }\n }, {\n key: 'desiredSize',\n get: function get() {\n if (IsTransformStreamDefaultController(this) === false) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n var transformStream = this._controlledTransformStream;\n var readableController = transformStream._readableController;\n\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n }]);\n\n return TransformStreamDefaultController;\n}();\n\nvar TransformStream = function () {\n function TransformStream() {\n var transformer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, TransformStream);\n\n this._transformer = transformer;\n var readableStrategy = transformer.readableStrategy,\n writableStrategy = transformer.writableStrategy;\n\n\n this._transforming = false;\n this._errored = false;\n this._storedError = undefined;\n\n this._writableController = undefined;\n this._readableController = undefined;\n this._transformStreamController = undefined;\n\n this._writableDone = false;\n this._readableClosed = false;\n\n this._backpressure = undefined;\n this._backpressureChangePromise = undefined;\n this._backpressureChangePromise_resolve = undefined;\n\n this._transformStreamController = new TransformStreamDefaultController(this);\n\n var startPromise_resolve = void 0;\n var startPromise = new Promise(function (resolve) {\n startPromise_resolve = resolve;\n });\n\n var source = new TransformStreamSource(this, startPromise);\n\n this._readable = new ReadableStream(source, readableStrategy);\n\n var sink = new TransformStreamSink(this, startPromise);\n\n this._writable = new WritableStream(sink, writableStrategy);\n\n assert(this._writableController !== undefined);\n assert(this._readableController !== undefined);\n\n var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(this._readableController);\n // Set _backpressure based on desiredSize. As there is no read() at this point, we can just interpret\n // desiredSize being non-positive as backpressure.\n TransformStreamSetBackpressure(this, desiredSize <= 0);\n\n var transformStream = this;\n var startResult = InvokeOrNoop(transformer, 'start', [transformStream._transformStreamController]);\n startPromise_resolve(startResult);\n startPromise.catch(function (e) {\n // The underlyingSink and underlyingSource will error the readable and writable ends on their own.\n if (transformStream._errored === false) {\n transformStream._errored = true;\n transformStream._storedError = e;\n }\n });\n }\n\n _createClass(TransformStream, [{\n key: 'readable',\n get: function get() {\n if (IsTransformStream(this) === false) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n }, {\n key: 'writable',\n get: function get() {\n if (IsTransformStream(this) === false) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n }]);\n\n return TransformStream;\n}();\n\nmodule.exports = { TransformStream: TransformStream };\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError('TransformStreamDefaultController.prototype.' + name + ' can only be used on a TransformStreamDefaultController');\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name) {\n return new TypeError('TransformStream.prototype.' + name + ' can only be used on a TransformStream');\n}\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __w_pdfjs_require__) {\n\nmodule.exports = __w_pdfjs_require__(5);\n\n\n/***/ })\n/******/ ])));","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* eslint-disable no-restricted-globals */\n\nif (typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('GENERIC')) {\n // The `URL` constructor is assumed to be available in the extension builds.\n exports.URL = URL;\n} else {\n let isURLSupported = false;\n try {\n if (typeof URL === 'function' && typeof URL.prototype === 'object' &&\n ('origin' in URL.prototype)) {\n const u = new URL('b', 'http://a');\n u.pathname = 'c%20d';\n isURLSupported = (u.href === 'http://a/c%20d');\n }\n } catch (ex) {\n // The `URL` constructor cannot be used.\n }\n\n if (isURLSupported) {\n exports.URL = URL;\n } else if (typeof PDFJSDev !== 'undefined' &&\n PDFJSDev.test('IMAGE_DECODERS')) {\n class DummyURL {\n constructor() {\n throw new Error('The current image decoders doesn\\'t utilize the ' +\n '`URL` constructor, hence it shouldn\\'t need to be ' +\n 'polyfilled for the IMAGE_DECODERS build target.');\n }\n }\n exports.URL = DummyURL;\n } else {\n const PolyfillURL = require('../../external/url/url-lib').URL;\n\n // Attempt to copy over the static methods.\n const OriginalURL = require('./global_scope').URL;\n if (OriginalURL) {\n PolyfillURL.createObjectURL = function(blob) {\n // IE extension allows a second optional options argument, see\n // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx\n return OriginalURL.createObjectURL.apply(OriginalURL, arguments);\n };\n PolyfillURL.revokeObjectURL = function(url) {\n OriginalURL.revokeObjectURL(url);\n };\n }\n exports.URL = PolyfillURL;\n }\n}\n","/* Any copyright is dedicated to the Public Domain.\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n// Polyfill obtained from: https://github.com/Polymer/URL\n\n(function URLConstructorClosure() {\n 'use strict';\n\n var relative = Object.create(null);\n relative['ftp'] = 21;\n relative['file'] = 0;\n relative['gopher'] = 70;\n relative['http'] = 80;\n relative['https'] = 443;\n relative['ws'] = 80;\n relative['wss'] = 443;\n\n var relativePathDotMapping = Object.create(null);\n relativePathDotMapping['%2e'] = '.';\n relativePathDotMapping['.%2e'] = '..';\n relativePathDotMapping['%2e.'] = '..';\n relativePathDotMapping['%2e%2e'] = '..';\n\n function isRelativeScheme(scheme) {\n return relative[scheme] !== undefined;\n }\n\n function invalid() {\n clear.call(this);\n this._isInvalid = true;\n }\n\n function IDNAToASCII(h) {\n if (h === '') {\n invalid.call(this);\n }\n // XXX\n return h.toLowerCase();\n }\n\n function percentEscape(c) {\n var unicode = c.charCodeAt(0);\n if (unicode > 0x20 &&\n unicode < 0x7F &&\n // \" # < > ? `\n [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1\n ) {\n return c;\n }\n return encodeURIComponent(c);\n }\n\n function percentEscapeQuery(c) {\n // XXX This actually needs to encode c using encoding and then\n // convert the bytes one-by-one.\n\n var unicode = c.charCodeAt(0);\n if (unicode > 0x20 &&\n unicode < 0x7F &&\n // \" # < > ` (do not escape '?')\n [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1\n ) {\n return c;\n }\n return encodeURIComponent(c);\n }\n\n var EOF, ALPHA = /[a-zA-Z]/,\n ALPHANUMERIC = /[a-zA-Z0-9\\+\\-\\.]/;\n\n function parse(input, stateOverride, base) {\n function err(message) {\n errors.push(message);\n }\n\n var state = stateOverride || 'scheme start',\n cursor = 0,\n buffer = '',\n seenAt = false,\n seenBracket = false,\n errors = [];\n\n loop: while ((input[cursor - 1] !== EOF || cursor === 0) &&\n !this._isInvalid) {\n var c = input[cursor];\n switch (state) {\n case 'scheme start':\n if (c && ALPHA.test(c)) {\n buffer += c.toLowerCase(); // ASCII-safe\n state = 'scheme';\n } else if (!stateOverride) {\n buffer = '';\n state = 'no scheme';\n continue;\n } else {\n err('Invalid scheme.');\n break loop;\n }\n break;\n\n case 'scheme':\n if (c && ALPHANUMERIC.test(c)) {\n buffer += c.toLowerCase(); // ASCII-safe\n } else if (c === ':') {\n this._scheme = buffer;\n buffer = '';\n if (stateOverride) {\n break loop;\n }\n if (isRelativeScheme(this._scheme)) {\n this._isRelative = true;\n }\n if (this._scheme === 'file') {\n state = 'relative';\n } else if (this._isRelative && base &&\n base._scheme === this._scheme) {\n state = 'relative or authority';\n } else if (this._isRelative) {\n state = 'authority first slash';\n } else {\n state = 'scheme data';\n }\n } else if (!stateOverride) {\n buffer = '';\n cursor = 0;\n state = 'no scheme';\n continue;\n } else if (c === EOF) {\n break loop;\n } else {\n err('Code point not allowed in scheme: ' + c);\n break loop;\n }\n break;\n\n case 'scheme data':\n if (c === '?') {\n this._query = '?';\n state = 'query';\n } else if (c === '#') {\n this._fragment = '#';\n state = 'fragment';\n } else {\n // XXX error handling\n if (c !== EOF && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n this._schemeData += percentEscape(c);\n }\n }\n break;\n\n case 'no scheme':\n if (!base || !(isRelativeScheme(base._scheme))) {\n err('Missing scheme.');\n invalid.call(this);\n } else {\n state = 'relative';\n continue;\n }\n break;\n\n case 'relative or authority':\n if (c === '/' && input[cursor + 1] === '/') {\n state = 'authority ignore slashes';\n } else {\n err('Expected /, got: ' + c);\n state = 'relative';\n continue;\n }\n break;\n\n case 'relative':\n this._isRelative = true;\n if (this._scheme !== 'file') {\n this._scheme = base._scheme;\n }\n if (c === EOF) {\n this._host = base._host;\n this._port = base._port;\n this._path = base._path.slice();\n this._query = base._query;\n this._username = base._username;\n this._password = base._password;\n break loop;\n } else if (c === '/' || c === '\\\\') {\n if (c === '\\\\') {\n err('\\\\ is an invalid code point.');\n }\n state = 'relative slash';\n } else if (c === '?') {\n this._host = base._host;\n this._port = base._port;\n this._path = base._path.slice();\n this._query = '?';\n this._username = base._username;\n this._password = base._password;\n state = 'query';\n } else if (c === '#') {\n this._host = base._host;\n this._port = base._port;\n this._path = base._path.slice();\n this._query = base._query;\n this._fragment = '#';\n this._username = base._username;\n this._password = base._password;\n state = 'fragment';\n } else {\n var nextC = input[cursor + 1];\n var nextNextC = input[cursor + 2];\n if (this._scheme !== 'file' || !ALPHA.test(c) ||\n (nextC !== ':' && nextC !== '|') ||\n (nextNextC !== EOF && nextNextC !== '/' && nextNextC !== '\\\\' &&\n nextNextC !== '?' && nextNextC !== '#')) {\n this._host = base._host;\n this._port = base._port;\n this._username = base._username;\n this._password = base._password;\n this._path = base._path.slice();\n this._path.pop();\n }\n state = 'relative path';\n continue;\n }\n break;\n\n case 'relative slash':\n if (c === '/' || c === '\\\\') {\n if (c === '\\\\') {\n err('\\\\ is an invalid code point.');\n }\n if (this._scheme === 'file') {\n state = 'file host';\n } else {\n state = 'authority ignore slashes';\n }\n } else {\n if (this._scheme !== 'file') {\n this._host = base._host;\n this._port = base._port;\n this._username = base._username;\n this._password = base._password;\n }\n state = 'relative path';\n continue;\n }\n break;\n\n case 'authority first slash':\n if (c === '/') {\n state = 'authority second slash';\n } else {\n err('Expected \\'/\\', got: ' + c);\n state = 'authority ignore slashes';\n continue;\n }\n break;\n\n case 'authority second slash':\n state = 'authority ignore slashes';\n if (c !== '/') {\n err('Expected \\'/\\', got: ' + c);\n continue;\n }\n break;\n\n case 'authority ignore slashes':\n if (c !== '/' && c !== '\\\\') {\n state = 'authority';\n continue;\n } else {\n err('Expected authority, got: ' + c);\n }\n break;\n\n case 'authority':\n if (c === '@') {\n if (seenAt) {\n err('@ already seen.');\n buffer += '%40';\n }\n seenAt = true;\n for (var i = 0; i < buffer.length; i++) {\n var cp = buffer[i];\n if (cp === '\\t' || cp === '\\n' || cp === '\\r') {\n err('Invalid whitespace in authority.');\n continue;\n }\n // XXX check URL code points\n if (cp === ':' && this._password === null) {\n this._password = '';\n continue;\n }\n var tempC = percentEscape(cp);\n if (this._password !== null) {\n this._password += tempC;\n } else {\n this._username += tempC;\n }\n }\n buffer = '';\n } else if (c === EOF || c === '/' || c === '\\\\' ||\n c === '?' || c === '#') {\n cursor -= buffer.length;\n buffer = '';\n state = 'host';\n continue;\n } else {\n buffer += c;\n }\n break;\n\n case 'file host':\n if (c === EOF || c === '/' || c === '\\\\' || c === '?' || c === '#') {\n if (buffer.length === 2 && ALPHA.test(buffer[0]) &&\n (buffer[1] === ':' || buffer[1] === '|')) {\n state = 'relative path';\n } else if (buffer.length === 0) {\n state = 'relative path start';\n } else {\n this._host = IDNAToASCII.call(this, buffer);\n buffer = '';\n state = 'relative path start';\n }\n continue;\n } else if (c === '\\t' || c === '\\n' || c === '\\r') {\n err('Invalid whitespace in file host.');\n } else {\n buffer += c;\n }\n break;\n\n case 'host':\n case 'hostname':\n if (c === ':' && !seenBracket) {\n // XXX host parsing\n this._host = IDNAToASCII.call(this, buffer);\n buffer = '';\n state = 'port';\n if (stateOverride === 'hostname') {\n break loop;\n }\n } else if (c === EOF || c === '/' ||\n c === '\\\\' || c === '?' || c === '#') {\n this._host = IDNAToASCII.call(this, buffer);\n buffer = '';\n state = 'relative path start';\n if (stateOverride) {\n break loop;\n }\n continue;\n } else if (c !== '\\t' && c !== '\\n' && c !== '\\r') {\n if (c === '[') {\n seenBracket = true;\n } else if (c === ']') {\n seenBracket = false;\n }\n buffer += c;\n } else {\n err('Invalid code point in host/hostname: ' + c);\n }\n break;\n\n case 'port':\n if (/[0-9]/.test(c)) {\n buffer += c;\n } else if (c === EOF || c === '/' || c === '\\\\' ||\n c === '?' || c === '#' || stateOverride) {\n if (buffer !== '') {\n var temp = parseInt(buffer, 10);\n if (temp !== relative[this._scheme]) {\n this._port = temp + '';\n }\n buffer = '';\n }\n if (stateOverride) {\n break loop;\n }\n state = 'relative path start';\n continue;\n } else if (c === '\\t' || c === '\\n' || c === '\\r') {\n err('Invalid code point in port: ' + c);\n } else {\n invalid.call(this);\n }\n break;\n\n case 'relative path start':\n if (c === '\\\\') {\n err('\\'\\\\\\' not allowed in path.');\n }\n state = 'relative path';\n if (c !== '/' && c !== '\\\\') {\n continue;\n }\n break;\n\n case 'relative path':\n if (c === EOF || c === '/' || c === '\\\\' ||\n (!stateOverride && (c === '?' || c === '#'))) {\n if (c === '\\\\') {\n err('\\\\ not allowed in relative path.');\n }\n var tmp;\n if ((tmp = relativePathDotMapping[buffer.toLowerCase()])) {\n buffer = tmp;\n }\n if (buffer === '..') {\n this._path.pop();\n if (c !== '/' && c !== '\\\\') {\n this._path.push('');\n }\n } else if (buffer === '.' && c !== '/' && c !== '\\\\') {\n this._path.push('');\n } else if (buffer !== '.') {\n if (this._scheme === 'file' && this._path.length === 0 &&\n buffer.length === 2 && ALPHA.test(buffer[0]) &&\n buffer[1] === '|') {\n buffer = buffer[0] + ':';\n }\n this._path.push(buffer);\n }\n buffer = '';\n if (c === '?') {\n this._query = '?';\n state = 'query';\n } else if (c === '#') {\n this._fragment = '#';\n state = 'fragment';\n }\n } else if (c !== '\\t' && c !== '\\n' && c !== '\\r') {\n buffer += percentEscape(c);\n }\n break;\n\n case 'query':\n if (!stateOverride && c === '#') {\n this._fragment = '#';\n state = 'fragment';\n } else if (c !== EOF && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n this._query += percentEscapeQuery(c);\n }\n break;\n\n case 'fragment':\n if (c !== EOF && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n this._fragment += c;\n }\n break;\n }\n\n cursor++;\n }\n }\n\n function clear() {\n this._scheme = '';\n this._schemeData = '';\n this._username = '';\n this._password = null;\n this._host = '';\n this._port = '';\n this._path = [];\n this._query = '';\n this._fragment = '';\n this._isInvalid = false;\n this._isRelative = false;\n }\n\n // Does not process domain names or IP addresses.\n // Does not handle encoding for the query parameter.\n function JURL(url, base /* , encoding */) {\n if (base !== undefined && !(base instanceof JURL)) {\n base = new JURL(String(base));\n }\n\n this._url = url;\n clear.call(this);\n\n var input = url.replace(/^[ \\t\\r\\n\\f]+|[ \\t\\r\\n\\f]+$/g, '');\n // encoding = encoding || 'utf-8'\n\n parse.call(this, input, null, base);\n }\n\n JURL.prototype = {\n toString() {\n return this.href;\n },\n get href() {\n if (this._isInvalid) {\n return this._url;\n }\n var authority = '';\n if (this._username !== '' || this._password !== null) {\n authority = this._username +\n (this._password !== null ? ':' + this._password : '') + '@';\n }\n\n return this.protocol +\n (this._isRelative ? '//' + authority + this.host : '') +\n this.pathname + this._query + this._fragment;\n },\n // The named parameter should be different from the setter's function name.\n // Otherwise Safari 5 will throw an error (see issue 8541)\n set href(value) {\n clear.call(this);\n parse.call(this, value);\n },\n\n get protocol() {\n return this._scheme + ':';\n },\n set protocol(value) {\n if (this._isInvalid) {\n return;\n }\n parse.call(this, value + ':', 'scheme start');\n },\n\n get host() {\n return this._isInvalid ? '' : this._port ?\n this._host + ':' + this._port : this._host;\n },\n set host(value) {\n if (this._isInvalid || !this._isRelative) {\n return;\n }\n parse.call(this, value, 'host');\n },\n\n get hostname() {\n return this._host;\n },\n set hostname(value) {\n if (this._isInvalid || !this._isRelative) {\n return;\n }\n parse.call(this, value, 'hostname');\n },\n\n get port() {\n return this._port;\n },\n set port(value) {\n if (this._isInvalid || !this._isRelative) {\n return;\n }\n parse.call(this, value, 'port');\n },\n\n get pathname() {\n return this._isInvalid ? '' : this._isRelative ?\n '/' + this._path.join('/') : this._schemeData;\n },\n set pathname(value) {\n if (this._isInvalid || !this._isRelative) {\n return;\n }\n this._path = [];\n parse.call(this, value, 'relative path start');\n },\n\n get search() {\n return this._isInvalid || !this._query || this._query === '?' ?\n '' : this._query;\n },\n set search(value) {\n if (this._isInvalid || !this._isRelative) {\n return;\n }\n this._query = '?';\n if (value[0] === '?') {\n value = value.slice(1);\n }\n parse.call(this, value, 'query');\n },\n\n get hash() {\n return this._isInvalid || !this._fragment || this._fragment === '#' ?\n '' : this._fragment;\n },\n set hash(value) {\n if (this._isInvalid) {\n return;\n }\n this._fragment = '#';\n if (value[0] === '#') {\n value = value.slice(1);\n }\n parse.call(this, value, 'fragment');\n },\n\n get origin() {\n var host;\n if (this._isInvalid || !this._scheme) {\n return '';\n }\n // javascript: Gecko returns String(\"\"), WebKit/Blink String(\"null\")\n // Gecko throws error for \"data://\"\n // data: Gecko returns \"\", Blink returns \"data://\", WebKit returns \"null\"\n // Gecko returns String(\"\") for file: mailto:\n // WebKit/Blink returns String(\"SCHEME://\") for file: mailto:\n switch (this._scheme) {\n case 'data':\n case 'file':\n case 'javascript':\n case 'mailto':\n return 'null';\n case 'blob':\n // Special case of blob: -- returns valid origin of _schemeData.\n try {\n return new JURL(this._schemeData).origin || 'null';\n } catch (_) {\n // Invalid _schemeData origin -- ignoring errors.\n }\n return 'null';\n }\n host = this.host;\n if (!host) {\n return '';\n }\n return this._scheme + '://' + host;\n },\n };\n\n exports.URL = JURL;\n})();\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals requirejs, __non_webpack_require__ */\n/* eslint no-var: error */\n\nimport {\n assert, createPromiseCapability, getVerbosityLevel, info, InvalidPDFException,\n isArrayBuffer, isSameOrigin, MissingPDFException, NativeImageDecoding,\n PasswordException, setVerbosityLevel, shadow, stringToBytes,\n UnexpectedResponseException, UnknownErrorException, unreachable, URL, warn\n} from '../shared/util';\nimport {\n deprecated, DOMCanvasFactory, DOMCMapReaderFactory, DummyStatTimer,\n loadScript, PageViewport, releaseImageResources, RenderingCancelledException,\n StatTimer\n} from './display_utils';\nimport { FontFaceObject, FontLoader } from './font_loader';\nimport { apiCompatibilityParams } from './api_compatibility';\nimport { CanvasGraphics } from './canvas';\nimport globalScope from '../shared/global_scope';\nimport { GlobalWorkerOptions } from './worker_options';\nimport { MessageHandler } from '../shared/message_handler';\nimport { Metadata } from './metadata';\nimport { PDFDataTransportStream } from './transport_stream';\nimport { WebGLContext } from './webgl';\n\nconst DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536\n\nlet isWorkerDisabled = false;\nlet fallbackWorkerSrc;\n\nlet fakeWorkerFilesLoader = null;\nif (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('GENERIC')) {\n let useRequireEnsure = false;\n // For GENERIC build we need to add support for different fake file loaders\n // for different frameworks.\n if (typeof window === 'undefined') {\n // node.js - disable worker and set require.ensure.\n isWorkerDisabled = true;\n if (typeof __non_webpack_require__.ensure === 'undefined') {\n __non_webpack_require__.ensure = __non_webpack_require__('node-ensure');\n }\n useRequireEnsure = true;\n } else if (typeof __non_webpack_require__ !== 'undefined' &&\n typeof __non_webpack_require__.ensure === 'function') {\n useRequireEnsure = true;\n }\n if (typeof requirejs !== 'undefined' && requirejs.toUrl) {\n fallbackWorkerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');\n }\n const dynamicLoaderSupported =\n typeof requirejs !== 'undefined' && requirejs.load;\n fakeWorkerFilesLoader = useRequireEnsure ? (function() {\n return new Promise(function(resolve, reject) {\n __non_webpack_require__.ensure([], function() {\n try {\n let worker;\n if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('LIB')) {\n worker = __non_webpack_require__('../pdf.worker.js');\n } else {\n worker = __non_webpack_require__('./pdf.worker.js');\n }\n resolve(worker.WorkerMessageHandler);\n } catch (ex) {\n reject(ex);\n }\n }, reject, 'pdfjsWorker');\n });\n }) : dynamicLoaderSupported ? (function() {\n return new Promise(function(resolve, reject) {\n requirejs(['pdfjs-dist/build/pdf.worker'], function(worker) {\n try {\n resolve(worker.WorkerMessageHandler);\n } catch (ex) {\n reject(ex);\n }\n }, reject);\n });\n }) : null;\n\n if (!fallbackWorkerSrc && typeof document === 'object' &&\n 'currentScript' in document) {\n const pdfjsFilePath = document.currentScript && document.currentScript.src;\n if (pdfjsFilePath) {\n fallbackWorkerSrc =\n pdfjsFilePath.replace(/(\\.(?:min\\.)?js)(\\?.*)?$/i, '.worker$1$2');\n }\n }\n}\n\n/**\n * @typedef {function} IPDFStreamFactory\n * @param {DocumentInitParameters} params The document initialization\n * parameters. The \"url\" key is always present.\n * @return {IPDFStream}\n */\n\n/** @type IPDFStreamFactory */\nlet createPDFNetworkStream;\n\n/**\n * Sets the function that instantiates a IPDFStream as an alternative PDF data\n * transport.\n * @param {IPDFStreamFactory} pdfNetworkStreamFactory - the factory function\n * that takes document initialization parameters (including a \"url\") and returns\n * an instance of IPDFStream.\n */\nfunction setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {\n createPDFNetworkStream = pdfNetworkStreamFactory;\n}\n\n/**\n * Document initialization / loading parameters object.\n *\n * @typedef {Object} DocumentInitParameters\n * @property {string} url - The URL of the PDF.\n * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays\n * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,\n * use atob() to convert it to a binary string first.\n * @property {Object} httpHeaders - Basic authentication headers.\n * @property {boolean} withCredentials - Indicates whether or not cross-site\n * Access-Control requests should be made using credentials such as cookies\n * or authorization headers. The default is false.\n * @property {string} password - For decrypting password-protected PDFs.\n * @property {TypedArray} initialData - A typed array with the first portion or\n * all of the pdf data. Used by the extension since some data is already\n * loaded before the switch to range requests.\n * @property {number} length - The PDF file length. It's used for progress\n * reports and range requests operations.\n * @property {PDFDataRangeTransport} range\n * @property {number} rangeChunkSize - Optional parameter to specify\n * maximum number of bytes fetched per range request. The default value is\n * 2^16 = 65536.\n * @property {PDFWorker} worker - (optional) The worker that will be used for\n * the loading and parsing of the PDF data.\n * @property {boolean} postMessageTransfers - (optional) Enables transfer usage\n * in postMessage for ArrayBuffers. The default value is `true`.\n * @property {number} verbosity - (optional) Controls the logging level; the\n * constants from {VerbosityLevel} should be used.\n * @property {string} docBaseUrl - (optional) The base URL of the document,\n * used when attempting to recover valid absolute URLs for annotations, and\n * outline items, that (incorrectly) only specify relative URLs.\n * @property {string} nativeImageDecoderSupport - (optional) Strategy for\n * decoding certain (simple) JPEG images in the browser. This is useful for\n * environments without DOM image and canvas support, such as e.g. Node.js.\n * Valid values are 'decode', 'display' or 'none'; where 'decode' is intended\n * for browsers with full image/canvas support, 'display' for environments\n * with limited image support through stubs (useful for SVG conversion),\n * and 'none' where JPEG images will be decoded entirely by PDF.js.\n * The default value is 'decode'.\n * @property {string} cMapUrl - (optional) The URL where the predefined\n * Adobe CMaps are located. Include trailing slash.\n * @property {boolean} cMapPacked - (optional) Specifies if the Adobe CMaps are\n * binary packed.\n * @property {Object} CMapReaderFactory - (optional) The factory that will be\n * used when reading built-in CMap files. Providing a custom factory is useful\n * for environments without `XMLHttpRequest` support, such as e.g. Node.js.\n * The default value is {DOMCMapReaderFactory}.\n * @property {boolean} stopAtErrors - (optional) Reject certain promises, e.g.\n * `getOperatorList`, `getTextContent`, and `RenderTask`, when the associated\n * PDF data cannot be successfully parsed, instead of attempting to recover\n * whatever possible of the data. The default value is `false`.\n * @property {number} maxImageSize - (optional) The maximum allowed image size\n * in total pixels, i.e. width * height. Images above this value will not be\n * rendered. Use -1 for no limit, which is also the default value.\n * @property {boolean} isEvalSupported - (optional) Determines if we can eval\n * strings as JS. Primarily used to improve performance of font rendering,\n * and when parsing PDF functions. The default value is `true`.\n * @property {boolean} disableFontFace - (optional) By default fonts are\n * converted to OpenType fonts and loaded via font face rules. If disabled,\n * fonts will be rendered using a built-in font renderer that constructs the\n * glyphs with primitive path commands. The default value is `false`.\n * @property {boolean} disableRange - (optional) Disable range request loading\n * of PDF files. When enabled, and if the server supports partial content\n * requests, then the PDF will be fetched in chunks.\n * The default value is `false`.\n * @property {boolean} disableStream - (optional) Disable streaming of PDF file\n * data. By default PDF.js attempts to load PDFs in chunks.\n * The default value is `false`.\n * @property {boolean} disableAutoFetch - (optional) Disable pre-fetching of PDF\n * file data. When range requests are enabled PDF.js will automatically keep\n * fetching more data even if it isn't needed to display the current page.\n * The default value is `false`.\n * NOTE: It is also necessary to disable streaming, see above,\n * in order for disabling of pre-fetching to work correctly.\n * @property {boolean} disableCreateObjectURL - (optional) Disable the use of\n * `URL.createObjectURL`, for compatibility with older browsers.\n * The default value is `false`.\n * @property {boolean} pdfBug - (optional) Enables special hooks for debugging\n * PDF.js (see `web/debugger.js`). The default value is `false`.\n */\n\n/**\n * @typedef {Object} PDFDocumentStats\n * @property {Array} streamTypes - Used stream types in the document (an item\n * is set to true if specific stream ID was used in the document).\n * @property {Array} fontTypes - Used font type in the document (an item is set\n * to true if specific font ID was used in the document).\n */\n\n/**\n * This is the main entry point for loading a PDF and interacting with it.\n * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)\n * is used, which means it must follow the same origin rules that any XHR does\n * e.g. No cross domain requests without CORS.\n *\n * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src\n * Can be a url to where a PDF is located, a typed array (Uint8Array)\n * already populated with data or parameter object.\n *\n * @return {PDFDocumentLoadingTask}\n */\nfunction getDocument(src) {\n const task = new PDFDocumentLoadingTask();\n\n let source;\n if (typeof src === 'string') {\n source = { url: src, };\n } else if (isArrayBuffer(src)) {\n source = { data: src, };\n } else if (src instanceof PDFDataRangeTransport) {\n source = { range: src, };\n } else {\n if (typeof src !== 'object') {\n throw new Error('Invalid parameter in getDocument, ' +\n 'need either Uint8Array, string or a parameter object');\n }\n if (!src.url && !src.data && !src.range) {\n throw new Error(\n 'Invalid parameter object: need either .data, .range or .url');\n }\n source = src;\n }\n const params = Object.create(null);\n let rangeTransport = null, worker = null;\n\n for (const key in source) {\n if (key === 'url' && typeof window !== 'undefined') {\n // The full path is required in the 'url' field.\n params[key] = new URL(source[key], window.location).href;\n continue;\n } else if (key === 'range') {\n rangeTransport = source[key];\n continue;\n } else if (key === 'worker') {\n worker = source[key];\n continue;\n } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {\n // Converting string or array-like data to Uint8Array.\n const pdfBytes = source[key];\n if (typeof pdfBytes === 'string') {\n params[key] = stringToBytes(pdfBytes);\n } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&\n !isNaN(pdfBytes.length)) {\n params[key] = new Uint8Array(pdfBytes);\n } else if (isArrayBuffer(pdfBytes)) {\n params[key] = new Uint8Array(pdfBytes);\n } else {\n throw new Error('Invalid PDF binary data: either typed array, ' +\n 'string or array-like object is expected in the ' +\n 'data property.');\n }\n continue;\n }\n params[key] = source[key];\n }\n\n params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;\n params.CMapReaderFactory = params.CMapReaderFactory || DOMCMapReaderFactory;\n params.ignoreErrors = params.stopAtErrors !== true;\n params.pdfBug = params.pdfBug === true;\n\n const NativeImageDecoderValues = Object.values(NativeImageDecoding);\n if (params.nativeImageDecoderSupport === undefined ||\n !NativeImageDecoderValues.includes(params.nativeImageDecoderSupport)) {\n params.nativeImageDecoderSupport =\n (apiCompatibilityParams.nativeImageDecoderSupport ||\n NativeImageDecoding.DECODE);\n }\n if (!Number.isInteger(params.maxImageSize)) {\n params.maxImageSize = -1;\n }\n if (typeof params.isEvalSupported !== 'boolean') {\n params.isEvalSupported = true;\n }\n if (typeof params.disableFontFace !== 'boolean') {\n params.disableFontFace = apiCompatibilityParams.disableFontFace || false;\n }\n\n if (typeof params.disableRange !== 'boolean') {\n params.disableRange = false;\n }\n if (typeof params.disableStream !== 'boolean') {\n params.disableStream = false;\n }\n if (typeof params.disableAutoFetch !== 'boolean') {\n params.disableAutoFetch = false;\n }\n if (typeof params.disableCreateObjectURL !== 'boolean') {\n params.disableCreateObjectURL =\n apiCompatibilityParams.disableCreateObjectURL || false;\n }\n\n // Set the main-thread verbosity level.\n setVerbosityLevel(params.verbosity);\n\n if (!worker) {\n const workerParams = {\n postMessageTransfers: params.postMessageTransfers,\n verbosity: params.verbosity,\n port: GlobalWorkerOptions.workerPort,\n };\n // Worker was not provided -- creating and owning our own. If message port\n // is specified in global worker options, using it.\n worker = workerParams.port ? PDFWorker.fromPort(workerParams) :\n new PDFWorker(workerParams);\n task._worker = worker;\n }\n const docId = task.docId;\n worker.promise.then(function() {\n if (task.destroyed) {\n throw new Error('Loading aborted');\n }\n return _fetchDocument(worker, params, rangeTransport, docId).then(\n function(workerId) {\n if (task.destroyed) {\n throw new Error('Loading aborted');\n }\n\n let networkStream;\n if (rangeTransport) {\n networkStream = new PDFDataTransportStream({\n length: params.length,\n initialData: params.initialData,\n progressiveDone: params.progressiveDone,\n disableRange: params.disableRange,\n disableStream: params.disableStream,\n }, rangeTransport);\n } else if (!params.data) {\n networkStream = createPDFNetworkStream({\n url: params.url,\n length: params.length,\n httpHeaders: params.httpHeaders,\n withCredentials: params.withCredentials,\n rangeChunkSize: params.rangeChunkSize,\n disableRange: params.disableRange,\n disableStream: params.disableStream,\n });\n }\n\n const messageHandler = new MessageHandler(docId, workerId, worker.port);\n messageHandler.postMessageTransfers = worker.postMessageTransfers;\n const transport = new WorkerTransport(messageHandler, task, networkStream,\n params);\n task._transport = transport;\n messageHandler.send('Ready', null);\n });\n }).catch(task._capability.reject);\n\n return task;\n}\n\n/**\n * Starts fetching of specified PDF document/data.\n * @param {PDFWorker} worker\n * @param {Object} source\n * @param {PDFDataRangeTransport} pdfDataRangeTransport\n * @param {string} docId Unique document id, used as MessageHandler id.\n * @returns {Promise} The promise, which is resolved when worker id of\n * MessageHandler is known.\n * @private\n */\nfunction _fetchDocument(worker, source, pdfDataRangeTransport, docId) {\n if (worker.destroyed) {\n return Promise.reject(new Error('Worker was destroyed'));\n }\n\n if (pdfDataRangeTransport) {\n source.length = pdfDataRangeTransport.length;\n source.initialData = pdfDataRangeTransport.initialData;\n source.progressiveDone = pdfDataRangeTransport.progressiveDone;\n }\n return worker.messageHandler.sendWithPromise('GetDocRequest', {\n docId,\n apiVersion: (typeof PDFJSDev !== 'undefined' ?\n PDFJSDev.eval('BUNDLE_VERSION') : null),\n source: { // Only send the required properties, and *not* the entire object.\n data: source.data,\n url: source.url,\n password: source.password,\n disableAutoFetch: source.disableAutoFetch,\n rangeChunkSize: source.rangeChunkSize,\n length: source.length,\n },\n maxImageSize: source.maxImageSize,\n disableFontFace: source.disableFontFace,\n disableCreateObjectURL: source.disableCreateObjectURL,\n postMessageTransfers: worker.postMessageTransfers,\n docBaseUrl: source.docBaseUrl,\n nativeImageDecoderSupport: source.nativeImageDecoderSupport,\n ignoreErrors: source.ignoreErrors,\n isEvalSupported: source.isEvalSupported,\n }).then(function(workerId) {\n if (worker.destroyed) {\n throw new Error('Worker was destroyed');\n }\n return workerId;\n });\n}\n\n/**\n * PDF document loading operation.\n * @class\n * @alias PDFDocumentLoadingTask\n */\nconst PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {\n let nextDocumentId = 0;\n\n /** @constructs PDFDocumentLoadingTask */\n class PDFDocumentLoadingTask {\n constructor() {\n this._capability = createPromiseCapability();\n this._transport = null;\n this._worker = null;\n\n /**\n * Unique document loading task id -- used in MessageHandlers.\n * @type {string}\n */\n this.docId = 'd' + (nextDocumentId++);\n\n /**\n * Shows if loading task is destroyed.\n * @type {boolean}\n */\n this.destroyed = false;\n\n /**\n * Callback to request a password if wrong or no password was provided.\n * The callback receives two parameters: function that needs to be called\n * with new password and reason (see {PasswordResponses}).\n */\n this.onPassword = null;\n\n /**\n * Callback to be able to monitor the loading progress of the PDF file\n * (necessary to implement e.g. a loading bar). The callback receives\n * an {Object} with the properties: {number} loaded and {number} total.\n */\n this.onProgress = null;\n\n /**\n * Callback to when unsupported feature is used. The callback receives\n * an {UNSUPPORTED_FEATURES} argument.\n */\n this.onUnsupportedFeature = null;\n }\n\n /**\n * @return {Promise}\n */\n get promise() {\n return this._capability.promise;\n }\n\n /**\n * Aborts all network requests and destroys worker.\n * @return {Promise} A promise that is resolved after destruction activity\n * is completed.\n */\n destroy() {\n this.destroyed = true;\n\n const transportDestroyed = !this._transport ? Promise.resolve() :\n this._transport.destroy();\n return transportDestroyed.then(() => {\n this._transport = null;\n if (this._worker) {\n this._worker.destroy();\n this._worker = null;\n }\n });\n }\n\n /**\n * Registers callbacks to indicate the document loading completion.\n *\n * @param {function} onFulfilled The callback for the loading completion.\n * @param {function} onRejected The callback for the loading failure.\n * @return {Promise} A promise that is resolved after the onFulfilled or\n * onRejected callback.\n */\n then(onFulfilled, onRejected) {\n deprecated('PDFDocumentLoadingTask.then method, ' +\n 'use the `promise` getter instead.');\n return this.promise.then.apply(this.promise, arguments);\n }\n }\n return PDFDocumentLoadingTask;\n})();\n\n/**\n * Abstract class to support range requests file loading.\n * @param {number} length\n * @param {Uint8Array} initialData\n * @param {boolean} progressiveDone\n */\nclass PDFDataRangeTransport {\n constructor(length, initialData, progressiveDone = false) {\n this.length = length;\n this.initialData = initialData;\n this.progressiveDone = progressiveDone;\n\n this._rangeListeners = [];\n this._progressListeners = [];\n this._progressiveReadListeners = [];\n this._progressiveDoneListeners = [];\n this._readyCapability = createPromiseCapability();\n }\n\n addRangeListener(listener) {\n this._rangeListeners.push(listener);\n }\n\n addProgressListener(listener) {\n this._progressListeners.push(listener);\n }\n\n addProgressiveReadListener(listener) {\n this._progressiveReadListeners.push(listener);\n }\n\n addProgressiveDoneListener(listener) {\n this._progressiveDoneListeners.push(listener);\n }\n\n onDataRange(begin, chunk) {\n for (const listener of this._rangeListeners) {\n listener(begin, chunk);\n }\n }\n\n onDataProgress(loaded, total) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressListeners) {\n listener(loaded, total);\n }\n });\n }\n\n onDataProgressiveRead(chunk) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveReadListeners) {\n listener(chunk);\n }\n });\n }\n\n onDataProgressiveDone() {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveDoneListeners) {\n listener();\n }\n });\n }\n\n transportReady() {\n this._readyCapability.resolve();\n }\n\n requestDataRange(begin, end) {\n unreachable('Abstract method PDFDataRangeTransport.requestDataRange');\n }\n\n abort() {}\n}\n\n/**\n * Proxy to a PDFDocument in the worker thread. Also, contains commonly used\n * properties that can be read synchronously.\n */\nclass PDFDocumentProxy {\n constructor(pdfInfo, transport) {\n this._pdfInfo = pdfInfo;\n this._transport = transport;\n }\n\n /**\n * @return {number} Total number of pages the PDF contains.\n */\n get numPages() {\n return this._pdfInfo.numPages;\n }\n\n /**\n * @return {string} A (not guaranteed to be) unique ID to identify a PDF.\n */\n get fingerprint() {\n return this._pdfInfo.fingerprint;\n }\n\n /**\n * @param {number} pageNumber - The page number to get. The first page is 1.\n * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}\n * object.\n */\n getPage(pageNumber) {\n return this._transport.getPage(pageNumber);\n }\n\n /**\n * @param {{num: number, gen: number}} ref - The page reference. Must have\n * the `num` and `gen` properties.\n * @return {Promise} A promise that is resolved with the page index that is\n * associated with the reference.\n */\n getPageIndex(ref) {\n return this._transport.getPageIndex(ref);\n }\n\n /**\n * @return {Promise} A promise that is resolved with a lookup table for\n * mapping named destinations to reference numbers.\n *\n * This can be slow for large documents. Use `getDestination` instead.\n */\n getDestinations() {\n return this._transport.getDestinations();\n }\n\n /**\n * @param {string} id - The named destination to get.\n * @return {Promise} A promise that is resolved with all information\n * of the given named destination.\n */\n getDestination(id) {\n return this._transport.getDestination(id);\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Array} containing\n * the page labels that correspond to the page indexes, or `null` when\n * no page labels are present in the PDF file.\n */\n getPageLabels() {\n return this._transport.getPageLabels();\n }\n\n /**\n * @return {Promise} A promise that is resolved with a {string} containing\n * the page layout name.\n */\n getPageLayout() {\n return this._transport.getPageLayout();\n }\n\n /**\n * @return {Promise} A promise that is resolved with a {string} containing\n * the page mode name.\n */\n getPageMode() {\n return this._transport.getPageMode();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Object} containing\n * the viewer preferences.\n */\n getViewerPreferences() {\n return this._transport.getViewerPreferences();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Array} containing the\n * destination, or `null` when no open action is present in the PDF file.\n */\n getOpenActionDestination() {\n return this._transport.getOpenActionDestination();\n }\n\n /**\n * @return {Promise} A promise that is resolved with a lookup table for\n * mapping named attachments to their content.\n */\n getAttachments() {\n return this._transport.getAttachments();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Array} of all the\n * JavaScript strings in the name tree, or `null` if no JavaScript exists.\n */\n getJavaScript() {\n return this._transport.getJavaScript();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Array} that is a\n * tree outline (if it has one) of the PDF. The tree is in the format of:\n * [\n * {\n * title: string,\n * bold: boolean,\n * italic: boolean,\n * color: rgb Uint8ClampedArray,\n * count: integer or undefined,\n * dest: dest obj,\n * url: string,\n * items: array of more items like this\n * },\n * ...\n * ]\n */\n getOutline() {\n return this._transport.getOutline();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Array} that contains\n * the permission flags for the PDF document, or `null` when\n * no permissions are present in the PDF file.\n */\n getPermissions() {\n return this._transport.getPermissions();\n }\n\n /**\n * @return {Promise} A promise that is resolved with an {Object} that has\n * `info` and `metadata` properties. `info` is an {Object} filled with\n * anything available in the information dictionary and similarly\n * `metadata` is a {Metadata} object with information from the metadata\n * section of the PDF.\n */\n getMetadata() {\n return this._transport.getMetadata();\n }\n\n /**\n * @return {Promise} A promise that is resolved with a {TypedArray} that has\n * the raw data from the PDF.\n */\n getData() {\n return this._transport.getData();\n }\n\n /**\n * @return {Promise} A promise that is resolved when the document's data\n * is loaded. It is resolved with an {Object} that contains the `length`\n * property that indicates size of the PDF data in bytes.\n */\n getDownloadInfo() {\n return this._transport.downloadInfoCapability.promise;\n }\n\n /**\n * @return {Promise} A promise this is resolved with current statistics about\n * document structures (see {@link PDFDocumentStats}).\n */\n getStats() {\n return this._transport.getStats();\n }\n\n /**\n * Cleans up resources allocated by the document, e.g. created `@font-face`.\n */\n cleanup() {\n this._transport.startCleanup();\n }\n\n /**\n * Destroys the current document instance and terminates the worker.\n */\n destroy() {\n return this.loadingTask.destroy();\n }\n\n /**\n * @return {Object} A subset of the current {DocumentInitParameters},\n * which are either needed in the viewer and/or whose default values\n * may be affected by the `apiCompatibilityParams`.\n */\n get loadingParams() {\n return this._transport.loadingParams;\n }\n\n /**\n * @return {PDFDocumentLoadingTask} The loadingTask for the current document.\n */\n get loadingTask() {\n return this._transport.loadingTask;\n }\n}\n\n/**\n * Page getViewport parameters.\n *\n * @typedef {Object} GetViewportParameters\n * @property {number} scale - The desired scale of the viewport.\n * @property {number} rotation - (optional) The desired rotation, in degrees, of\n * the viewport. If omitted it defaults to the page rotation.\n * @property {boolean} dontFlip - (optional) If true, the y-axis will not be\n * flipped. The default value is `false`.\n */\n\n/**\n * Page getTextContent parameters.\n *\n * @typedef {Object} getTextContentParameters\n * @property {boolean} normalizeWhitespace - replaces all occurrences of\n * whitespace with standard spaces (0x20). The default value is `false`.\n * @property {boolean} disableCombineTextItems - do not attempt to combine\n * same line {@link TextItem}'s. The default value is `false`.\n */\n\n/**\n * Page text content.\n *\n * @typedef {Object} TextContent\n * @property {array} items - array of {@link TextItem}\n * @property {Object} styles - {@link TextStyle} objects, indexed by font name.\n */\n\n/**\n * Page text content part.\n *\n * @typedef {Object} TextItem\n * @property {string} str - text content.\n * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.\n * @property {array} transform - transformation matrix.\n * @property {number} width - width in device space.\n * @property {number} height - height in device space.\n * @property {string} fontName - font name used by pdf.js for converted font.\n */\n\n/**\n * Text style.\n *\n * @typedef {Object} TextStyle\n * @property {number} ascent - font ascent.\n * @property {number} descent - font descent.\n * @property {boolean} vertical - text is in vertical mode.\n * @property {string} fontFamily - possible font family\n */\n\n/**\n * Page annotation parameters.\n *\n * @typedef {Object} GetAnnotationsParameters\n * @property {string} intent - Determines the annotations that will be fetched,\n * can be either 'display' (viewable annotations) or 'print'\n * (printable annotations).\n * If the parameter is omitted, all annotations are fetched.\n */\n\n/**\n * Page render parameters.\n *\n * @typedef {Object} RenderParameters\n * @property {Object} canvasContext - A 2D context of a DOM Canvas object.\n * @property {PageViewport} viewport - Rendering viewport obtained by\n * calling the `PDFPageProxy.getViewport` method.\n * @property {string} intent - Rendering intent, can be 'display' or 'print'\n * (default value is 'display').\n * @property {boolean} enableWebGL - (optional) Enables WebGL accelerated\n * rendering for some operations. The default value is `false`.\n * @property {boolean} renderInteractiveForms - (optional) Whether or not\n * interactive form elements are rendered in the display\n * layer. If so, we do not render them on canvas as well.\n * @property {Array} transform - (optional) Additional transform, applied\n * just before viewport transform.\n * @property {Object} imageLayer - (optional) An object that has beginLayout,\n * endLayout and appendImage functions.\n * @property {Object} canvasFactory - (optional) The factory that will be used\n * when creating canvases. The default value is\n * {DOMCanvasFactory}.\n * @property {Object} background - (optional) Background to use for the canvas.\n * Can use any valid canvas.fillStyle: A DOMString parsed as\n * CSS value, a CanvasGradient object (a linear or\n * radial gradient) or a CanvasPattern object (a repetitive\n * image). The default value is 'rgb(255,255,255)'.\n */\n\n/**\n * PDF page operator list.\n *\n * @typedef {Object} PDFOperatorList\n * @property {Array} fnArray - Array containing the operator functions.\n * @property {Array} argsArray - Array containing the arguments of the\n * functions.\n */\n\n/**\n * Proxy to a PDFPage in the worker thread.\n * @alias PDFPageProxy\n */\nclass PDFPageProxy {\n constructor(pageIndex, pageInfo, transport, pdfBug = false) {\n this.pageIndex = pageIndex;\n this._pageInfo = pageInfo;\n this._transport = transport;\n this._stats = (pdfBug ? new StatTimer() : DummyStatTimer);\n this._pdfBug = pdfBug;\n this.commonObjs = transport.commonObjs;\n this.objs = new PDFObjects();\n\n this.cleanupAfterRender = false;\n this.pendingCleanup = false;\n this.intentStates = Object.create(null);\n this.destroyed = false;\n }\n\n /**\n * @return {number} Page number of the page. First page is 1.\n */\n get pageNumber() {\n return this.pageIndex + 1;\n }\n\n /**\n * @return {number} The number of degrees the page is rotated clockwise.\n */\n get rotate() {\n return this._pageInfo.rotate;\n }\n\n /**\n * @return {Object} The reference that points to this page. It has 'num' and\n * 'gen' properties.\n */\n get ref() {\n return this._pageInfo.ref;\n }\n\n /**\n * @return {number} The default size of units in 1/72nds of an inch.\n */\n get userUnit() {\n return this._pageInfo.userUnit;\n }\n\n /**\n * @return {Array} An array of the visible portion of the PDF page in the\n * user space units - [x1, y1, x2, y2].\n */\n get view() {\n return this._pageInfo.view;\n }\n\n /**\n * @param {GetViewportParameters} params - Viewport parameters.\n * @return {PageViewport} Contains 'width' and 'height' properties\n * along with transforms required for rendering.\n */\n getViewport({ scale, rotation = this.rotate, dontFlip = false, } = {}) {\n if ((typeof PDFJSDev !== 'undefined' && PDFJSDev.test('GENERIC')) &&\n (arguments.length > 1 || typeof arguments[0] === 'number')) {\n deprecated('getViewport is called with obsolete arguments.');\n scale = arguments[0];\n rotation = typeof arguments[1] === 'number' ? arguments[1] : this.rotate;\n dontFlip = typeof arguments[2] === 'boolean' ? arguments[2] : false;\n }\n return new PageViewport({\n viewBox: this.view,\n scale,\n rotation,\n dontFlip,\n });\n }\n\n /**\n * @param {GetAnnotationsParameters} params - Annotation parameters.\n * @return {Promise} A promise that is resolved with an {Array} of the\n * annotation objects.\n */\n getAnnotations({ intent = null, } = {}) {\n if (!this.annotationsPromise || this.annotationsIntent !== intent) {\n this.annotationsPromise = this._transport.getAnnotations(this.pageIndex,\n intent);\n this.annotationsIntent = intent;\n }\n return this.annotationsPromise;\n }\n\n /**\n * Begins the process of rendering a page to the desired context.\n * @param {RenderParameters} params Page render parameters.\n * @return {RenderTask} An object that contains the promise, which\n * is resolved when the page finishes rendering.\n */\n render({ canvasContext, viewport, intent = 'display', enableWebGL = false,\n renderInteractiveForms = false, transform = null, imageLayer = null,\n canvasFactory = null, background = null, }) {\n const stats = this._stats;\n stats.time('Overall');\n\n // If there was a pending destroy, cancel it so no cleanup happens during\n // this call to render.\n this.pendingCleanup = false;\n\n const renderingIntent = (intent === 'print' ? 'print' : 'display');\n const canvasFactoryInstance = canvasFactory || new DOMCanvasFactory();\n const webGLContext = new WebGLContext({\n enable: enableWebGL,\n });\n\n if (!this.intentStates[renderingIntent]) {\n this.intentStates[renderingIntent] = Object.create(null);\n }\n const intentState = this.intentStates[renderingIntent];\n\n // If there's no displayReadyCapability yet, then the operatorList\n // was never requested before. Make the request and create the promise.\n if (!intentState.displayReadyCapability) {\n intentState.receivingOperatorList = true;\n intentState.displayReadyCapability = createPromiseCapability();\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n };\n\n stats.time('Page Request');\n this._transport.messageHandler.send('RenderPageRequest', {\n pageIndex: this.pageNumber - 1,\n intent: renderingIntent,\n renderInteractiveForms: renderInteractiveForms === true,\n });\n }\n\n const complete = (error) => {\n const i = intentState.renderTasks.indexOf(internalRenderTask);\n if (i >= 0) {\n intentState.renderTasks.splice(i, 1);\n }\n\n // Attempt to reduce memory usage during *printing*, by always running\n // cleanup once rendering has finished (regardless of cleanupAfterRender).\n if (this.cleanupAfterRender || renderingIntent === 'print') {\n this.pendingCleanup = true;\n }\n this._tryCleanup();\n\n if (error) {\n internalRenderTask.capability.reject(error);\n } else {\n internalRenderTask.capability.resolve();\n }\n stats.timeEnd('Rendering');\n stats.timeEnd('Overall');\n };\n\n const internalRenderTask = new InternalRenderTask({\n callback: complete,\n params: { // Include the required properties, and *not* the entire object.\n canvasContext,\n viewport,\n transform,\n imageLayer,\n background,\n },\n objs: this.objs,\n commonObjs: this.commonObjs,\n operatorList: intentState.operatorList,\n pageNumber: this.pageNumber,\n canvasFactory: canvasFactoryInstance,\n webGLContext,\n useRequestAnimationFrame: renderingIntent !== 'print',\n pdfBug: this._pdfBug,\n });\n\n if (!intentState.renderTasks) {\n intentState.renderTasks = [];\n }\n intentState.renderTasks.push(internalRenderTask);\n const renderTask = internalRenderTask.task;\n\n intentState.displayReadyCapability.promise.then((transparency) => {\n if (this.pendingCleanup) {\n complete();\n return;\n }\n stats.time('Rendering');\n internalRenderTask.initializeGraphics(transparency);\n internalRenderTask.operatorListChanged();\n }).catch(complete);\n\n return renderTask;\n }\n\n /**\n * @return {Promise} A promise resolved with an {@link PDFOperatorList}\n * object that represents page's operator list.\n */\n getOperatorList() {\n function operatorListChanged() {\n if (intentState.operatorList.lastChunk) {\n intentState.opListReadCapability.resolve(intentState.operatorList);\n\n const i = intentState.renderTasks.indexOf(opListTask);\n if (i >= 0) {\n intentState.renderTasks.splice(i, 1);\n }\n }\n }\n\n const renderingIntent = 'oplist';\n if (!this.intentStates[renderingIntent]) {\n this.intentStates[renderingIntent] = Object.create(null);\n }\n const intentState = this.intentStates[renderingIntent];\n let opListTask;\n\n if (!intentState.opListReadCapability) {\n opListTask = {};\n opListTask.operatorListChanged = operatorListChanged;\n intentState.receivingOperatorList = true;\n intentState.opListReadCapability = createPromiseCapability();\n intentState.renderTasks = [];\n intentState.renderTasks.push(opListTask);\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n };\n\n this._stats.time('Page Request');\n this._transport.messageHandler.send('RenderPageRequest', {\n pageIndex: this.pageIndex,\n intent: renderingIntent,\n });\n }\n return intentState.opListReadCapability.promise;\n }\n\n /**\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @return {ReadableStream} ReadableStream to read textContent chunks.\n */\n streamTextContent({ normalizeWhitespace = false,\n disableCombineTextItems = false, } = {}) {\n const TEXT_CONTENT_CHUNK_SIZE = 100;\n\n return this._transport.messageHandler.sendWithStream('GetTextContent', {\n pageIndex: this.pageNumber - 1,\n normalizeWhitespace: normalizeWhitespace === true,\n combineTextItems: disableCombineTextItems !== true,\n }, {\n highWaterMark: TEXT_CONTENT_CHUNK_SIZE,\n size(textContent) {\n return textContent.items.length;\n },\n });\n }\n\n /**\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @return {Promise} That is resolved a {@link TextContent}\n * object that represent the page text content.\n */\n getTextContent(params = {}) {\n const readableStream = this.streamTextContent(params);\n\n return new Promise(function(resolve, reject) {\n function pump() {\n reader.read().then(function({ value, done, }) {\n if (done) {\n resolve(textContent);\n return;\n }\n Object.assign(textContent.styles, value.styles);\n textContent.items.push(...value.items);\n pump();\n }, reject);\n }\n\n const reader = readableStream.getReader();\n const textContent = {\n items: [],\n styles: Object.create(null),\n };\n pump();\n });\n }\n\n /**\n * Destroys page object.\n */\n _destroy() {\n this.destroyed = true;\n this._transport.pageCache[this.pageIndex] = null;\n\n const waitOn = [];\n Object.keys(this.intentStates).forEach(function(intent) {\n if (intent === 'oplist') {\n // Avoid errors below, since the renderTasks are just stubs.\n return;\n }\n const intentState = this.intentStates[intent];\n intentState.renderTasks.forEach(function(renderTask) {\n const renderCompleted = renderTask.capability.promise.\n catch(function() {}); // ignoring failures\n waitOn.push(renderCompleted);\n renderTask.cancel();\n });\n }, this);\n this.objs.clear();\n this.annotationsPromise = null;\n this.pendingCleanup = false;\n return Promise.all(waitOn);\n }\n\n /**\n * Cleans up resources allocated by the page.\n * @param {boolean} resetStats - (optional) Reset page stats, if enabled.\n * The default value is `false`.\n */\n cleanup(resetStats = false) {\n this.pendingCleanup = true;\n this._tryCleanup(resetStats);\n }\n\n /**\n * For internal use only. Attempts to clean up if rendering is in a state\n * where that's possible.\n * @ignore\n */\n _tryCleanup(resetStats = false) {\n if (!this.pendingCleanup ||\n Object.keys(this.intentStates).some(function(intent) {\n const intentState = this.intentStates[intent];\n return (intentState.renderTasks.length !== 0 ||\n intentState.receivingOperatorList);\n }, this)) {\n return;\n }\n\n Object.keys(this.intentStates).forEach(function(intent) {\n delete this.intentStates[intent];\n }, this);\n this.objs.clear();\n this.annotationsPromise = null;\n if (resetStats && this._stats instanceof StatTimer) {\n this._stats = new StatTimer();\n }\n this.pendingCleanup = false;\n }\n\n /**\n * For internal use only.\n * @ignore\n */\n _startRenderPage(transparency, intent) {\n const intentState = this.intentStates[intent];\n // TODO Refactor RenderPageRequest to separate rendering\n // and operator list logic\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.resolve(transparency);\n }\n }\n\n /**\n * For internal use only.\n * @ignore\n */\n _renderPageChunk(operatorListChunk, intent) {\n const intentState = this.intentStates[intent];\n // Add the new chunk to the current operator list.\n for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {\n intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);\n intentState.operatorList.argsArray.push(\n operatorListChunk.argsArray[i]);\n }\n intentState.operatorList.lastChunk = operatorListChunk.lastChunk;\n\n // Notify all the rendering tasks there are more operators to be consumed.\n for (let i = 0; i < intentState.renderTasks.length; i++) {\n intentState.renderTasks[i].operatorListChanged();\n }\n\n if (operatorListChunk.lastChunk) {\n intentState.receivingOperatorList = false;\n this._tryCleanup();\n }\n }\n\n /**\n * @return {Object} Returns page stats, if enabled.\n */\n get stats() {\n return (this._stats instanceof StatTimer ? this._stats : null);\n }\n}\n\nclass LoopbackPort {\n constructor(defer = true) {\n this._listeners = [];\n this._defer = defer;\n this._deferred = Promise.resolve(undefined);\n }\n\n postMessage(obj, transfers) {\n function cloneValue(value) {\n // Trying to perform a structured clone close to the spec, including\n // transfers.\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (cloned.has(value)) { // already cloned the object\n return cloned.get(value);\n }\n let buffer, result;\n if ((buffer = value.buffer) && isArrayBuffer(buffer)) {\n // We found object with ArrayBuffer (typed array).\n const transferable = transfers && transfers.includes(buffer);\n if (value === buffer) {\n // Special case when we are faking typed arrays in compatibility.js.\n result = value;\n } else if (transferable) {\n result = new value.constructor(buffer, value.byteOffset,\n value.byteLength);\n } else {\n result = new value.constructor(value);\n }\n cloned.set(value, result);\n return result;\n }\n result = Array.isArray(value) ? [] : {};\n cloned.set(value, result); // adding to cache now for cyclic references\n // Cloning all value and object properties, however ignoring properties\n // defined via getter.\n for (const i in value) {\n let desc, p = value;\n while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {\n p = Object.getPrototypeOf(p);\n }\n if (typeof desc.value === 'undefined' ||\n typeof desc.value === 'function') {\n continue;\n }\n result[i] = cloneValue(desc.value);\n }\n return result;\n }\n\n if (!this._defer) {\n this._listeners.forEach(function(listener) {\n listener.call(this, { data: obj, });\n }, this);\n return;\n }\n\n const cloned = new WeakMap();\n const e = { data: cloneValue(obj), };\n this._deferred.then(() => {\n this._listeners.forEach(function(listener) {\n listener.call(this, e);\n }, this);\n });\n }\n\n addEventListener(name, listener) {\n this._listeners.push(listener);\n }\n\n removeEventListener(name, listener) {\n const i = this._listeners.indexOf(listener);\n this._listeners.splice(i, 1);\n }\n\n terminate() {\n this._listeners.length = 0;\n }\n}\n\n/**\n * @typedef {Object} PDFWorkerParameters\n * @property {string} name - (optional) The name of the worker.\n * @property {Object} port - (optional) The `workerPort`.\n * @property {boolean} postMessageTransfers - (optional) Enables transfer usage\n * in postMessage for ArrayBuffers. The default value is `true`.\n * @property {number} verbosity - (optional) Controls the logging level; the\n * constants from {VerbosityLevel} should be used.\n */\n\n/**\n * PDF.js web worker abstraction, it controls instantiation of PDF documents and\n * WorkerTransport for them. If creation of a web worker is not possible,\n * a \"fake\" worker will be used instead.\n * @class\n */\nconst PDFWorker = (function PDFWorkerClosure() {\n const pdfWorkerPorts = new WeakMap();\n let nextFakeWorkerId = 0;\n let fakeWorkerFilesLoadedCapability;\n\n function getWorkerSrc() {\n if (GlobalWorkerOptions.workerSrc) {\n return GlobalWorkerOptions.workerSrc;\n }\n if (typeof fallbackWorkerSrc !== 'undefined') {\n return fallbackWorkerSrc;\n }\n throw new Error('No \"GlobalWorkerOptions.workerSrc\" specified.');\n }\n\n function getMainThreadWorkerMessageHandler() {\n try {\n if (typeof window !== 'undefined') {\n return (window.pdfjsWorker && window.pdfjsWorker.WorkerMessageHandler);\n }\n } catch (ex) { }\n return null;\n }\n\n // Loads worker code into main thread.\n function setupFakeWorkerGlobal() {\n if (fakeWorkerFilesLoadedCapability) {\n return fakeWorkerFilesLoadedCapability.promise;\n }\n fakeWorkerFilesLoadedCapability = createPromiseCapability();\n\n const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();\n if (mainWorkerMessageHandler) {\n // The worker was already loaded using a `