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,KAAK22C,eAAiBvyB,EAASwyB,KAAO,IAAIhzB,KAAKQ,EAASwyB,MAAQ,IAAIhzB,KACpEtN,OAAOwI,eAAe9e,KAAM,MAAO,CAAE6e,YAAc,EAAOtR,QAAe6W,IACzE9N,OAAOwI,eAAe9e,KAAM,SAAU,CAAE6e,YAAc,EAAOtR,MAAQ,MAAO,IAAM2R,EAAU/P,OAAOnP,KAAO,GAC9G,CAEA,YAAI2M,GAAa,OAAO3M,KAAK6sB,cAAclgB,QAAU,CAErD,OAAIyQ,GAAQ,MAAO,CAAC,CAAG,CAMvBtQ,IAAIoC,EAASkV,GACT,IAAInX,EACJjN,KAAKmC,GAAKiiB,EAASjiB,GACnBnC,KAAK6sB,cAAgB3d,EACrBlP,KAAKwd,WAA4C,QAA9BvQ,EAAKmX,EAAS5G,kBAA+B,IAAPvQ,EAAgBA,EAAK,GAC9EjN,KAAK0c,cAAgB0H,EAAStB,eAC9B9iB,KAAKy2C,mBAAqB,CAACryB,EAAShV,aACpCpP,KAAK02C,QAAUtyB,EAASsyB,OAC5B,CAEAvnC,SACI,OAAOwI,EAAU3X,UAAM,OAAQ,EAAQ,YAAe,EAC1D,EAGR,CA5CA,CA4CGyL,IAAgBA,EAAc,CAAC","names":["SubscriptionLabelComponent","_SubscriptionLabelComponent","constructor","store","this","subscriptionLabelTranslateKey$","select","selectSubscriptionLevelLabelTranslateKey","i0","i1","selectors","standalone","features","decls","vars","template","rf","ctx","AsyncPipe","TranslatePipe","SubscriptionDetailComponent_div_0_div_19_ng_template_1_Template","SubscriptionDetailComponent_div_0_div_19_p_3_Template","_r4","subscription_r2","ngIf","ctx_r2","editSubscription","proSubId","eventsSubIds","length","noEventsProTpl_r5","SubscriptionDetailComponent_div_0_ng_template_20_p_0_Template","SubscriptionDetailComponent_div_0_ng_template_20_ng_template_1_Template","_r6","subscribe","noEventTpl_r7","_c0","routeProjectDetail","project_r8","id","title","tmp_12_0","undefined","subscription","cf_project_name","expires","renews","eventDate","_r9","$implicit","editEventSubscription","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_ion_button_2_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_ng_template_3_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_div_12_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_div_13_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_div_14_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_ion_button_17_Template","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_ng_template_18_Template","noId_r10","tmp_13_0","subLevel","subscriptionLevel","eventConfig","canEdit","subscriptionId","includes","noEditTpl_r11","SubscriptionDetailComponent_div_0_div_27_div_1_ion_item_5_Template","eventProjects_r12","SubscriptionDetailComponent_div_0_div_27_div_1_Template","_r13","addMinutes","minutes$","_r14","openBillingInfo","openPaymentMethods","openPurchaseHistory","SubscriptionDetailComponent_div_0_ng_container_28_ion_item_1_Template","SubscriptionDetailComponent_div_0_ng_container_28_ng_container_2_Template","minutesEnabled","isActive","_r1","subscriptionActionClick","SubscriptionDetailComponent_div_0_div_19_Template","SubscriptionDetailComponent_div_0_ng_template_20_Template","SubscriptionDetailComponent_div_0_div_27_Template","SubscriptionDetailComponent_div_0_ng_container_28_Template","name","notActiveDetail_r15","myEventProjectsVm","SubscriptionDetailComponent","_SubscriptionDetailComponent","userService","projectService","billingService","modalCtrl","navCtrl","subscriptionSignalVm","selectSignal","selectSubscriptionStatus","myEventProjectsSignal","selectEventSubscriptionProjects","userIdSignal","toSignal","userId$","computed","userId","filter","p","map","project","level","getEventSubscriptionDetail","isProjectAdmin","eventIsActive","isSubscriptionActive","selectMinutes","isPro$","selectIsPro","ENABLE_BILLING_MINUTES","PROJECT_DETAIL_ROUTE","_this","_asyncToGenerator","console","log","event","navigateForward","SIGNUP_RETURN_URL_PRO","_this2","openEditSubscription","_this3","modal","create","component","PlansModalComponent","componentProps","cssClass","present","data","onWillDismiss","openCheckout","warn","viewPlans","error","i2","i3","i4","i5","consts","SubscriptionDetailComponent_div_0_Template","NgIf","NgFor","RouterLink","UpperCasePipe","DatePipe","ButtonComponent","IonList","IonItem","IonLabel","IonNote","IonButton","IonIcon","IonGrid","IonRow","IonCol","styles","StudioArchiveModal","_StudioArchiveModal","dismiss","dismissed","navHelp","HELP_ROUTE","archive","inputs","NATIVE_APP_STORE_KEY_WEDDING","NATIVE_APP_STORE_KEY_PRO_ANNUALLY","NATIVE_APP_STORE_KEY_PRO_MONTHLY","NativeAppStoreService","_NativeAppStoreService","alertController","plt","products","signal","enabled","isPro","hasWedding","hasEvent","errorMessage","cdvPlatform","CdvPurchase","Platform","TEST","changeDetectionEmitter","EventEmitter","ready","then","Capacitor","isNativePlatform","verbosity","LogLevel","DEBUG","getPlatform","APPLE_APPSTORE","GOOGLE_PLAY","registerProducts","setupListeners","initialize","platform","options","needAppReceipt","set","getProductState","product","_a","findInLocalReceipts","state","TransactionState","UNKNOWN_STATE","productId","get","Error","getOffer","order","code","ErrorCode","PAYMENT_CANCELLED","hasActiveSubscription","owned","restore","restorePurchases","presentAlert","header","message","buttons","register","type","ProductType","NON_RENEWING_SUBSCRIPTION","PAID_SUBSCRIPTION","emit","when","productUpdated","refreshUI","approved","finishPurchase","verified","receipt","finish","transaction","find","verify","factory","ɵfac","providedIn","p_r3","_r2","ctx_r3","purchase","description","pricing","price","currency","NativeAppStoreComponent_div_0_ion_item_11_Template","NativeAppStoreComponent","_NativeAppStoreComponent","appStoreService","cdRef","detectChanges","err","NativeAppStoreComponent_div_0_Template","ctx_r1","cancel","EditStudioPage_ion_grid_2_ion_row_13_Template","isBusy","usernameMinLength","usernameMaxLength","usernamePatternDesc","EditStudioPage_ion_grid_7_div_21_div_1_Template","EditStudioPage_ion_grid_7_div_21_div_2_Template","EditStudioPage_ion_grid_7_div_21_div_3_Template","profileForm","errors","minlength","maxlength","pattern","email_r5","changePassword","EditStudioPage_ion_grid_7_ion_col_7_Template","_r3","save","EditStudioPage_ion_grid_7_div_21_Template","EditStudioPage_ion_grid_7_fs_button_37_Template","avatarUrl$","enableBilling","loading","invalid","dirty","touched","email$","EditStudioPage","_EditStudioPage","formBuilder","toaster","router","translate","ENABLE_BILLING","group","handle","Validators","compose","minLength","maxLength","bio","location","value","disabled","required","email","onDestroy$","Subject","ngOnInit","addIcons","imagesOutline","icons","dFz","archiveOutline","loggedIn$","isLoggedIn$","pipe","take","res","obs","field","username$","bio$","location$","forEach","takeUntil","val","updateProp","ngAfterViewInit","showTutorial","getCurrentNavigation","extras","tutorial","ngOnDestroy","next","complete","valid","controls","didSave","setUsername","replace","trim","setBio","setLocation","navigateBack","STUDIO_PAGE","key","patchValue","m","getErrorMessage","Object","keys","instant","Boolean","onDidDismiss","changeEmail","FORGOT_PASS_PAGE","i6","EditStudioPage_ion_grid_2_Template","EditStudioPage_ng_template_5_Template","EditStudioPage_ion_grid_7_Template","notAuthed_r6","FormsModule","ReactiveFormsModule","FormControlCastPipe","FormInputComponent","FormTextareaComponent","TopNavbarComponent","EditableAvatarComponent","IonHeader","IonContent","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","step","e","rejected","throw","result","done","adopt","apply","initCDVPurchase","oldStore","window","Store","assign","SETUP","ERROR_CODES_BASE","LOAD","PURCHASE","LOAD_RECEIPTS","CLIENT_INVALID","PAYMENT_INVALID","PAYMENT_NOT_ALLOWED","UNKNOWN","REFRESH_RECEIPTS","INVALID_PRODUCT_ID","FINISH","COMMUNICATION","SUBSCRIPTIONS_NOT_AVAILABLE","MISSING_TOKEN","VERIFICATION_FAILED","BAD_RESPONSE","REFRESH","PAYMENT_EXPIRED","DOWNLOAD","SUBSCRIPTION_UPDATE_NOT_AVAILABLE","PRODUCT_NOT_AVAILABLE","CLOUD_SERVICE_PERMISSION_DENIED","CLOUD_SERVICE_NETWORK_CONNECTION_FAILED","CLOUD_SERVICE_REVOKED","PRIVACY_ACKNOWLEDGEMENT_REQUIRED","UNAUTHORIZED_REQUEST_DATA","INVALID_OFFER_IDENTIFIER","INVALID_OFFER_PRICE","INVALID_SIGNATURE","MISSING_OFFER_PARAMS","VALIDATOR_SUBSCRIPTION_EXPIRED","storeError","isError","Iaptic","config","url","child","braintreeClientTokenProvider","callback","info","Utils","ajax","appName","apiKey","method","applicationUsername","getApplicationUsername","customerId","Braintree","success","body","JSON","stringify","clientToken","BRAINTREE","appStoreDiscountEligibilityDeterminer","latestReceipt","debug","determiner","_appStoreReceipt","requests","analyzeReceipt","onVerified","off","cacheReceipt","ineligibleIntro","raw","ineligible_for_intro_price","request","discountType","collection","validator","QUIET","ERROR","WARNING","INFO","Logger","prefix","o","toString","stack","logCallbackException","context","fileName","lineNumber","LOG_LEVEL_STRING","fullPrefix","str","nonEnumerable","target","desc","enumerable","defineProperty","writable","configurable","Product","decorator","className","offers","pricingPhases","canPurchase","addOffer","offer","push","objectValues","obj","ret","hasOwnProperty","platformName","WINDOWS_STORE","Internal","ReceiptsToValidate","array","concat","add","has","clear","pop","el","Validator","controller","receiptsToValidate","verifiedReceipts","numRequests","numResponses","cache","incrRequestsCounter","incrResponsesCounter","addVerifiedReceipt","vr","newVR","VerifiedReceipt","receiptOrTransaction","Transaction","parentReceipt","run","receipts","onResponse","r","payload","adapter","adapters","handleReceiptValidationResponse","ok","verifiedCallbacks","trigger","transactionId","lastTransaction","col","isExpired","unverifiedCallbacks","runOnReceipt","_b","Test","Adapter","transactions","latest_receipt","buildRequestBody","runValidatorFunction","runValidatorRequest","timeout","_c","receiptValidationBody","additionalData","device","getDeviceInfo","priceMicros","introPriceMicros","removeExpiredCache","now","Date","deleteList","hash","bodyTransactionHash","md5","cached","customHeaders","headers","response","isValidatorResponsePayload","status","fullMessage","Adapters","list","po","AppleAppStore","GooglePlay","platforms","newPlatforms","registeredProducts","byPlatform","all","platformToInit","platformProducts","isSupported","initResult","loadProductsResult","loadReceiptsResult","supportsParallelLoading","loadProducts","loadReceipts","loadedProducts","listener","productsUpdated","lr","a","findReady","StoreAdapterListener","delegate","supportedPlatforms","platformWithReceiptsReady","lastTransactionState","lastCallTimeForState","updatedReceiptsToProcess","makeTransactionToken","setSupportedPlatforms","join","receiptsReadyCallbacks","receiptsReady","indexOf","updatedCallbacks","receiptsUpdated","updatedReceiptsProcessor","clearTimeout","setTimeout","_processUpdatedReceipts","updatedReceiptCallbacks","transactionToken","tokenWithState","lastState","APPROVED","lastCalled","approvedCallbacks","Math","round","INITIATED","initiatedCallbacks","FINISHED","finishedCallbacks","PENDING","pendingCallbacks","Callbacks","logger","finalStateMode","callbacks","numTriggers","callbackName","lastTriggerArgument","existing","reason","safeCall","remove","ReadyCallbacks","isReady","readyCallbacks","cb","RegisteredProducts","rp","newProducts","Array","isArray","TransactionStateMonitors","monitors","isListening","findMonitors","monitor","startListening","callOnChange","finished","lastChange","onChange","start","monitorId","uuidv4","stop","ReceiptsMonitor","hasCalledReceiptsVerified","callReceiptsVerified","receiptsVerified","launch","check","numValidationResponses","numValidationRequests","intervalChecker","clearInterval","unverified","hasLocalReceipts","hasValidator","setInterval","ExpiryMonitor","activePurchases","notifiedPurchases","interval","gracePeriod","GRACE_PERIOD_MS","DEFAULT","expiryDate","onVerifiedPurchaseExpired","INTERVAL_MS","PLUGIN_VERSION","_readyCallbacks","updatedReceiptsCallbacks","receiptsVerifiedCallbacks","errorCallbacks","initializedHasBeenCalled","lastUpdate","minTimeBetweenUpdates","version","transactionStateMonitors","_validator","bind","localReceipts","validator_privacy_policy","expiryMonitor","verifiedPurchase","sourceReceipt","getAdapter","Function","defaultPlatform","triggerError","apiDecorators","refresh","update","registration","receiptUpdated","updated","initiated","pending","safeCallback","localTransactions","verifiedPurchases","VerifiedReceipts","getVerifiedPurchases","findInVerifiedReceipts","LocalReceipts","Offer","checkSupport","requestPayment","paymentRequest","_d","_e","PaymentRequestPromise","failed","amountMicros","item","items","promise","functionality","Receipt","manageSubscriptions","manageBilling","platformId","cordova","RecurrenceMode","PaymentMode","RenewalIntent","PriceConsentStatus","CancelationReason","CONSUMABLE","NON_CONSUMABLE","FREE_SUBSCRIPTION","APPLICATION","NON_RECURRING","FINITE_RECURRING","INFINITE_RECURRING","PAY_AS_YOU_GO","UP_FRONT","FREE_TRIAL","CANCELLED","LAPSE","RENEW","NOTIFIED","AGREED","NOT_CANCELED","DEVELOPER","SYSTEM","SYSTEM_REPLACED","SYSTEM_PRODUCT_UNAVAILABLE","SYSTEM_BILLING_ERROR","SYSTEM_DELETED","CUSTOMER","CUSTOMER_TECHNICAL_ISSUES","CUSTOMER_PRICE_INCREASE","CUSTOMER_COST","CUSTOMER_FOUND_BETTER_APP","CUSTOMER_NOT_USEFUL_ENOUGH","CUSTOMER_OTHER_REASON","productType","productGroup","failedCallbacks","PromiseLike","cancelledCallback","cancelled","argument","hasTransaction","t","found","trProducts","purchaseDate","isOwned","isConsumed","isPending","expirationDate","getTime","resolved","resolvedArgument","Retry","minTimeout","maxTimeout","retryTimeout","retries","document","addEventListener","i","tid","fn","call","retry","indexed","lastRenewalDate","ApplePay","ContactField","PaymentNetwork","MerchantCapability","Name","EmailAddress","PhoneNumber","PostalAddress","PhoneticName","Amex","Barcode","CartesBancaires","ChinaUnionPay","Dankort","Discover","Eftpos","Electron","Elo","Girocard","IDCredit","Interac","JCB","Mada","Maestro","MasterCard","Mir","Nanaco","PrivateLabel","QuicPay","Suica","Visa","VPay","Waon","ThreeDS","EMV","Credit","Debit","virtualTransactionId","appStoreError","_canMakePayments","forceReceiptReload","_products","validProducts","_paymentMonitor","_appStoreReceiptLoading","_appStoreReceiptCallbacks","bridge","Bridge","discountEligibilityDeterminer","autoFinish","pseudoReceipt","createDebouncer","_receiptsUpdated","getProduct","_receipt","addValidProducts","vp","upsertTransactionInProgress","tr","SKTransaction","removeTransactionInProgress","upsertTransaction","initializeAppReceipt","removeTransaction","setPaymentMonitor","callPaymentMonitor","bridgeLogger","init","msg","purchased","transactionIdentifier","originalTransactionIdentifier","transactionDate","discountId","purchaseEnqueued","quantity","purchaseFailed","purchasing","deferred","wait","restored","receiptsRefreshed","restoreFailed","errorCode","onRestoreCompleted","restoreCompleted","canMakePayments","nativeData","loadAppStoreReceipt","callCallbacks","arg","appStoreReceipt","SKApplicationReceipt","prepareReceipt","catch","loadEligibility","DiscountEligibilities","eligibilityRequests","discounts","discount","introPrice","applicationReceipt","callDiscountEligibilityDeterminer","load","invalidProducts","eligibilities","v","SKProduct","callResolve","DEFAULT_OFFER_ID","appStore","APPLICATION_VIRTUAL_TRANSACTION_ID","refreshReceipt","refreshReceipts","skReceipt","slice","bundleIdentifier","isEligible","localReceiptUpdated","vTransaction","original_purchase_date_ms","parseInt","payment","presentCodeRedemptionSheet","Bridge_1","noop","args","exec","methodName","protectCall","transactionsForProduct","initialized","needRestoreNotification","pendingUpdates","onPurchased","onFailed","onRestored","storekit","setupOk","processPendingTransactions","finalizeTransactionUpdates","purchaseOk","errMsg","productIds","loadOk","loadFailed","errMessage","transactionUpdated","errorText","transactionReceipt","lastTransactionUpdated","restoreCompletedTransactionsFinished","restoreCompletedTransactionsFailed","parseReceiptArgs","base64","bundleShortVersion","bundleNumericVersion","bundleSignature","successCb","errorCb","req","SKOffer","super","offerType","validProduct","removeIneligibleDiscounts","countryCode","finalPhase","billingPeriod","formatBillingPeriod","billingPeriodUnit","paymentMode","recurrenceMode","numCycles","period","discountPhase","periodUnit","billingCycles","hasIntroductoryOffer","defaultPhases","introPricePeriod","introPricePeriodUnit","introPricePaymentMode","numPeriods","needApplicationReceipt","offerId","originalTransactionId","VerifyReceipt","AppleExpirationIntent","CANCELED","BILLING_ERROR","PRICE_INCREASE","BraintreeReceipt","dropInResult","paymentMethodNonce","nonce","paymentMethodType","paymentDescription","_receipts","IosBridge","AndroidBridge","iosBridge","tokenizationKey","clientTokenProvider","braintreeError","applePay","androidBridge","launchDropIn","dropInRequest","_f","_g","_h","_j","braintree","ApplePayPlugin","applePayDisabled","googlePay","googlePayRequest","transactionInfo","currencyCode","totalPrice","totalPriceStatus","GooglePay","TotalPriceStatus","FINAL","threeDSecure","threeDSecureRequest","threeDS","amount","asDecimalString","amountCents","billingAddress","givenName","surname","countryCodeAlpha2","postalCode","locality","streetAddress","streetAddress1","extendedAddress","streetAddress2","line3","streetAddress3","phoneNumber","region","dropInResponseIsOK","dropInResponseError","isBraintreeReceipt","deviceData","lCustomerId","customer","PLUGIN_ID","getClientToken","token","isApplePaySupported","errCode","split","CdvPurchaseBraintreeApplePay","installed","applePayOptions","continueDropInForApplePay","DropInRequest","preparePaymentRequest","merchantCapabilities","paymentSummaryItems","index","label","total","companyName","userCancelled","isDefault","applePayCardNonce","onSuccess","DropIn","PaymentMethod","APPLE_PAY","onError","errorString","braintreePlugin","CdvPurchaseBraintree","CardFormFieldStatus","DISABLED","OPTIONAL","REQUIRED","GOOGLE_PAY","LASER","UK_MAESTRO","SWITCH","SOLOR","AMEX","DINERS_CLUB","DISCOVER","MAESTRO","MASTERCARD","PAYPAL","VISA","VENMO","UNIONPAY","HIPER","HIPERCARD","BillingAddressFormat","MIN","FULL","NOT_CURRENTLY_KNOWN","ESTIMATED","ThreeDSecure","AccountType","ShippingMethod","Version","UNSPECIFIED","CREDIT","DEBIT","SAME_DAY","EXPEDITED","PRIORITY","GROUND","ELECTRONIC_DELIVERY","SHIP_TO_STORE","V1","V2","nativePurchase","toState","fromConstructor","isAcknowledged","PurchaseState","PURCHASED","UNSPECIFIED_STATE","orderId","purchaseToken","purchaseId","purchaseTime","getPurchaseState","acknowledged","consumed","autoRenewing","renewalIntent","refreshPurchase","autoRefreshIntervalMillis","_instance","Products","initializationPromise","iabOptions","onSetPurchases","onPurchasesUpdated","onPurchaseConsumed","showLog","iabReady","getPurchases","playStoreError","getSkusOf","inAppSkus","subsSkus","iabLoaded","go","registeredProduct","addProduct","getAvailableProducts","firstProduct","onFailure","consumePurchase","acknowledgePurchase","purchases","existingReceipt","newReceipt","onPriceChangeConfirmationResult","failure","buySuccess","buyFailed","idAndToken","oldPurchaseToken","findOldPurchaseToken","googlePlay","buy","oldReceipt","signature","trimProductTitles","ProrationMode","ReplacementMode","IMMEDIATE_WITH_TIME_PRORATION","IMMEDIATE_AND_CHARGE_PRORATED_PRICE","IMMEDIATE_WITHOUT_PRORATION","DEFERRED","IMMEDIATE_AND_CHARGE_FULL_PRICE","WITH_TIME_PRORATION","CHARGE_PRORATED_PRICE","WITHOUT_PRORATION","CHARGE_FULL_PRICE","Bridge_2","fail","tokens","test","extendAdditionalData","ad","ensureObject","accountId","skus","launchPriceChangeConfirmationFlow","GProduct","InAppOffer","arguments","SubscriptionOffer","tags","existingProduct","product_format","product_type","onSubsV12Loaded","onInAppLoaded","productOffer","lastPhase","pricing_phases","recurrence_mode","baseOffer","findBasePlan","basePlanId","base_plan_id","offer_id","iabSubsOfferV12Loaded","makeOfferId","existingOffer","toPricingPhase","formatted_price","price_amount_micros","price_currency_code","newOffer","toPaymentMode","phase","toRecurrenceMode","mode","billing_period","billing_cycle_count","PublisherAPI","GoogleErrorReason","SUBSCRIPTION_NO_LONGER_AVAILABLE","PURCHASE_TOKEN_NO_LONGER_VALID","GONE","updateVerifiedPurchases","attributes","renewalIntentChangeDate","testStoreError","registerProduct","testProductsArray","testProducts","PAID_SUBSCRIPTION_ACTIVE","reportActiveSubscription","initTestProduct","prompt","toUpperCase","asyncDelay","alert","RENEWS_EVERY_MS","makeTransaction","n","extra","firstPurchase","transactionNumber","CONSUMABLE_FAILING","WindowsStore","windowsStoreError","Ajax","HTTP_REQUEST_TIMEOUT","plugin","http","ajaxWithHttpPlugin","doneCb","ajaxOptions","toLowerCase","serializer","ajaxDone","callExternal","parse","sendRequest","xhr","XMLHttpRequest","ontimeout","open","onreadystatechange","readyState","responseText","statusText","setRequestHeader","send","prototype","milliseconds","waiting","later","toCall","delay","debounce","formatBillingCycleEN","pricingPhase","fixedRecurrenceMode","cycles","formatDurationEN","omitOne","iso","l","D","W","M","Y","HEX2STR","toHexString","hexStringFromArray","out","arrayLength","add32","complexShift","u","shiftFunction","shiftAdd32","op0","op1","v1","add32x4","j0","j1","step1Function","f","step2Function","step3Function","step4Function","hashStep","inOutVec4","strAsInts","v0","v2","v3","step1","step2","step3","step4","stringToIntArray","charCodeAt","computeMD5","lastCharIndex","strLength","vec4","substring","vec16","reminderLength","vec16Index","errorAsError","c","getCryptoExtension","crypto","msCrypto","getRandomValues","Uint8Array","privacyPolicy","getPrivacyPolicy","allowed","policy","wdw","isObject","ionic","Ionic","model","manufacturer","serial","uuid","isVirtual","fingerprint","Request","nativeTransactions","warning","validationDate","date"],"ignoreList":[],"sourceRoot":"webpack:///","sources":["./src/app/billing/shared/components/subscription-label/subscription-label.component.ts","./src/app/billing/shared/components/subscription-label/subscription-label.component.html","./src/app/billing/shared/components/subscription-detail/subscription-detail.component.html","./src/app/billing/shared/components/subscription-detail/subscription-detail.component.ts","./src/app/studio/shared/components/studio-archive/studio-archive.modal.ts","./src/app/studio/shared/components/studio-archive/studio-archive.modal.html","./src/app/billing/shared/native-app-store.model.ts","./src/app/billing/shared/services/native-app-store.service.ts","./src/app/billing/shared/components/native-app-store/native-app-store.component.html","./src/app/billing/shared/components/native-app-store/native-app-store.component.ts","./src/app/studio/edit-studio/edit-studio.page.html","./src/app/studio/edit-studio/edit-studio.page.ts","./node_modules/cordova-plugin-purchase/www/store.js"],"sourcesContent":["/** @format */\n\nimport { Component } from '@angular/core';\nimport { AsyncPipe } from '@angular/common';\nimport { TranslatePipe } from '@ngx-translate/core';\nimport { Observable } from 'rxjs';\nimport { Store } from '@ngrx/store';\nimport { State } from '@app/billing/store/billing.reducer';\nimport { selectSubscriptionLevelLabelTranslateKey } from '@app/billing/store/billing.selectors';\n// import { SubscriptionLevel, SUB_LEVEL_TRANSLATE_KEYS } from '@app/billing/shared/billing.model';\n\n@Component({\n  selector: 'fs-subscription-label',\n  templateUrl: './subscription-label.component.html',\n  styleUrls: ['./subscription-label.component.scss'],\n  standalone: true,\n  imports: [AsyncPipe, TranslatePipe],\n})\nexport class SubscriptionLabelComponent {\n  subscriptionLabelTranslateKey$: Observable<string> = this.store.select(selectSubscriptionLevelLabelTranslateKey);\n\n  constructor(private store: Store<State>) {}\n}\n","{{ subscriptionLabelTranslateKey$ | async | translate }}\n","<div *ngIf=\"subscriptionSignalVm() as subscription\" class=\"subscription-detail\">\n  <h2>{{ 'AUTH.ACCOUNT' | translate }}</h2>\n  <ion-list lines=\"none\">\n    <ion-item class=\"sub-summary\">\n      <ion-label>\n        <h3 class=\"ion-text-wrap\">{{ 'AUTH.PLANS.SUBSCRIPTION_LEVEL' | translate }}</h3>\n        <p class=\"ion-text-wrap\">\n          <fs-subscription-label></fs-subscription-label>\n        </p>\n      </ion-label>\n      <ion-note slot=\"end\" color=\"light\" class=\"well\">{{ subscription.name | translate | uppercase }}</ion-note>\n      <ion-button\n        slot=\"end\"\n        shape=\"round\"\n        fill=\"solid\"\n        color=\"primary\"\n        title=\"Edit\"\n        class=\"icon-btn\"\n        (click)=\"subscriptionActionClick(subscription)\">\n        <ion-icon slot=\"icon-only\" name=\"create-outline\"></ion-icon>\n      </ion-button>\n    </ion-item>\n\n    <div class=\"plan-options\">\n      <!-- <pre>{{ subscription | json }}</pre> -->\n      <div *ngIf=\"subscription.isActive && subscription?.proSubId else notActiveDetail\">\n        <!-- <p class=\"bright\">{{ 'BILLING.ALREADY_PRO' | translate }}</p> -->\n        <ng-template #noEventsProTpl>\n          <p class=\"bright\">{{ 'ONBOARDING.COMMON.ACTIVE_DETAIL_PRO' | translate }}</p>\n        </ng-template>\n        <p *ngIf=\"subscription?.eventsSubIds?.length > 0 else noEventsProTpl\" class=\"bright\">{{ 'ONBOARDING.COMMON.ACTIVE_DETAIL_WITH_EVENT' | translate }}</p>\n        <fs-button size=\"default\" (click)=\"editSubscription(subscription?.proSubId)\">{{ 'AUTH.PLANS.EDIT_SUBSCRIPTION' | translate }}</fs-button>\n      </div>\n      <ng-template #notActiveDetail>\n        <p *ngIf=\"subscription?.eventsSubIds?.length > 0 else noEventTpl\" class=\"bright\">{{ 'ONBOARDING.COMMON.NOT_ACTIVE_DETAIL_WITH_EVENT' | translate }}</p>\n        <ng-template #noEventTpl>\n          <p class=\"bright\">{{ 'ONBOARDING.COMMON.NOT_ACTIVE_DETAIL' | translate }}</p>\n        </ng-template>\n        <fs-button size=\"large\" (click)=\"subscribe()\">{{ 'AUTH.PLANS.SUBSCRIBE' | translate }}</fs-button>\n      </ng-template>\n      <p class=\"ion-text-wrap\" style=\"line-height: 4em;margin:0;\">\n        <ion-button class=\"btn-link-inline with-icon ion-text-wrap\" fill=\"clear\" href=\"https://filmstacker.com/plans-pricing\" target=\"_filmstacker\">\n          {{ 'AUTH.PLANS.LEARN_MORE' | translate }}\n          <ion-icon slot=\"end\" name=\"open-outline\"></ion-icon>\n        </ion-button>\n      </p>\n    </div>\n\n    <!-- \n      Owner: Username (not shown if my event on edit studio)\n      Status : Active: Expired\n      Expires: Renews: \n      Event Date\n\n      - only show MY events\n      -> move to studio page with links for places i can contribute\n     -->\n    <!-- <ng-container *ngIf=\"projectsWithEvents$ | async as eventProjects\">\n    <div *ngIf=\"eventProjects?.length > 0\" class=\"project-events\">\n      YOU HAVE PROJECT EVENTS!\n    </div>\n  </ng-container> -->\n    <div *ngIf=\"myEventProjectsVm() as eventProjects\" class=\"project-events\">\n      <div *ngIf=\"eventProjects?.length > 0\">\n        <h4>{{ 'PROJECT.ACTIVE_EVENTS' | translate }}:</h4>\n        <!-- \n          <fs-events-list\n            [eventProjects]=\"eventProjects\"\n            [subscription]=\"subscription\"\n            [showTitle]=\"false\"\n            [showOwner]=\"false\"\n          ></fs-events-list>\n         -->\n        <ion-list lines=\"none\">\n          <!-- // eventType, canBeActive, \n              eventIsActive, \n              eventDate, \n              eventConfig, \n              subscriptionId,\n              subscriptionBy, \n              subscriptionLevel, \n              subscriptionMinutes, \n              subscriptionStatus\n          -->\n          <ion-item *ngFor=\"let project of eventProjects\" class=\"project-events__item\">\n            <ion-label class=\"ion-text-wrap\">\n              <ion-button *ngIf=\"project?.id else noId\" [routerLink]=\"[routeProjectDetail, project.id]\"\n                fill=\"clear\"\n                size=\"default\"\n                class=\"ion-text-wrap ion-text-left\">\n                {{ project.title }}\n              </ion-button>\n              <ng-template #noId>\n                <!-- <pre>No ID: {{ project | json }}</pre> -->\n                <div style=\"padding-left: 16px;\">\n                  <span class=\"italic\">{{ 'PROJECT.NOT_FOUND' | translate }}:</span> {{ project?.title ?? project?.subscription?.cf_project_name }}\n                </div>\n              </ng-template>\n              <div class=\"ion-text-capitalize project-subscription-details\">\n                <div>\n                  <span class=\"\">{{ 'AUTH.PLANS.SUBSCRIPTION_LEVEL' | translate }}: </span><b>{{ project?.subLevel ?? project?.subscriptionLevel ?? project.eventConfig?.subscriptionLevel }}</b>\n                </div>\n                <div *ngIf=\"project?.expires\">\n                  <span class=\"bold\">{{ 'COMMON.EXPIRES' | translate }}:</span> {{ project?.expires | date: 'medium' }}\n                </div>\n                <div *ngIf=\"project?.renews\">\n                  <span class=\"bold\">{{ 'COMMON.RENEWS' | translate }}:</span> {{ project?.renews | date: 'medium' }}\n                </div>\n                <div *ngIf=\"project?.eventDate && !project.renews && !project.expires\">\n                  <span class=\"italic\">{{ 'COMMON.DATE' | translate }}: </span>{{ project?.eventDate | date: 'medium' }}\n                </div>\n              </div>\n            </ion-label>\n            <div slot=\"end\" class=\"active-event-icon\" title=\"Active Event\">\n              <ion-icon name=\"today-outline\" class=\"no-user\"></ion-icon>\n            </div>\n            <!-- added case where no project id but still active sub - allow to edit -->\n            <ion-button *ngIf=\"!(project?.id?.length > 0) || (project?.canEdit && project?.subscriptionId && subscription.eventsSubIds.includes(project.subscriptionId)); else noEditTpl\" \n              slot=\"end\" \n              (click)=\"editEventSubscription(subscription, project)\" \n              fill=\"outline\"\n              class=\"round\"\n              color=\"primary\" class=\"projects-action\">\n              <ion-icon name=\"create-outline\" slot=\"icon-only\"></ion-icon>\n            </ion-button>\n            <ng-template #noEditTpl>\n              <ion-button \n                slot=\"end\" \n                [routerLink]=\"[routeProjectDetail, project.id]\"\n                fill=\"outline\"\n                class=\"round\"\n                color=\"medium\" class=\"projects-action\">\n                <ion-icon name=\"information\" slot=\"icon-only\"></ion-icon>\n              </ion-button>\n            </ng-template>\n          </ion-item>\n        </ion-list>\n      </div>\n      \n    </div>\n\n    <ng-container *ngIf=\"subscription.isActive\">\n      <ion-item *ngIf=\"minutesEnabled\">\n        <ion-label>\n          <h3>Capture Minutes</h3>\n          <p class=\"ion-text-wrap\">The minutes and seconds of each clip you capture will deduct from your balance.</p>\n        </ion-label>\n        <ion-note slot=\"end\" color=\"light\" class=\"well\">{{ minutes$ | async }}</ion-note>\n\n        <ion-button\n          slot=\"end\"\n          color=\"primary\"\n          title=\"Buy Minutes\"\n          size=\"default\"\n          (click)=\"addMinutes()\">\n          Buy Minutes\n          <ion-icon slot=\"end\" name=\"cart\"></ion-icon>\n        </ion-button>\n        <!-- icon button:\n        <ion-button\n          slot=\"end\"\n          shape=\"round\"\n          fill=\"outline\"\n          color=\"light\"\n          title=\"Checkout\"\n          class=\"icon-btn\"\n          (click)=\"openCheckout($event)\">\n          <ion-icon slot=\"icon-only\" name=\"cart-outline\"></ion-icon>\n        </ion-button> -->\n      </ion-item>\n\n      <ng-container *ngIf=\"subscription?.isActive && (subscription?.proSubId || subscription?.eventsSubIds?.length > 0)\">\n        <ion-grid class=\"grid-buttons\">\n          <ion-row>\n            <ion-col size=\"12\" size-sm=\"4\">\n              <ion-button\n                fill=\"clear\"\n                class=\"text-btn\"\n                color=\"primary\"\n                [title]=\"'BILLING.INFO' | translate\"\n                (click)=\"openBillingInfo()\">\n                {{ 'BILLING.INFO' | translate }}\n              </ion-button>\n            </ion-col>\n            <ion-col size=\"12\" size-sm=\"4\">\n              <ion-button\n                fill=\"clear\"\n                class=\"text-btn\"\n                color=\"primary\"\n                [title]=\"'BILLING.PAYMENT_METHODS' | translate\"\n                (click)=\"openPaymentMethods()\">\n                {{ 'BILLING.PAYMENT_METHODS' | translate }}\n              </ion-button>\n            </ion-col>\n            <ion-col size=\"12\" size-sm=\"4\">\n              <ion-button\n                fill=\"clear\"\n                class=\"text-btn\"\n                color=\"primary\"\n                [title]=\"'BILLING.PURCHASE_HISTORY' | translate\"\n                (click)=\"openPurchaseHistory()\">\n                {{ 'BILLING.PURCHASE_HISTORY' | translate }}\n              </ion-button>\n            </ion-col>\n          </ion-row>\n        </ion-grid>\n      </ng-container>\n\n    </ng-container>\n\n  </ion-list>\n</div>\n","/** @format */\n\nimport { Component, computed, Signal } from '@angular/core';\nimport { NgIf, NgFor, AsyncPipe, UpperCasePipe, DatePipe } from '@angular/common';\nimport { RouterLink } from '@angular/router';\nimport { TranslatePipe } from '@ngx-translate/core';\nimport { toSignal } from '@angular/core/rxjs-interop';\nimport { Observable } from 'rxjs';\nimport { take } from 'rxjs/operators';\nimport {\n  ModalController,\n  NavController,\n  IonList,\n  IonItem,\n  IonLabel,\n  IonNote,\n  IonButton,\n  IonIcon,\n  IonGrid,\n  IonRow,\n  IonCol,\n} from '@ionic/angular/standalone';\n\nimport { Store } from '@ngrx/store';\nimport { State } from '@app/billing/store/billing.reducer';\nimport {\n  selectMinutes,\n  selectSubscriptionStatus,\n  SubscriptionViewModel,\n  selectIsPro,\n  selectEventSubscriptionProjects,\n} from '@app/billing/store/billing.selectors';\nimport {\n  ChargebeePlanId,\n  ChargebeeSubscription,\n  getEventSubscriptionDetail,\n  isSubscriptionActive,\n  SubscriptionLevel,\n  // SubscriptionStatus,\n} from '@app/billing/shared/billing.model';\nimport { BillingService } from '@app/billing/shared/services/billing.service';\nimport { PlansModalComponent } from '@app/billing/shared/components/plans-modal/plans-modal.component';\nimport { SubscriptionLabelComponent } from '@app/billing/shared/components/subscription-label/subscription-label.component';\n// import { CheckoutModalComponent } from '@app/billing/shared/components/checkout-modal/checkout-modal.component';\nimport { UserService } from '@app/core/services/user.service';\nimport { SIGNUP_RETURN_URL_PRO } from '@app/onboarding/shared/onboarding.model';\nimport { Project } from '@app/projects/shared/project.model';\nimport { ProjectService } from '@app/projects/shared/services/project.service';\nimport { ButtonComponent } from '@app/shared/components/ui/buttons/button/button.component';\nimport { ENABLE_BILLING_MINUTES } from '@app/app.config';\nimport { PROJECT_DETAIL_ROUTE } from '@app/app.routes';\n\n@Component({\n  selector: 'fs-subscription-detail',\n  templateUrl: './subscription-detail.component.html',\n  styleUrls: ['./subscription-detail.component.scss'],\n  standalone: true,\n  imports: [\n    NgIf,\n    NgFor,\n    RouterLink,\n    AsyncPipe,\n    UpperCasePipe,\n    DatePipe,\n    TranslatePipe,\n    ButtonComponent,\n    SubscriptionLabelComponent,\n    IonList,\n    IonItem,\n    IonLabel,\n    IonNote,\n    IonButton,\n    IonIcon,\n    IonGrid,\n    IonRow,\n    IonCol,\n  ],\n})\nexport class SubscriptionDetailComponent {\n  // trying a signal with computed for viewmodel\n  subscriptionSignalVm: Signal<SubscriptionViewModel> = this.store.selectSignal(selectSubscriptionStatus);\n  /** MY EVENTS paid with MY credit card (account) */\n  myEventProjectsSignal: Signal<\n    (Project & {\n      subscription?: ChargebeeSubscription;\n    })[]\n  > = this.store.selectSignal(selectEventSubscriptionProjects);\n\n  userIdSignal = toSignal(this.userService.userId$);\n\n  myEventProjectsVm: Signal<\n    (Project & {\n      canEdit: boolean;\n      eventIsActive: boolean;\n      subscription?: ChargebeeSubscription;\n      subLevel: SubscriptionLevel;\n      expires: string;\n      renews: string;\n    })[]\n  > = computed(() => {\n    const userId = this.userIdSignal();\n    return this.myEventProjectsSignal()\n      .filter((p) => typeof p !== 'undefined')\n      .map((project) => {\n        const { level, expires, renews } = getEventSubscriptionDetail(project?.subscription);\n        return {\n          ...project,\n          subLevel: level,\n          expires,\n          renews,\n        };\n      })\n      .map((project) => ({\n        ...project,\n        canEdit: this.projectService.isProjectAdmin(project, userId),\n        eventIsActive: isSubscriptionActive(project?.subscription), // || project.subscriptionStatus === SubscriptionStatus.Active,\n      }));\n  });\n\n  // deprecated - use computed signals\n  // subscriptionVm$: Observable<SubscriptionViewModel> = this.store.select(selectSubscriptionStatus);\n  // proSubscriptionId$: Observable<string> = this.store.select(selectProSubscriptionId);\n  // eventSubscriptionIds$: Observable<string[]> = this.store.select(selectEventSubscriptionIds);\n  // myEventProjects$: Observable<(Project & { canEdit: boolean })[]>;\n\n  minutes$: Observable<number> = this.store.select(selectMinutes);\n  isPro$: Observable<boolean> = this.store.select(selectIsPro);\n\n  minutesEnabled = ENABLE_BILLING_MINUTES;\n\n  routeProjectDetail = `/${PROJECT_DETAIL_ROUTE}`;\n\n  // private onDestroy$ = new Subject<void>();\n\n  constructor(\n    private store: Store<State>,\n    private userService: UserService,\n    private projectService: ProjectService,\n    private billingService: BillingService,\n    private modalCtrl: ModalController,\n    private navCtrl: NavController\n  ) {}\n\n  // ngOnDestroy() {\n  //   this.onDestroy$.next();\n  //   this.onDestroy$.complete();\n  // }\n\n  subscriptionActionClick(subscription: SubscriptionViewModel) {\n    if (subscription.isActive && subscription?.proSubId) {\n      this.editSubscription(subscription.proSubId);\n      // } else if (subscription.isActive && subscription?.eventsSubIds) {\n    } else {\n      this.subscribe();\n    }\n  }\n\n  async editEventSubscription(\n    subscription: SubscriptionViewModel,\n    project: Project & {\n      canEdit: boolean;\n      eventIsActive: boolean;\n      subscription?: ChargebeeSubscription;\n      subLevel: SubscriptionLevel;\n      expires: string;\n      renews: string;\n    }\n  ) {\n    console.log({ event, subscription, project });\n\n    if (project?.subscriptionId && subscription.eventsSubIds.includes(project.subscriptionId)) {\n      // we have a valid event subID - open that edit\n      this.editSubscription(project.subscriptionId);\n    } else if (!(project?.id?.length > 0) && project?.subscription?.id?.length > 0) {\n      // allow for an active sub to be edited, even if project DNE (!project.id)\n      this.editSubscription(project.subscription.id);\n    } else {\n      console.log('Not Authorized to editEventSubscription..');\n      this.navCtrl.navigateForward(SIGNUP_RETURN_URL_PRO);\n    }\n  }\n\n  /**\n   * Before calling me, validate that subscription.isActive\n   */\n  async editSubscription(subscriptionId: string) {\n    if (subscriptionId) {\n      this.billingService.openEditSubscription(subscriptionId);\n      return;\n      // this.userService.userId$.pipe(take(1)).subscribe(async (userId) => {\n      //   const iframeSrc = await this.billingService.getEditCheckoutHostedPageId({ userId, subscriptionId });\n      //   const modal = await this.modalCtrl.create({\n      //     component: CheckoutModalComponent,\n      //     componentProps: {\n      //       // id: subscription.id,\n      //       userId,\n      //       iframeSrc\n      //     },\n      //     cssClass: 'fullheight-iframe-modal',\n      //   });\n      //   await modal.present();\n\n      //   const { data } = await modal.onWillDismiss();\n      //   console.log(data);\n      // });\n    } else {\n      this.navCtrl.navigateForward(SIGNUP_RETURN_URL_PRO);\n    }\n  }\n\n  async subscribe() {\n    const modal = await this.modalCtrl.create({\n      component: PlansModalComponent,\n      componentProps: {\n        // userId,\n        // planId,\n        // priceId,\n        // referralCode,\n        // projectId,\n        // projectTitle,\n        // eventDate,\n        // successRedirectPath,\n      },\n      cssClass: 'fullheight-iframe-modal',\n    });\n    await modal.present();\n    const { data } = await modal.onWillDismiss();\n    if (data) {\n      console.log('PlansModal dismissed:', data);\n    }\n  }\n\n  /*\n  TODO: refactor all of the below:\n  */\n\n  /* eslint-disable @typescript-eslint/member-ordering */\n\n  /**\n   * @deprecated instead of this: use the checkout-button.component!\n   */\n  private async openCheckout() {\n    // how do we determine this here? diff buttons, or allow from marketing site?\n    const planId = ChargebeePlanId.Pro;\n    console.warn('openCheckout: UNHANDLED');\n    // this.userService.userId$.pipe(take(1)).subscribe(async (userId) => {\n    //   const modal = await this.modalCtrl.create({\n    //     component: CheckoutModalComponent,\n    //     componentProps: {\n    //       planId,\n    //       userId,\n    //     },\n    //     cssClass: 'fullheight-iframe-modal',\n    //   });\n    //   return await modal.present();\n    // });\n\n    // this.billingService.updateBillingInfoWithHostedPage('qx0lQY94Hyzrp2CK6zyolaVbqm4Imyie');\n    try {\n      // this.billingService.openCheckout(planId);\n    } catch (error) {\n      console.warn(`[SubscriptionDetail] openPortal caught:`, error);\n    }\n  }\n\n  /**\n   * billingService.initUser already done in the user-menu, do not need it again\n   */\n  // ngAfterViewInit() {\n  //   // console.log(`[SubscriptionDetail] afterViewInit -> initUser...`);\n  //   // this.billingService.initUser();\n  //   // this.billingService.generatePortalSession();\n  // }\n\n  /**\n   * @todo: jd\n   */\n  viewPlans() {\n    //   console.log(`[SubscriptionDetail] getPlans`);\n    //   this.billingService.getPlans();\n  }\n\n  addMinutes() {\n    // const planId = 'clip-minutes';  // @todo: jd\n    // const planId = ChargebeePlanId.Pro;\n    try {\n      console.warn(`todo: you'll need a planId here and addons`);\n      // this.billingService.openCheckout(planId);\n    } catch (error) {\n      console.warn(`[SubscriptionDetail] openPortal caught:`, error);\n    }\n  }\n\n  openBillingInfo() {\n    try {\n      this.billingService.openBillingInfo();\n    } catch (error) {\n      console.warn(`[SubscriptionDetail] openBillingInfo caught:`, error);\n    }\n  }\n\n  openPaymentMethods() {\n    try {\n      this.billingService.openPaymentMethods();\n    } catch (error) {\n      console.warn(`[SubscriptionDetail] openBillingInfo caught:`, error);\n    }\n  }\n\n  openPurchaseHistory() {\n    try {\n      this.billingService.openPurchaseHistory();\n    } catch (error) {\n      console.warn(`[SubscriptionDetail] openBillingInfo caught:`, error);\n    }\n  }\n\n  // openPortal(event) {\n  //   try {\n  //     this.billingService.openPortal({});\n  //   } catch (error) {\n  //     console.warn(`[SubscriptionDetail] openPortal caught:`, error);\n  //   }\n  // }\n}\n","/** @format */\n\nimport { Component, Input } from '@angular/core';\nimport { ModalController, NavController, IonIcon, IonButton } from '@ionic/angular/standalone';\nimport { HELP_ROUTE } from '@app/app.routes';\n\n@Component({\n  selector: 'app-studio-archive',\n  templateUrl: './studio-archive.modal.html',\n  styleUrls: ['./studio-archive.modal.scss'],\n  standalone: true,\n  imports: [IonIcon, IonButton],\n})\nexport class StudioArchiveModal {\n  @Input() title: string = 'Archive Studio';\n\n  constructor(private modalCtrl: ModalController, private navCtrl: NavController) {}\n\n  dismiss() {\n    // using the injected ModalController this page\n    // can \"dismiss\" itself and optionally pass back data\n    this.modalCtrl.dismiss({\n      dismissed: true,\n    });\n  }\n\n  navHelp() {\n    this.dismiss();\n    this.navCtrl.navigateForward(`/${HELP_ROUTE}`);\n  }\n\n  archive() {\n    console.log(`TODO: Archive Studio!`);\n  }\n}\n","<!-- @format -->\n\n<div class=\"ion-text-center ion-padding skinny-limit-width\">\n  <div class=\"top-icon\">\n    <ion-icon name=\"archive-outline\" size=\"large\" color=\"medium\"></ion-icon>\n  </div>\n\n  <h1>{{ title }}</h1>\n\n  <h2>So you want to hit pause with your studio?</h2>\n\n  <div class=\"input-wrap\">\n    <!-- input: type ARCHIVE to continue -->\n    <i> Feature Coming Soon... </i>\n  </div>\n\n  <div>\n    <ion-button disabled=\"true\" fill=\"outline\" color=\"medium\" (click)=\"archive()\"> Archive </ion-button>\n    <ion-button fill=\"clear\" color=\"medium\" (click)=\"dismiss()\"> Cancel </ion-button>\n  </div>\n\n  <div>\n    <p>\n      You will not lose any content. You can unarchive it when you're ready to focus on it again. To learn more, check\n      out <a (click)=\"navHelp()\">Archive or Unarchive Your Studio</a>.\n    </p>\n    <p>If you'd rather delete your studio, you can do so here.</p>\n  </div>\n</div>\n","/** AppStore Native */\nexport const NATIVE_APP_STORE_KEY_WEDDING = 'dev_wedding_project_nonrenewing';\nexport const NATIVE_APP_STORE_KEY_EVENT_MONTHLY = 'event_renewing_monthly_1';\nexport const NATIVE_APP_STORE_KEY_EVENT_ANNUALLY = 'event_renewing_annually_1';\nexport const NATIVE_APP_STORE_KEY_PRO_ANNUALLY = 'pro_renewing_annual_1';\nexport const NATIVE_APP_STORE_KEY_PRO_MONTHLY = 'pro_renewing_monthly_1';\n","/** @format */\n\nimport { EventEmitter, Injectable, signal } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport { AlertController, Platform } from '@ionic/angular/standalone';\nimport 'cordova-plugin-purchase';\nimport {\n  NATIVE_APP_STORE_KEY_WEDDING,\n  NATIVE_APP_STORE_KEY_EVENT_MONTHLY,\n  NATIVE_APP_STORE_KEY_EVENT_ANNUALLY,\n  NATIVE_APP_STORE_KEY_PRO_ANNUALLY,\n  NATIVE_APP_STORE_KEY_PRO_MONTHLY,\n} from '../native-app-store.model';\n\nexport type CdvPurchaseStore = CdvPurchase.Store; \nexport type CdvPurchaseProduct = CdvPurchase.Product; \nexport type CdvPurchaseProductType = CdvPurchase.ProductType; \nexport type CdvPurchaseTransaction = CdvPurchase.Transaction; \nexport type CdvPurchaseTransactionState = CdvPurchase.TransactionState; \n\nconst DEBUG = true;\n\n@Injectable({\n  providedIn: 'root',\n})\nexport class NativeAppStoreService {\n  // DO NOT initialize to CdvPurchase.store here\n  store?: CdvPurchase.Store;\n  products= signal<CdvPurchase.Product[]>([]);\n  enabled = signal(false);\n  isPro = signal(false);\n  hasWedding = signal(false);\n  hasEvent = signal(false);\n  errorMessage = signal('');\n  cdvPlatform: CdvPurchase.Platform = CdvPurchase.Platform.TEST;\n\n  changeDetectionEmitter: EventEmitter<void> = new EventEmitter<void>();\n\n  constructor(\n    private alertController: AlertController, \n    private plt: Platform,\n  ) {\n    this.plt.ready().then(() => {\n      if (Capacitor.isNativePlatform()) {\n        // MUST WAIT for Cordova to initialize before referencing CdvPurchase namespace\n        this.store = CdvPurchase.store;\n        // TODO: Setup receipt validation (recommended)\n        // ref: https://github.com/j3k0/cordova-plugin-purchase?tab=readme-ov-file\n        // store.validator = \"https://validator.iaptic.com/v1/validate?appName=demo&apiKey=12345678\";\n\n        if (DEBUG) {\n          this.store.verbosity = CdvPurchase.LogLevel.DEBUG;\n        }\n        if (Capacitor.getPlatform() === 'ios') {\n          this.cdvPlatform = CdvPurchase.Platform.APPLE_APPSTORE;\n        } else if (Capacitor.getPlatform() === 'android') {\n          this.cdvPlatform = CdvPurchase.Platform.GOOGLE_PLAY;\n        }\n        this.registerProducts(this.cdvPlatform);\n        this.setupListeners();\n        // Initialize the store\n        this.store.initialize([{\n          platform: this.cdvPlatform as CdvPurchase.Platform.APPLE_APPSTORE | CdvPurchase.Platform.GOOGLE_PLAY,\n          options: {\n            needAppReceipt: true,\n          }\n        }]);\n        this.enabled.set(true);\n      } else {\n        this.enabled.set(false);\n      }\n    });\n  }\n\n  getProductState(product: CdvPurchase.Product): CdvPurchase.TransactionState {\n    return this.store.findInLocalReceipts(product)?.state ?? CdvPurchase.TransactionState.UNKNOWN_STATE;\n  }\n\n  /** Purchase a subscription */\n  subscribe(productId: string) {\n    const product = this.store.get(productId);\n    if (!product) {\n      throw new Error('Product not found');\n    }\n    product.getOffer()?.order()\n      .then(error => {\n        if (error) {\n          if (error.code === CdvPurchase.ErrorCode.PAYMENT_CANCELLED) {\n            console.log('Payment cancelled by user');\n            throw new Error('Payment cancelled by user');\n          } else {\n            console.log('Failed to subscribe:', error);\n            throw new Error('Failed to subscribe - please try again.');\n          }\n        }\n      });\n  }\n\n  /** Check if user has an active subscription */\n  hasActiveSubscription(productId: string): boolean {\n    return this.store.owned(productId);\n  }\n\n  /** To comply with AppStore rules */\n  restore() {\n    this.store.restorePurchases();\n  }\n\n  async presentAlert(header, message) {\n    const alert = await this.alertController.create({\n      header,\n      message,\n      buttons: ['OK'],\n    });\n\n    await alert.present();\n  }\n\n  private registerProducts(platform: CdvPurchase.Platform) {\n    this.store.register({\n      id: NATIVE_APP_STORE_KEY_WEDDING,\n      type: CdvPurchase.ProductType.NON_RENEWING_SUBSCRIPTION,\n      platform,\n    });\n    // this.store.register({\n    //   id: NATIVE_APP_STORE_KEY_EVENT_MONTHLY,\n    //   type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n    //   platform,\n    // });\n    // this.store.register({\n    //   id: NATIVE_APP_STORE_KEY_EVENT_ANNUALLY,\n    //   type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n    //   platform,\n    // });\n    this.store.register({\n      id: NATIVE_APP_STORE_KEY_PRO_MONTHLY,\n      type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n      platform,\n    });\n    this.store.register({\n      id: NATIVE_APP_STORE_KEY_PRO_ANNUALLY,\n      type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n      platform,\n    });\n\n    // Get the real product information\n    this.store.ready(() => {\n      this.products.set(this.store.products);\n      this.changeDetectionEmitter.emit();\n    });\n  }\n\n  private setupListeners() {\n    // General query to all products\n    this.store.when()\n      .productUpdated(this.refreshUI)\n      .approved(this.finishPurchase)\n      .verified((receipt: CdvPurchase.VerifiedReceipt) => {\n        console.log('Purchase verified:', receipt);\n        receipt.finish();\n        this.refreshUI();\n      });\n      \n    this.store.error((error) => {\n      console.error('CdvPurchase ERROR: ' + error.message);\n      this.presentAlert('CdvPurchase Error', error.message);\n    });\n  }\n\n  private finishPurchase(transaction: CdvPurchase.Transaction) {\n    // Handle the product deliverable\n    \n    if (transaction.products.find((p) => p?.id === NATIVE_APP_STORE_KEY_PRO_ANNUALLY || p?.id === NATIVE_APP_STORE_KEY_PRO_MONTHLY)?.id?.length > 0) {\n      this.isPro.set(true);\n    } \n    if (transaction.products.find((p) => p?.id === NATIVE_APP_STORE_KEY_WEDDING)?.id?.length > 0) {\n      this.hasWedding.set(true);\n    }\n    if (transaction.products.find((p) => p?.id === NATIVE_APP_STORE_KEY_EVENT_ANNUALLY || p?.id === NATIVE_APP_STORE_KEY_EVENT_MONTHLY)?.id?.length > 0) {\n      this.hasEvent.set(true);\n    }\n    this.changeDetectionEmitter.emit();\n\n    transaction.verify();\n    this.refreshUI();\n  }\n  \n  private refreshUI() {\n    console.log('Products loaded from the store:', this.store.products);\n  }\n\n}\n","<div *ngIf=\"isNativePlatform\">\n  <h2>In-App Purchases</h2>\n\n  <ion-list>\n    <ion-item>\n      <ion-label>\n        Is Pro: {{ isPro() }}\n        <br>\n        Has Wedding: {{ hasWedding() }}\n        <br>\n        Has Event: {{ hasEvent() }}\n      </ion-label>\n    </ion-item>\n    <ion-item button *ngFor=\"let p of products()\" (click)=\"purchase(p)\" detail=\"false\">\n      <ion-label class=\"ion-text-wrap\">\n        {{ p.title }}\n        <p>{{ p.description }}</p>\n      </ion-label>\n      <ion-button slot=\"end\">\n        {{ p.pricing.price }} {{ p.pricing.currency }}\n      </ion-button>\n    </ion-item>\n  \n    <ion-button expand=\"full\" (click)=\"restore()\">Restore Purchases</ion-button>\n  </ion-list>\n</div>\n","/** @format */\n\nimport { ChangeDetectorRef, Component } from '@angular/core';\nimport { NgIf, NgFor } from '@angular/common';\nimport { Capacitor } from '@capacitor/core';\nimport { IonList, IonItem, IonLabel, IonButton, Platform } from '@ionic/angular/standalone';\nimport { NativeAppStoreService, CdvPurchaseProduct } from '@app/billing/shared/services/native-app-store.service';\n\n@Component({\n  selector: 'fs-native-app-store',\n  templateUrl: './native-app-store.component.html',\n  styleUrl: './native-app-store.component.scss',\n  standalone: true,\n  imports: [NgIf, NgFor, IonButton, IonLabel, IonItem, IonList],\n})\nexport class NativeAppStoreComponent {\n  isNativePlatform = false;\n\n  enabled = this.appStoreService.enabled;\n  products = this.appStoreService.products;\n  isPro = this.appStoreService.isPro;\n  hasWedding = this.appStoreService.hasWedding;\n  hasEvent = this.appStoreService.hasEvent;\n\n  constructor(private appStoreService: NativeAppStoreService, private plt: Platform, private cdRef: ChangeDetectorRef) {\n    this.plt.ready().then(() => {\n      this.isNativePlatform = Capacitor.isNativePlatform();\n    });\n    this.appStoreService.changeDetectionEmitter.subscribe(\n      () => {\n        this.cdRef.detectChanges();\n      },\n      (err) => {\n        console.error(err);\n      }\n    );\n  }\n\n  purchase(product: CdvPurchaseProduct) {\n    this.appStoreService.subscribe(product.id);\n  }\n\n  /** To comply with AppStore rules */\n  restore() {\n    this.appStoreService.restore();\n  }\n}\n","<ion-header>\n  <app-top-navbar [title]=\"title\"></app-top-navbar>\n  <ion-grid *ngIf=\"loggedIn$ | async\" class=\"limit-width ion-padding\">\n    <ion-row class=\"ion-align-items-end ion-justify-content-center\">\n      <ion-col>\n        <h1>{{ 'STUDIO.SETTINGS.TITLE' | translate }}</h1>\n      </ion-col>\n      <ion-col size=\"auto\">\n        <fs-button\n          type=\"submit\"\n          form=\"profileForm\"\n          [disabled]=\"isBusy\"\n        >\n          {{ 'COMMON.SAVE' | translate }}\n        </fs-button>\n        <fs-button buttonStyle=\"clear\"  (click)=\"cancel()\">{{ 'COMMON.CANCEL' | translate }}</fs-button>\n      </ion-col>\n    </ion-row>\n    <ion-row *ngIf=\"error\">\n      <ion-col>\n        <div class=\"form-error\">\n          <div><strong>{{ 'ERRORS.ERROR' | translate }}:</strong> {{ error }}</div>\n        </div>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n</ion-header>\n\n<ion-content forceOverflow=\"false\">\n  <ng-template #notAuthed>\n    <div class=\"ion-padding ion-text-center\">\n      <p class=\"ion-text-center\">{{ 'ERRORS.PAGE_AUTH' | translate }}</p>\n      <ion-button routerLink=\"/login\">{{ 'COMMON.LOGIN' | translate }}</ion-button>\n    </div>\n  </ng-template>\n\n  <ion-grid\n    *ngIf=\"loggedIn$ | async; else notAuthed\"\n    class=\"limit-width ion-padding\"\n  >\n    <ion-row class=\"ion-align-items-start ion-justify-content-center\">\n      <ion-col size=\"12\" size-md=\"4\">\n        <div class=\"avatar-wrap\">\n          <app-editable-avatar\n            [userId]=\"userId$ | async\"\n            [avatarUrl]=\"avatarUrl$ | async\"\n            [canEditAvatar]=\"true\"\n          ></app-editable-avatar>\n        </div>\n      </ion-col>\n      <ion-col *ngIf=\"enableBilling\" size=\"12\" size-md=\"8\">\n        <fs-subscription-detail class=\"ion-margin-vertical\" style=\"display:block;\"></fs-subscription-detail>\n      </ion-col>\n    </ion-row>\n    <ion-row>\n      <ion-col>\n        <fs-native-app-store></fs-native-app-store>\n      </ion-col>\n    </ion-row>\n    <!-- id enableBilling: ion-justify-content-end -->\n    <ion-row class=\"ion-justify-content-center\">\n      <ion-col size=\"12\" size-md=\"8\">\n        <h2>{{ 'STUDIO.SETTINGS.HEADING' | translate }}</h2>\n        <form id=\"profileForm\" class=\"fs-profile-form\" [formGroup]=\"profileForm\" (ngSubmit)=\"save()\">\n          <fs-form-input\n            label=\"{{ 'STUDIO.SETTINGS.LABEL_HANDLE' | translate }}\"\n            [hint]=\"'STUDIO.SETTINGS.INSTRUCTIONS' | translate\"\n            [control]=\"profileForm.get('handle') | formControlCast\"\n            [disabled]=\"loading\"\n          ></fs-form-input>\n          <!-- <div class=\"instructions\">\n            {{ 'STUDIO.SETTINGS.INSTRUCTIONS' | translate }}\n          </div> -->\n          <div *ngIf=\"profileForm.get('handle').invalid && (profileForm.get('handle').dirty || profileForm.get('handle').touched)\" class=\"form-error\">\n            <div *ngIf=\"profileForm.get('handle').errors['minlength']\">\n              {{ 'ERRORS.FORM.HANDLE_MIN_LENGTH' | translate:{length: usernameMinLength} }}\n            </div>\n            <div *ngIf=\"profileForm.get('handle').errors['maxlength']\">\n              {{ 'ERRORS.FORM.HANDLE_MAX_LENGTH' | translate:{length: usernameMaxLength} }}\n            </div>\n            <div *ngIf=\"profileForm.get('handle').errors['pattern']\">\n                {{usernamePatternDesc}}\n            </div>\n          </div>\n        \n          <fs-form-input\n            label=\"{{ 'STUDIO.SETTINGS.LABEL_LOCATION' | translate }}\"\n            [control]=\"profileForm.get('location') | formControlCast\"\n            [disabled]=\"loading\"\n          ></fs-form-input>\n          <fs-form-textarea\n            label=\"{{ 'STUDIO.SETTINGS.LABEL_BIO' | translate }}\"\n            [control]=\"profileForm.get('bio') | formControlCast\"\n            [disabled]=\"loading\"\n          ></fs-form-textarea>\n          <fs-form-input\n            label=\"{{ 'STUDIO.SETTINGS.LABEL_NAME' | translate }}\"\n            [hint]=\"'STUDIO.SETTINGS.USERID_NOTE' | translate\"\n            [control]=\"profileForm.get('userId') | formControlCast\"\n            [disabled]=\"true\"\n          ></fs-form-input>\n          <!-- <div class=\"instructions\">\n            {{ 'STUDIO.SETTINGS.USERID_NOTE' | translate }}\n          </div> -->\n          <fs-form-input\n            label=\"{{ 'COMMON.EMAIL' | translate }}\"\n            [hint]=\"'STUDIO.SETTINGS.EMAIL_NOTE' | translate\"\n            [control]=\"profileForm.get('email') | formControlCast\"\n            [disabled]=\"loading || true\"\n          ></fs-form-input>\n          <!-- <div class=\"instructions\">\n            {{ 'STUDIO.SETTINGS.EMAIL_NOTE' | translate }}\n          </div> -->\n        </form>\n\n        <div class=\"ion-padding ion-margin-top\" style=\"display: flex; align-items: center;\">\n          <fs-button \n            *ngIf=\"email$ | async as email\"\n            buttonStyle=\"outline\"\n            (click)=\"changePassword(email)\"\n          >{{ 'AUTH.CHANGE_PASSWORD' | translate }}</fs-button>\n          <fs-button \n            class=\"ion-text-right\" \n            buttonStyle=\"outline\" \n            icon=\"archive-outline\" \n            (click)=\"archive()\"\n          >{{ 'COMMON.ARCHIVE' | translate }}</fs-button>\n        </div>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n  <div class=\"tab-bottom-spacer\"></div>\n</ion-content>\n","/** @format */\n\nimport { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';\nimport { NgIf, AsyncPipe } from '@angular/common';\nimport { NavigationExtras, Router, RouterLink } from '@angular/router';\nimport { UntypedFormBuilder, Validators, ValidationErrors, FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport {\n  ModalController,\n  NavController,\n  IonHeader,\n  IonGrid,\n  IonRow,\n  IonCol,\n  IonContent,\n  IonButton,\n} from '@ionic/angular/standalone';\nimport { addIcons } from 'ionicons';\nimport { archiveOutline, imagesOutline } from 'ionicons/icons';\nimport { TranslateService, TranslatePipe } from '@ngx-translate/core';\nimport { Observable, Subject } from 'rxjs';\nimport { take, takeUntil } from 'rxjs/operators';\nimport { ENABLE_BILLING } from '@app/app.config';\nimport { FORGOT_PASS_PAGE, STUDIO_PAGE } from '@app/app.routes';\nimport { UserService } from '@app/core/services/user.service';\nimport { ToasterService } from '@app/core/services/toaster.service';\nimport { TopNavbarComponent } from '@app/shared/components/top-navbar/top-navbar.component';\nimport { ButtonComponent } from '@app/shared/components/ui/buttons/button/button.component';\nimport { FormInputComponent } from '@app/shared/components/ui/form/form-input/form-input.component';\nimport { FormTextareaComponent } from '@app/shared/components/ui/form/form-textarea/form-textarea.component';\nimport { FormControlCastPipe } from '@app/shared/pipes/form-control-cast.pipe';\nimport { SubscriptionDetailComponent } from '@app/billing/shared/components/subscription-detail/subscription-detail.component';\nimport { EditableAvatarComponent } from '../shared/components/editable-avatar/editable-avatar.component';\nimport { StudioArchiveModal } from '../shared/components/studio-archive/studio-archive.modal';\nimport { NativeAppStoreComponent } from '@app/billing/shared/components/native-app-store/native-app-store.component';\n\n/**\n * @todo\n * controls to manage your information and protect your privacy and security.\n */\n\nconst DEBUG_LOGS = false;\nconst PAGE = '[EditStudio]';\n\n@Component({\n  selector: 'app-edit-studio',\n  templateUrl: './edit-studio.page.html',\n  styleUrls: ['./edit-studio.page.scss'],\n  standalone: true,\n  imports: [\n    NgIf,\n    RouterLink,\n    FormsModule,\n    ReactiveFormsModule,\n    AsyncPipe,\n    TranslatePipe,\n    FormControlCastPipe,\n    NativeAppStoreComponent,\n    FormInputComponent,\n    FormTextareaComponent,\n    TopNavbarComponent,\n    SubscriptionDetailComponent,\n    EditableAvatarComponent,\n    ButtonComponent,\n    IonHeader,\n    IonGrid,\n    IonRow,\n    IonCol,\n    IonContent,\n    IonButton,\n  ],\n})\nexport class EditStudioPage implements OnInit, OnDestroy, AfterViewInit {\n  enableBilling = ENABLE_BILLING;\n\n  usernameMinLength = 2;\n  usernameMaxLength = 32;\n  /** will be translated OnInit */\n  usernamePatternDesc =\n    'Public Name must start with a letter and only contain letters, numbers, dashes(-) and underscores (_)';\n\n  profileForm = this.formBuilder.group({\n    handle: [\n      '',\n      Validators.compose([\n        Validators.minLength(this.usernameMinLength),\n        Validators.maxLength(this.usernameMaxLength),\n        Validators.pattern('^[a-zA-Z]+[0-9a-zA-Z _-]+$'),\n      ]),\n    ],\n    bio: [''],\n    location: [''],\n    userId: [{ value: '', disabled: true }, Validators.required],\n    email: [{ value: '', disabled: true }, Validators.compose([Validators.required, Validators.email])],\n  });\n\n  error = '';\n  loading = false;\n\n  title: string = 'Studio';\n  loggedIn$: Observable<boolean>;\n  userId$: Observable<string>;\n  // username$: Observable<string>;\n  email$: Observable<string>;\n  avatarUrl$: Observable<string>;\n  // identityId$: Observable<string>;\n\n  private onDestroy$ = new Subject<void>();\n\n  constructor(\n    private formBuilder: UntypedFormBuilder,\n    private userService: UserService,\n    private modalCtrl: ModalController,\n    private navCtrl: NavController,\n    private toaster: ToasterService,\n    private router: Router,\n    private translate: TranslateService\n  ) {}\n\n  ngOnInit() {\n    addIcons({\n      imagesOutline, archiveOutline,\n    });\n    this.loggedIn$ = this.userService.isLoggedIn$;\n    this.userId$ = this.userService.userId$;\n    // this.username$ = this.userService.username$;\n    this.email$ = this.userService.email$;\n    this.avatarUrl$ = this.userService.avatarUrl$;\n    // this.identityId$ = this.userService.identityId$;\n\n    this.translate\n      .get('ERRORS.FORM.HANDLE_PATTERN')\n      .pipe(take(1))\n      .subscribe((res) => {\n        this.usernamePatternDesc = res;\n      });\n\n    const formSubs = [\n      {\n        obs: this.userId$,\n        field: 'userId',\n      },\n      {\n        obs: this.userService.username$,\n        field: 'handle',\n      },\n      {\n        obs: this.userService.bio$,\n        field: 'bio',\n      },\n      {\n        obs: this.userService.location$,\n        field: 'location',\n      },\n      {\n        obs: this.email$,\n        field: 'email',\n      },\n    ];\n\n    formSubs.forEach(({ obs, field }) => {\n      obs.pipe(takeUntil(this.onDestroy$)).subscribe((val: string) => {\n        DEBUG_LOGS && console.log(`${PAGE} formSub(${field}):`, val);\n        this.updateProp(field, val || '');\n      });\n    });\n  }\n\n  ngAfterViewInit() {\n    // state.tutorial - definition of something to alert the user to\n    const showTutorial = this.router.getCurrentNavigation().extras.state?.tutorial;\n    if (showTutorial) {\n      console.warn('navstate.showTutorial: ' + showTutorial);\n    }\n  }\n\n  ngOnDestroy() {\n    this.onDestroy$.next();\n    this.onDestroy$.complete();\n  }\n\n  get isBusy() {\n    return this.loading || this.profileForm.invalid;\n  }\n\n  async save() {\n    this.loading = true;\n    this.error = '';\n\n    if (!this.profileForm.valid) {\n      this.error = 'Form is not valid';\n      return;\n    }\n\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      const { handle, bio, location, userId, email } = this.profileForm.controls;\n      DEBUG_LOGS && console.log(`${PAGE} save:`, this.profileForm.controls);\n      let didSave = false;\n\n      /**\n       * I tried using the <fs-form-input>, but how can i tell if the FormControls have changed?\n       * control.dirty, control.pristine, ?\n       */\n\n      // make the updates to the store, then the effects will update api..\n\n      if (handle.dirty && handle.value) {\n        // replace any repeating spaces with single space, and trim\n        this.userService.setUsername(handle.value.replace(/\\s\\s+/g, ' ').trim());\n        didSave = true;\n      }\n\n      if (bio.dirty && bio.value) {\n        this.userService.setBio(bio.value.trim());\n        didSave = true;\n      }\n\n      if (location.dirty && location.value) {\n        this.userService.setLocation(location.value.trim());\n        didSave = true;\n      }\n\n      if (didSave) {\n        this.toaster.present(`Saved!`);\n      }\n      this.navCtrl.navigateBack(`/${STUDIO_PAGE}`);\n    } catch (err) {\n      this.error = err.message;\n    } finally {\n      this.loading = false;\n    }\n  }\n\n  updateProp(key: string, value: string) {\n    this.profileForm.patchValue({ [key]: value });\n  }\n\n  getErrorMessage(errors: ValidationErrors | undefined) {\n    return Object.keys(errors || {})\n      .filter((key) => errors[key])\n      .map((key) => {\n        switch (key) {\n          case 'required':\n            // return 'This field is required.';\n            return this.translate.instant('ERRORS.REQUIRED_FIELD');\n        }\n      })\n      .find(Boolean);\n  }\n\n  cancel() {\n    this.navCtrl.navigateBack(`/${STUDIO_PAGE}`);\n  }\n\n  async archive() {\n    // https://xd.adobe.com/view/61615fe1-b7c1-47a9-493b-3c7268fe8988-1750/screen/66b3edda-b47d-4cb3-822f-f9a42bb38f99/\n\n    const modal = await this.modalCtrl.create({\n      component: StudioArchiveModal,\n      cssClass: 'modal-light',\n      componentProps: {\n        title: 'Archive My Studio',\n      },\n    });\n    await modal.present();\n\n    const res = await modal.onDidDismiss(); // or onWillDismiss\n    console.log(`${PAGE} modalDismiss res:`, res);\n  }\n\n  changeEmail() {\n    // https://filmstacker.atlassian.net/browse/MVP-521\n  }\n\n  changePassword(email: string) {\n    const navigationExtras: NavigationExtras = {\n      state: {\n        email,\n        title: 'Change Password',\n      },\n    };\n    this.navCtrl.navigateForward(`/${FORGOT_PASS_PAGE}`, navigationExtras);\n  }\n}\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nvar CdvPurchase;\n(function (CdvPurchase) {\n    const ERROR_CODES_BASE = 6777000;\n    /**\n     * Error codes\n     */\n    let ErrorCode;\n    (function (ErrorCode) {\n        /** Error: Failed to intialize the in-app purchase library */\n        ErrorCode[ErrorCode[\"SETUP\"] = ERROR_CODES_BASE + 1] = \"SETUP\";\n        /** Error: Failed to load in-app products metadata */\n        ErrorCode[ErrorCode[\"LOAD\"] = ERROR_CODES_BASE + 2] = \"LOAD\";\n        /** Error: Failed to make a purchase */\n        ErrorCode[ErrorCode[\"PURCHASE\"] = ERROR_CODES_BASE + 3] = \"PURCHASE\";\n        /** Error: Failed to load the purchase receipt */\n        ErrorCode[ErrorCode[\"LOAD_RECEIPTS\"] = ERROR_CODES_BASE + 4] = \"LOAD_RECEIPTS\";\n        /** Error: Client is not allowed to issue the request */\n        ErrorCode[ErrorCode[\"CLIENT_INVALID\"] = ERROR_CODES_BASE + 5] = \"CLIENT_INVALID\";\n        /** Error: Purchase flow has been cancelled by user */\n        ErrorCode[ErrorCode[\"PAYMENT_CANCELLED\"] = ERROR_CODES_BASE + 6] = \"PAYMENT_CANCELLED\";\n        /** Error: Something is suspicious about a purchase */\n        ErrorCode[ErrorCode[\"PAYMENT_INVALID\"] = ERROR_CODES_BASE + 7] = \"PAYMENT_INVALID\";\n        /** Error: The user is not allowed to make a payment */\n        ErrorCode[ErrorCode[\"PAYMENT_NOT_ALLOWED\"] = ERROR_CODES_BASE + 8] = \"PAYMENT_NOT_ALLOWED\";\n        /** Error: Unknown error */\n        ErrorCode[ErrorCode[\"UNKNOWN\"] = ERROR_CODES_BASE + 10] = \"UNKNOWN\";\n        /** Error: Failed to refresh the purchase receipt */\n        ErrorCode[ErrorCode[\"REFRESH_RECEIPTS\"] = ERROR_CODES_BASE + 11] = \"REFRESH_RECEIPTS\";\n        /** Error: The product identifier is invalid */\n        ErrorCode[ErrorCode[\"INVALID_PRODUCT_ID\"] = ERROR_CODES_BASE + 12] = \"INVALID_PRODUCT_ID\";\n        /** Error: Cannot finalize a transaction or acknowledge a purchase */\n        ErrorCode[ErrorCode[\"FINISH\"] = ERROR_CODES_BASE + 13] = \"FINISH\";\n        /** Error: Failed to communicate with the server */\n        ErrorCode[ErrorCode[\"COMMUNICATION\"] = ERROR_CODES_BASE + 14] = \"COMMUNICATION\";\n        /** Error: Subscriptions are not available */\n        ErrorCode[ErrorCode[\"SUBSCRIPTIONS_NOT_AVAILABLE\"] = ERROR_CODES_BASE + 15] = \"SUBSCRIPTIONS_NOT_AVAILABLE\";\n        /** Error: Purchase information is missing token */\n        ErrorCode[ErrorCode[\"MISSING_TOKEN\"] = ERROR_CODES_BASE + 16] = \"MISSING_TOKEN\";\n        /** Error: Verification of store data failed */\n        ErrorCode[ErrorCode[\"VERIFICATION_FAILED\"] = ERROR_CODES_BASE + 17] = \"VERIFICATION_FAILED\";\n        /** Error: Bad response from the server */\n        ErrorCode[ErrorCode[\"BAD_RESPONSE\"] = ERROR_CODES_BASE + 18] = \"BAD_RESPONSE\";\n        /** Error: Failed to refresh the store */\n        ErrorCode[ErrorCode[\"REFRESH\"] = ERROR_CODES_BASE + 19] = \"REFRESH\";\n        /** Error: Payment has expired */\n        ErrorCode[ErrorCode[\"PAYMENT_EXPIRED\"] = ERROR_CODES_BASE + 20] = \"PAYMENT_EXPIRED\";\n        /** Error: Failed to download the content */\n        ErrorCode[ErrorCode[\"DOWNLOAD\"] = ERROR_CODES_BASE + 21] = \"DOWNLOAD\";\n        /** Error: Failed to update a subscription */\n        ErrorCode[ErrorCode[\"SUBSCRIPTION_UPDATE_NOT_AVAILABLE\"] = ERROR_CODES_BASE + 22] = \"SUBSCRIPTION_UPDATE_NOT_AVAILABLE\";\n        /** Error: The requested product is not available in the store. */\n        ErrorCode[ErrorCode[\"PRODUCT_NOT_AVAILABLE\"] = ERROR_CODES_BASE + 23] = \"PRODUCT_NOT_AVAILABLE\";\n        /** Error: The user has not allowed access to Cloud service information */\n        ErrorCode[ErrorCode[\"CLOUD_SERVICE_PERMISSION_DENIED\"] = ERROR_CODES_BASE + 24] = \"CLOUD_SERVICE_PERMISSION_DENIED\";\n        /** Error: The device could not connect to the network. */\n        ErrorCode[ErrorCode[\"CLOUD_SERVICE_NETWORK_CONNECTION_FAILED\"] = ERROR_CODES_BASE + 25] = \"CLOUD_SERVICE_NETWORK_CONNECTION_FAILED\";\n        /** Error: The user has revoked permission to use this cloud service. */\n        ErrorCode[ErrorCode[\"CLOUD_SERVICE_REVOKED\"] = ERROR_CODES_BASE + 26] = \"CLOUD_SERVICE_REVOKED\";\n        /** Error: The user has not yet acknowledged Apple’s privacy policy */\n        ErrorCode[ErrorCode[\"PRIVACY_ACKNOWLEDGEMENT_REQUIRED\"] = ERROR_CODES_BASE + 27] = \"PRIVACY_ACKNOWLEDGEMENT_REQUIRED\";\n        /** Error: The app is attempting to use a property for which it does not have the required entitlement. */\n        ErrorCode[ErrorCode[\"UNAUTHORIZED_REQUEST_DATA\"] = ERROR_CODES_BASE + 28] = \"UNAUTHORIZED_REQUEST_DATA\";\n        /** Error: The offer identifier is invalid. */\n        ErrorCode[ErrorCode[\"INVALID_OFFER_IDENTIFIER\"] = ERROR_CODES_BASE + 29] = \"INVALID_OFFER_IDENTIFIER\";\n        /** Error: The price you specified in App Store Connect is no longer valid. */\n        ErrorCode[ErrorCode[\"INVALID_OFFER_PRICE\"] = ERROR_CODES_BASE + 30] = \"INVALID_OFFER_PRICE\";\n        /** Error: The signature in a payment discount is not valid. */\n        ErrorCode[ErrorCode[\"INVALID_SIGNATURE\"] = ERROR_CODES_BASE + 31] = \"INVALID_SIGNATURE\";\n        /** Error: Parameters are missing in a payment discount. */\n        ErrorCode[ErrorCode[\"MISSING_OFFER_PARAMS\"] = ERROR_CODES_BASE + 32] = \"MISSING_OFFER_PARAMS\";\n        /**\n         * Server code used when a subscription expired.\n         *\n         * @deprecated Validator should now return the transaction in the collection as expired.\n         */\n        ErrorCode[ErrorCode[\"VALIDATOR_SUBSCRIPTION_EXPIRED\"] = 6778003] = \"VALIDATOR_SUBSCRIPTION_EXPIRED\";\n    })(ErrorCode = CdvPurchase.ErrorCode || (CdvPurchase.ErrorCode = {}));\n    /**\n     * Create an {@link IError} instance\n     *\n     * @internal\n     */\n    function storeError(code, message, platform, productId) {\n        return { isError: true, code, message, platform, productId };\n    }\n    CdvPurchase.storeError = storeError;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Integrate with https://www.iaptic.com/\n     *\n     * @example\n     * const iaptic = new CdvPurchase.Iaptic({\n     *   url: 'https://validator.iaptic.com',\n     *   appName: 'test',\n     *   apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',\n     * });\n     * store.validator = iaptic.validator;\n     */\n    class Iaptic {\n        constructor(config, store) {\n            this.config = config;\n            if (!config.url) {\n                config.url = 'https://validator.iaptic.com';\n            }\n            this.store = store !== null && store !== void 0 ? store : CdvPurchase.store;\n            this.log = this.store.log.child('Iaptic');\n        }\n        /**\n         * Provides a client token generated on iaptic's servers\n         *\n         * Can be passed to the Braintree Adapter at initialization.\n         *\n         * @example\n         * store.initialize([\n         *   {\n         *     platform: Platform.BRAINTREE,\n         *     options: {\n         *       clientTokenProvider: iaptic.braintreeClientTokenProvider\n         *     }\n         *   }\n         * ]);\n         */\n        get braintreeClientTokenProvider() {\n            return callback => {\n                this.log.info('Calling Braintree clientTokenProvider');\n                CdvPurchase.Utils.ajax(this.log, {\n                    url: `${this.config.url}/v3/braintree/client-token?appName=${this.config.appName}&apiKey=${this.config.apiKey}`,\n                    method: 'POST',\n                    data: {\n                        applicationUsername: CdvPurchase.store.getApplicationUsername(),\n                        customerId: CdvPurchase.Braintree.customerId,\n                    },\n                    success: body => {\n                        this.log.info('clientTokenProvider success: ' + JSON.stringify(body));\n                        callback(body.clientToken);\n                    },\n                    error: err => {\n                        this.log.info('clientTokenProvider error: ' + JSON.stringify(err));\n                        callback(CdvPurchase.storeError(err, 'ERROR ' + err, CdvPurchase.Platform.BRAINTREE, null));\n                    },\n                });\n            };\n        }\n        /**\n         * Determine the eligibility of discounts based on the content of the application receipt.\n         *\n         * The secret sauce used here is to wait for validation of the application receipt.\n         * The receipt validator will return the necessary data to determine eligibility.\n         *\n         * Receipt validation is expected to happen after loading product information, so the implementation here is to\n         * wait for a validation response.\n         */\n        get appStoreDiscountEligibilityDeterminer() {\n            // the user needs the appStoreDiscountEligibilityDeterminer, let's start listening to receipt validation events.\n            let latestReceipt;\n            this.log.debug(\"AppStore eligibility determiner is listening...\");\n            this.store.when().verified(receipt => {\n                if (receipt.platform === CdvPurchase.Platform.APPLE_APPSTORE) {\n                    this.log.debug(\"Got a verified AppStore receipt.\");\n                    latestReceipt = receipt;\n                }\n            }, 'appStoreDiscountEligibilityDeterminer_listening');\n            const determiner = (_appStoreReceipt, requests, callback) => {\n                this.log.debug(\"AppStore eligibility determiner\");\n                if (latestReceipt) {\n                    this.log.debug(\"Using cached receipt\");\n                    return callback(analyzeReceipt(latestReceipt, requests));\n                }\n                const onVerified = (receipt) => {\n                    if (receipt.platform === CdvPurchase.Platform.APPLE_APPSTORE) {\n                        this.log.debug(\"Receipt is verified, let's analyze the content and respond.\");\n                        this.store.off(onVerified);\n                        callback(analyzeReceipt(receipt, requests));\n                    }\n                };\n                this.log.debug(\"Waiting for receipt\");\n                this.store.when().verified(onVerified, 'appStoreDiscountEligibilityDeterminer_waiting');\n            };\n            determiner.cacheReceipt = function (receipt) {\n                latestReceipt = receipt;\n            };\n            return determiner;\n            function analyzeReceipt(receipt, requests) {\n                const ineligibleIntro = receipt.raw.ineligible_for_intro_price;\n                return requests.map(request => {\n                    var _a;\n                    if (request.discountType === 'Introductory' && ineligibleIntro && ineligibleIntro.find(id => request.productId === id)) {\n                        // User is not eligible for this introductory offer\n                        return false;\n                    }\n                    else if (request.discountType === 'Subscription') {\n                        // Discount only available if user is or was a subscriber\n                        const matchingPurchase = (_a = receipt.raw.collection) === null || _a === void 0 ? void 0 : _a.find(purchase => purchase.id === request.productId);\n                        return matchingPurchase ? true : false;\n                    }\n                    else {\n                        // In other cases, assume the user is eligible\n                        return true;\n                    }\n                });\n            }\n        }\n        /** Validator URL */\n        get validator() {\n            return `${this.config.url}/v1/validate?appName=${this.config.appName}&apiKey=${this.config.apiKey}`;\n        }\n    }\n    CdvPurchase.Iaptic = Iaptic;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Desired logging level for the {@link Logger}\n     *\n     * @see {@link Store.verbosity}\n     */\n    let LogLevel;\n    (function (LogLevel) {\n        /** Disable all logging (default) */\n        LogLevel[LogLevel[\"QUIET\"] = 0] = \"QUIET\";\n        /** Show only error messages */\n        LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n        /** Show warnings and errors */\n        LogLevel[LogLevel[\"WARNING\"] = 2] = \"WARNING\";\n        /** Also show information messages */\n        LogLevel[LogLevel[\"INFO\"] = 3] = \"INFO\";\n        /** Enable internal debugging messages. */\n        LogLevel[LogLevel[\"DEBUG\"] = 4] = \"DEBUG\";\n    })(LogLevel = CdvPurchase.LogLevel || (CdvPurchase.LogLevel = {}));\n    ;\n    class Logger {\n        /** @internal */\n        constructor(store, prefix = '') {\n            /** All log lines are prefixed with this string */\n            this.prefix = '';\n            this.store = store;\n            this.prefix = prefix || 'CdvPurchase';\n        }\n        /**\n         * Create a child logger, whose prefix will be this one's + the given string.\n         *\n         * @example\n         * const log = store.log.child('AppStore')\n         */\n        child(prefix) {\n            return new Logger(this.store, this.prefix + '.' + prefix);\n        }\n        /**\n         * Logs an error message, only if `store.verbosity` >= store.ERROR\n         */\n        error(o) {\n            log(this.store.verbosity, LogLevel.ERROR, this.prefix, o);\n            // show the stack trace\n            try {\n                throw new Error(toString(o));\n            }\n            catch (e) {\n                log(this.store.verbosity, LogLevel.ERROR, this.prefix, e.stack);\n            }\n        }\n        /**\n         * Logs a warning message, only if `store.verbosity` >= store.WARNING\n         */\n        warn(o) { log(this.store.verbosity, LogLevel.WARNING, this.prefix, o); }\n        /**\n         * Logs an info message, only if `store.verbosity` >= store.INFO\n         */\n        info(o) { log(this.store.verbosity, LogLevel.INFO, this.prefix, o); }\n        /**\n         * Logs a debug message, only if `store.verbosity` >= store.DEBUG\n         */\n        debug(o) { log(this.store.verbosity, LogLevel.DEBUG, this.prefix, o); }\n        /**\n         * Add warning logs on a console describing an exception.\n         *\n         * This method is mostly used when executing user registered callbacks.\n         *\n         * @param context - a string describing why the method was called\n         * @param error - a javascript Error object thrown by an exception\n         */\n        logCallbackException(context, err) {\n            this.warn(\"A callback in \\'\" + context + \"\\' failed with an exception.\");\n            if (typeof err === 'string')\n                this.warn(\"           \" + err);\n            else if (err) {\n                const errAny = err;\n                if (errAny.fileName)\n                    this.warn(\"           \" + errAny.fileName + \":\" + errAny.lineNumber);\n                if (err.message)\n                    this.warn(\"           \" + err.message);\n                if (err.stack)\n                    this.warn(\"           \" + err.stack);\n            }\n        }\n    }\n    /**\n     * Console object used to display log lines.\n     *\n     * It can be replaced by your implementation if you want to, for example, send logs to a remote server.\n     *\n     * @example\n     * Logger.console = {\n     *   log: (message) => { remoteLog('LOG', message); },\n     *   warn: (message) => { remoteLog('WARN', message); },\n     *   error: (message) => { remoteLog('ERROR', message); }\n     * }\n     */\n    Logger.console = window.console;\n    CdvPurchase.Logger = Logger;\n    const LOG_LEVEL_STRING = [\"QUIET\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\"];\n    function toString(o) {\n        if (typeof o !== 'string')\n            o = JSON.stringify(o);\n        return o;\n    }\n    function log(verbosity, level, prefix, o) {\n        var maxLevel = verbosity === true ? 1 : verbosity;\n        if (level > maxLevel)\n            return;\n        if (typeof o !== 'string')\n            o = JSON.stringify(o);\n        const fullPrefix = prefix ? `[${prefix}] ` : '';\n        const logStr = (level === LogLevel.ERROR) ? ((str) => Logger.console.error(str))\n            : (level === LogLevel.WARNING) ? ((str) => Logger.console.warn(str))\n                : ((str) => Logger.console.log(str));\n        if (LOG_LEVEL_STRING[level])\n            logStr(`${fullPrefix}${LOG_LEVEL_STRING[level]}: ${o}`);\n        else\n            logStr(`${fullPrefix}${o}`);\n    }\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        Utils.nonEnumerable = (target, name, desc) => {\n            if (desc) {\n                desc.enumerable = false;\n                return desc;\n            }\n            Object.defineProperty(target, name, {\n                set(value) {\n                    Object.defineProperty(this, name, {\n                        value, writable: true, configurable: true,\n                    });\n                },\n                configurable: true,\n            });\n        };\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** Product definition from a store */\n    class Product {\n        /** @internal */\n        constructor(p, decorator) {\n            /** @internal */\n            this.className = 'Product';\n            /** Product title from the store. */\n            this.title = '';\n            /** Product full description from the store. */\n            this.description = '';\n            this.platform = p.platform;\n            this.type = p.type;\n            this.id = p.id;\n            this.group = p.group;\n            this.offers = [];\n            Object.defineProperty(this, 'pricing', { enumerable: false, get: () => { var _a; return (_a = this.offers[0]) === null || _a === void 0 ? void 0 : _a.pricingPhases[0]; } });\n            Object.defineProperty(this, 'canPurchase', { enumerable: false, get: () => decorator.canPurchase(this) });\n            Object.defineProperty(this, 'owned', { enumerable: false, get: () => decorator.owned(this) });\n        }\n        /**\n         * Shortcut to offers[0].pricingPhases[0]\n         *\n         * Useful when you know products have a single offer and a single pricing phase.\n         */\n        get pricing() {\n            var _a;\n            // see Object.defineProperty in the constructor for the actual implementation.\n            return (_a = this.offers[0]) === null || _a === void 0 ? void 0 : _a.pricingPhases[0];\n        }\n        /**\n         * Returns true if the product can be purchased.\n         */\n        get canPurchase() {\n            // Pseudo implementation to make typescript happy.\n            // see Object.defineProperty in the constructor for the actual implementation.\n            return false;\n        }\n        /**\n         * Returns true if the product is owned.\n         *\n         * Important: This value will be false when the app starts and will only become\n         * true after purchase receipts have been loaded and validated. Without receipt validation,\n         * it might remain false depending on the platform, make sure to store the ownership status\n         * of non-consumable products in some way.\n         */\n        get owned() {\n            // Pseudo implementation to make typescript happy.\n            // see Object.defineProperty in the constructor for the actual implementation.\n            return false;\n        }\n        /**\n         * Find and return an offer for this product from its id\n         *\n         * If id isn't specified, returns the first offer.\n         *\n         * @param id - Identifier of the offer to return\n         * @return An Offer or undefined if no match is found\n         */\n        getOffer(id = '') {\n            if (!id)\n                return this.offers[0];\n            return this.offers.find(o => o.id === id);\n        }\n        /**\n         * Add an offer to this product.\n         *\n         * @internal\n         */\n        addOffer(offer) {\n            if (this.getOffer(offer.id))\n                return this;\n            this.offers.push(offer);\n            return this;\n        }\n    }\n    CdvPurchase.Product = Product;\n})(CdvPurchase || (CdvPurchase = {}));\n// Functions defined here so we can generate code compatible with old version of JS\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /** Object.values() for ES6 */\n        function objectValues(obj) {\n            const ret = [];\n            for (let key in obj) {\n                if (obj.hasOwnProperty(key)) {\n                    ret.push(obj[key]);\n                }\n            }\n            return ret;\n        }\n        Utils.objectValues = objectValues;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /** Returns human format name for a given platform */\n        function platformName(platform) {\n            switch (platform) {\n                case CdvPurchase.Platform.APPLE_APPSTORE:\n                    return \"App Store\";\n                case CdvPurchase.Platform.GOOGLE_PLAY:\n                    return \"Google Play\";\n                case CdvPurchase.Platform.WINDOWS_STORE:\n                    return \"Windows Store\";\n                case CdvPurchase.Platform.BRAINTREE:\n                    return \"Braintree\";\n                case CdvPurchase.Platform.TEST:\n                    return \"Test\";\n                default: return platform;\n            }\n        }\n        Utils.platformName = platformName;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * @internal\n     */\n    let Internal;\n    (function (Internal) {\n        /** Queue of receipts to validate */\n        class ReceiptsToValidate {\n            constructor() {\n                this.array = [];\n            }\n            get length() {\n                return this.array.length;\n            }\n            get() {\n                return this.array.concat();\n            }\n            add(receipt) {\n                if (!this.has(receipt))\n                    this.array.push(receipt);\n            }\n            clear() {\n                while (this.array.length !== 0)\n                    this.array.pop();\n            }\n            has(receipt) {\n                return !!this.array.find(el => el === receipt);\n            }\n        }\n        Internal.ReceiptsToValidate = ReceiptsToValidate;\n        /** Handles communication with the remote receipt validation service */\n        class Validator {\n            constructor(controller, log) {\n                /** List of receipts waiting for validation */\n                this.receiptsToValidate = new ReceiptsToValidate();\n                /** List of verified receipts */\n                this.verifiedReceipts = [];\n                this.numRequests = 0;\n                this.numResponses = 0;\n                /**\n                 * For each md5-hashed values of the validator request's \".transaction\" field,\n                 * store the response from the server.\n                 *\n                 * This way, if a subsequent request is necessary (without a couple of minutes)\n                 * we just reuse the same data.\n                 */\n                this.cache = {};\n                this.controller = controller;\n                this.log = log.child('Validator');\n            }\n            incrRequestsCounter() {\n                this.numRequests = (this.numRequests + 1) | 0;\n                this.log.debug(`Validation requests=${this.numRequests} responses=${this.numResponses}`);\n            }\n            incrResponsesCounter() {\n                this.numResponses = (this.numResponses + 1) | 0;\n                this.log.debug(`Validation requests=${this.numRequests} responses=${this.numResponses}`);\n            }\n            /** Add/update a verified receipt from the server response */\n            addVerifiedReceipt(receipt, data) {\n                for (const vr of this.verifiedReceipts) {\n                    if (vr.platform === receipt.platform && vr.id === data.id) {\n                        // update existing receipt\n                        this.log.debug(\"Updating existing receipt.\");\n                        vr.set(receipt, data);\n                        return vr;\n                    }\n                }\n                this.log.debug(\"Register a new verified receipt.\");\n                const newVR = new CdvPurchase.VerifiedReceipt(receipt, data, this.controller);\n                this.verifiedReceipts.push(newVR);\n                return newVR;\n            }\n            /** Add a receipt to the validation queue. It'll get validated after a few milliseconds. */\n            add(receiptOrTransaction) {\n                this.log.debug(\"Schedule validation: \" + JSON.stringify(receiptOrTransaction));\n                const receipt = (receiptOrTransaction instanceof CdvPurchase.Transaction) ? receiptOrTransaction.parentReceipt : receiptOrTransaction;\n                if (!this.receiptsToValidate.has(receipt)) {\n                    this.incrRequestsCounter();\n                    this.receiptsToValidate.add(receipt);\n                }\n            }\n            /** Run validation for all receipts in the queue */\n            run() {\n                // pseudo implementation\n                const receipts = this.receiptsToValidate.get();\n                this.receiptsToValidate.clear();\n                const onResponse = (r) => __awaiter(this, void 0, void 0, function* () {\n                    var _a;\n                    const { receipt, payload } = r;\n                    this.incrResponsesCounter();\n                    try {\n                        const adapter = this.controller.adapters.find(receipt.platform);\n                        yield (adapter === null || adapter === void 0 ? void 0 : adapter.handleReceiptValidationResponse(receipt, payload));\n                        if (payload.ok) {\n                            const vr = this.addVerifiedReceipt(receipt, payload.data);\n                            this.controller.verifiedCallbacks.trigger(vr, 'payload_ok');\n                            // this.verifiedCallbacks.trigger(data.receipt);\n                        }\n                        else if (payload.code === CdvPurchase.ErrorCode.VALIDATOR_SUBSCRIPTION_EXPIRED) {\n                            // find the subscription in an existing verified receipt and mark as expired.\n                            const transactionId = (_a = receipt.lastTransaction()) === null || _a === void 0 ? void 0 : _a.transactionId;\n                            const vr = transactionId ? this.verifiedReceipts.find(r => { var _a; return ((_a = r.collection[0]) === null || _a === void 0 ? void 0 : _a.transactionId) === transactionId; }) : undefined;\n                            if (vr) {\n                                vr === null || vr === void 0 ? void 0 : vr.collection.forEach(col => {\n                                    if (col.transactionId === transactionId)\n                                        col.isExpired = true;\n                                });\n                                this.controller.verifiedCallbacks.trigger(vr, 'payload_expired');\n                            }\n                            else {\n                                this.controller.unverifiedCallbacks.trigger({ receipt, payload }, 'no_verified_receipt');\n                            }\n                        }\n                        else {\n                            this.controller.unverifiedCallbacks.trigger({ receipt, payload }, 'validator_error');\n                        }\n                    }\n                    catch (err) {\n                        this.log.error('Exception probably caused by an invalid response from the validator.' + err.message);\n                        this.controller.unverifiedCallbacks.trigger({ receipt, payload: {\n                                ok: false,\n                                code: CdvPurchase.ErrorCode.VERIFICATION_FAILED,\n                                message: err.message,\n                            } }, 'validator_exception');\n                    }\n                });\n                receipts.forEach(receipt => this.runOnReceipt(receipt, onResponse));\n            }\n            runOnReceipt(receipt, callback) {\n                var _a, _b;\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (receipt.platform === CdvPurchase.Platform.TEST) {\n                        this.log.debug('Using Test Adapter mock verify function.');\n                        return CdvPurchase.Test.Adapter.verify(receipt, callback);\n                    }\n                    if (!this.controller.validator) {\n                        this.incrResponsesCounter();\n                        // for backward compatibility, we consider that the receipt is verified.\n                        callback({\n                            receipt,\n                            payload: {\n                                ok: true,\n                                data: {\n                                    id: ((_b = (_a = receipt.transactions) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.transactionId) || 'unknown',\n                                    latest_receipt: true,\n                                    transaction: { type: 'test' } // dummy data\n                                }\n                            }\n                        });\n                        return;\n                    }\n                    const body = yield this.buildRequestBody(receipt);\n                    if (!body) {\n                        this.incrResponsesCounter();\n                        return;\n                    }\n                    if (typeof this.controller.validator === 'function')\n                        return this.runValidatorFunction(this.controller.validator, receipt, body, callback);\n                    const target = typeof this.controller.validator === 'string'\n                        ? {\n                            url: this.controller.validator,\n                            timeout: 20000, // validation request will timeout after 20 seconds by default\n                        }\n                        : this.controller.validator;\n                    return this.runValidatorRequest(target, receipt, body, callback);\n                });\n            }\n            runValidatorFunction(validator, receipt, body, callback) {\n                try {\n                    validator(body, (payload) => callback({ receipt, payload }));\n                }\n                catch (error) {\n                    this.log.warn(\"user provided validator function failed with error: \" + (error === null || error === void 0 ? void 0 : error.stack));\n                }\n            }\n            buildRequestBody(receipt) {\n                var _a, _b, _c;\n                return __awaiter(this, void 0, void 0, function* () {\n                    // Let the adapter generate the initial content\n                    const adapter = this.controller.adapters.find(receipt.platform);\n                    const body = yield (adapter === null || adapter === void 0 ? void 0 : adapter.receiptValidationBody(receipt));\n                    if (!body)\n                        return;\n                    // Add the applicationUsername\n                    body.additionalData = Object.assign(Object.assign({}, (_a = body.additionalData) !== null && _a !== void 0 ? _a : {}), { applicationUsername: this.controller.getApplicationUsername() });\n                    if (!body.additionalData.applicationUsername)\n                        delete body.additionalData.applicationUsername;\n                    // Add device information\n                    body.device = Object.assign(Object.assign({}, (_b = body.device) !== null && _b !== void 0 ? _b : {}), CdvPurchase.Validator.Internal.getDeviceInfo(this.controller));\n                    // Add legacy pricing information\n                    if (((_c = body.offers) === null || _c === void 0 ? void 0 : _c.length) === 1) {\n                        const offer = body.offers[0];\n                        if (offer.pricingPhases.length === 1) {\n                            const pricing = offer.pricingPhases[0];\n                            body.currency = pricing.currency;\n                            body.priceMicros = pricing.priceMicros;\n                        }\n                        else if (offer.pricingPhases.length === 2) {\n                            const pricing = offer.pricingPhases[1];\n                            body.currency = pricing.currency;\n                            body.priceMicros = pricing.priceMicros;\n                            const intro = offer.pricingPhases[0];\n                            body.introPriceMicros = intro.priceMicros;\n                        }\n                    }\n                    return body;\n                });\n            }\n            removeExpiredCache() {\n                const now = +new Date();\n                const deleteList = [];\n                for (const hash in this.cache) {\n                    if (this.cache[hash].expires < now) {\n                        deleteList.push(hash);\n                    }\n                }\n                for (const hash of deleteList) {\n                    delete this.cache[hash];\n                }\n            }\n            runValidatorRequest(target, receipt, body, callback) {\n                this.removeExpiredCache();\n                const bodyTransactionHash = CdvPurchase.Utils.md5(JSON.stringify(body.transaction));\n                const cached = this.cache[bodyTransactionHash];\n                if (cached) {\n                    this.log.debug(\"validator cache hit, using cached response\");\n                    return callback({ receipt, payload: cached.payload });\n                }\n                CdvPurchase.Utils.ajax(this.log.child(\"Ajax\"), {\n                    url: target.url,\n                    method: 'POST',\n                    customHeaders: target.headers,\n                    timeout: target.timeout,\n                    data: body,\n                    success: (response) => {\n                        var _a;\n                        this.log.debug(\"validator success, response: \" + JSON.stringify(response));\n                        if (!isValidatorResponsePayload(response))\n                            return callback({\n                                receipt,\n                                payload: {\n                                    ok: false,\n                                    code: CdvPurchase.ErrorCode.BAD_RESPONSE,\n                                    message: 'Validator responded with invalid data',\n                                    data: { latest_receipt: (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.latest_receipt },\n                                }\n                            });\n                        this.cache[bodyTransactionHash] = {\n                            payload: response,\n                            expires: (+new Date()) + 120000, // expires in 2 minutes\n                        };\n                        callback({ receipt, payload: response });\n                    },\n                    error: (status, message, data) => {\n                        var fullMessage = \"Error \" + status + \": \" + message;\n                        this.log.debug(\"validator failed, response: \" + JSON.stringify(fullMessage));\n                        this.log.debug(\"body => \" + JSON.stringify(data));\n                        callback({\n                            receipt,\n                            payload: {\n                                ok: false,\n                                message: fullMessage,\n                                code: CdvPurchase.ErrorCode.COMMUNICATION,\n                                status: status,\n                                data: {},\n                            }\n                        });\n                    }\n                });\n            }\n        }\n        Internal.Validator = Validator;\n        /**\n         * Check if a payload looks like a valid validator response.\n         */\n        function isValidatorResponsePayload(payload) {\n            // TODO: could be made more robust.\n            return (!!payload)\n                && (typeof payload === 'object')\n                && ('ok' in payload)\n                && (typeof payload.ok === 'boolean');\n        }\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** @internal */\n    let Internal;\n    (function (Internal) {\n        /**\n         * The list of active platform adapters\n         */\n        class Adapters {\n            constructor() {\n                /**\n                 * List of instantiated adapters.\n                 *\n                 * They are added to this list by \"initialize()\".\n                 */\n                this.list = [];\n            }\n            add(log, adapters, context) {\n                adapters.forEach(po => {\n                    log.info(\"\");\n                    if (this.find(po.platform))\n                        return;\n                    switch (po.platform) {\n                        case CdvPurchase.Platform.APPLE_APPSTORE:\n                            return this.list.push(new CdvPurchase.AppleAppStore.Adapter(context, po.options || {}));\n                        case CdvPurchase.Platform.GOOGLE_PLAY:\n                            return this.list.push(new CdvPurchase.GooglePlay.Adapter(context));\n                        case CdvPurchase.Platform.BRAINTREE:\n                            if (!po.options) {\n                                log.error('Options missing for Braintree initialization. Use {platform: Platform.BRAINTREE, options: {...}} in your call to store.initialize');\n                            }\n                            return this.list.push(new CdvPurchase.Braintree.Adapter(context, po.options));\n                        case CdvPurchase.Platform.TEST:\n                            return this.list.push(new CdvPurchase.Test.Adapter(context));\n                        default:\n                            return;\n                    }\n                });\n            }\n            /**\n             * Initialize some platform adapters.\n             */\n            initialize(platforms, context) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (typeof platforms === 'string') {\n                        platforms = [platforms];\n                    }\n                    const newPlatforms = platforms.map(p => typeof p === 'string' ? { platform: p } : p).filter(p => !this.find(p.platform));\n                    const log = context.log.child('Adapters');\n                    log.info(\"Adding platforms: \" + JSON.stringify(newPlatforms));\n                    this.add(log, newPlatforms, context);\n                    const products = context.registeredProducts.byPlatform();\n                    const result = yield Promise.all(newPlatforms.map((platformToInit) => __awaiter(this, void 0, void 0, function* () {\n                        var _a, _b, _c;\n                        const platformProducts = (_c = (_b = (_a = products.filter(p => p.platform === platformToInit.platform)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.products) !== null && _c !== void 0 ? _c : [];\n                        const adapter = this.find(platformToInit.platform);\n                        if (!adapter)\n                            return;\n                        log.info(`${adapter.name} initializing...`);\n                        if (!adapter.isSupported) {\n                            log.info(`${adapter.name} is not supported.`);\n                            return; // skip unsupported adapters\n                        }\n                        const initResult = yield adapter.initialize();\n                        adapter.ready = true;\n                        log.info(`${adapter.name} initialized. ${initResult ? JSON.stringify(initResult) : ''}`);\n                        if (initResult === null || initResult === void 0 ? void 0 : initResult.code)\n                            return initResult;\n                        log.info(`${adapter.name} products: ${JSON.stringify(platformProducts)}`);\n                        if (platformProducts.length === 0)\n                            return;\n                        let loadProductsResult = [];\n                        let loadReceiptsResult = [];\n                        if (adapter.supportsParallelLoading) {\n                            [loadProductsResult, loadReceiptsResult] = yield Promise.all([\n                                adapter.loadProducts(platformProducts),\n                                adapter.loadReceipts()\n                            ]);\n                        }\n                        else {\n                            loadProductsResult = yield adapter.loadProducts(platformProducts);\n                            loadReceiptsResult = yield adapter.loadReceipts();\n                        }\n                        // const loadProductsResult = await adapter.loadProducts(platformProducts);\n                        log.info(`${adapter.name} products loaded: ${JSON.stringify(loadProductsResult)}`);\n                        const loadedProducts = loadProductsResult.filter(p => p instanceof CdvPurchase.Product);\n                        context.listener.productsUpdated(platformToInit.platform, loadedProducts);\n                        // const loadReceiptsResult = await adapter.loadReceipts();\n                        log.info(`${adapter.name} receipts loaded: ${JSON.stringify(loadReceiptsResult)}`);\n                        return loadProductsResult.filter(lr => 'code' in lr && 'message' in lr)[0];\n                    })));\n                    return result.filter(err => err);\n                });\n            }\n            /**\n             * Retrieve a platform adapter.\n             */\n            find(platform) {\n                return this.list.filter(a => a.id === platform)[0];\n            }\n            /**\n             * Retrieve the first platform adapter in the ready state, if any.\n             *\n             * You can optionally force the platform adapter you are looking for.\n             *\n             * Useful for methods that accept an optional \"platform\" argument, so they either act\n             * on the only active adapter or on the one selected by the user, if it's ready.\n             */\n            findReady(platform) {\n                return this.list.filter(adapter => (!platform || adapter.id === platform) && adapter.ready)[0];\n            }\n        }\n        Internal.Adapters = Adapters;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /**\n         * Monitor the updates for products and receipt.\n         *\n         * Call the callbacks when appropriate.\n         */\n        class StoreAdapterListener {\n            constructor(delegate, log) {\n                /** The list of supported platforms, needs to be set by \"store.initialize\" */\n                this.supportedPlatforms = [];\n                /** Those platforms have reported that their receipts are ready */\n                this.platformWithReceiptsReady = [];\n                this.lastTransactionState = {};\n                /** Store the listener's latest calling time (in ms) for a given transaction at a given state */\n                this.lastCallTimeForState = {};\n                this.updatedReceiptsToProcess = [];\n                this.delegate = delegate;\n                this.log = log.child('AdapterListener');\n            }\n            static makeTransactionToken(transaction) {\n                return transaction.platform + '|' + transaction.transactionId;\n            }\n            /**\n             * Set the list of supported platforms.\n             *\n             * Called by the store when it is initialized.\n             */\n            setSupportedPlatforms(platforms) {\n                this.log.debug(`setSupportedPlatforms: ${platforms.join(',')} (${this.platformWithReceiptsReady.length} have their receipts ready)`);\n                this.supportedPlatforms = platforms;\n                if (this.supportedPlatforms.length === this.platformWithReceiptsReady.length) {\n                    this.log.debug('triggering receiptsReady()');\n                    this.delegate.receiptsReadyCallbacks.trigger(undefined, 'adapterListener_setSupportedPlatforms');\n                }\n            }\n            /**\n             * Trigger the \"receiptsReady\" event when all platforms have reported that their receipts are ready.\n             *\n             * This function is used by adapters to report that their receipts are ready.\n             * Once all adapters have reported their receipts, the \"receiptsReady\" event is triggered.\n             *\n             * @param platform The platform that has its receipts ready.\n             */\n            receiptsReady(platform) {\n                if (this.supportedPlatforms.length > 0 && this.platformWithReceiptsReady.length === this.supportedPlatforms.length) {\n                    this.log.debug('receiptsReady: ' + platform + '(skipping)');\n                    return;\n                }\n                if (this.platformWithReceiptsReady.indexOf(platform) < 0) {\n                    this.platformWithReceiptsReady.push(platform);\n                    this.log.debug(`receiptsReady: ${platform} (${this.platformWithReceiptsReady.length}/${this.supportedPlatforms.length})`);\n                    if (this.platformWithReceiptsReady.length === this.supportedPlatforms.length) {\n                        this.log.debug('triggering receiptsReady()');\n                        this.delegate.receiptsReadyCallbacks.trigger(undefined, 'adapterListener_receiptsReady');\n                    }\n                }\n            }\n            /**\n             * Trigger the \"updated\" event for each product.\n             */\n            productsUpdated(platform, products) {\n                products.forEach(product => this.delegate.updatedCallbacks.trigger(product, 'adapterListener_productsUpdated'));\n            }\n            /**\n             * Triggers the \"approved\", \"pending\" and \"finished\" events for transactions.\n             *\n             * - \"approved\" is triggered only if it hasn't been called for the same transaction in the last 5 seconds.\n             * - \"finished\" and \"pending\" are triggered only if the transaction state has changed.\n             *\n             * @param platform The platform that has its receipts updated.\n             * @param receipts The receipts that have been updated.\n             */\n            receiptsUpdated(platform, receipts) {\n                this.log.debug(\"receiptsUpdated: \" + JSON.stringify(receipts.map(r => ({\n                    platform: r.platform,\n                    transactions: r.transactions,\n                }))));\n                for (const receipt of receipts) {\n                    if (this.updatedReceiptsToProcess.indexOf(receipt) < 0) {\n                        this.updatedReceiptsToProcess.push(receipt);\n                    }\n                }\n                if (this.updatedReceiptsProcessor !== undefined) {\n                    clearTimeout(this.updatedReceiptsProcessor);\n                }\n                this.updatedReceiptsProcessor = setTimeout(() => {\n                    this._processUpdatedReceipts();\n                }, 500);\n            }\n            _processUpdatedReceipts() {\n                this.log.debug(\"processing \" + this.updatedReceiptsToProcess.length + \" updated receipts\");\n                const now = +new Date();\n                const receipts = this.updatedReceiptsToProcess;\n                this.updatedReceiptsToProcess = [];\n                receipts.forEach(receipt => {\n                    this.delegate.updatedReceiptCallbacks.trigger(receipt, 'adapterListener_receiptsUpdated');\n                    receipt.transactions.forEach(transaction => {\n                        var _a;\n                        const transactionToken = StoreAdapterListener.makeTransactionToken(transaction);\n                        const tokenWithState = transactionToken + '@' + transaction.state;\n                        const lastState = this.lastTransactionState[transactionToken];\n                        // Retrigger \"approved\", so validation is rerun on potential update.\n                        if (transaction.state === CdvPurchase.TransactionState.APPROVED) {\n                            // prevent calling approved twice in a very short period (60 seconds).\n                            const lastCalled = (_a = this.lastCallTimeForState[tokenWithState]) !== null && _a !== void 0 ? _a : 0;\n                            if (now - lastCalled > 60000) {\n                                this.lastCallTimeForState[tokenWithState] = now;\n                                this.delegate.approvedCallbacks.trigger(transaction, 'adapterListener_receiptsUpdated_approved');\n                            }\n                            else {\n                                this.log.debug(`Skipping ${tokenWithState}, because it has been last called ${lastCalled > 0 ? Math.round(now - lastCalled) + 'ms ago (' + now + '-' + lastCalled + ')' : 'never'}`);\n                            }\n                        }\n                        else if (lastState !== transaction.state) {\n                            if (transaction.state === CdvPurchase.TransactionState.INITIATED) {\n                                this.lastCallTimeForState[tokenWithState] = now;\n                                this.delegate.initiatedCallbacks.trigger(transaction, 'adapterListener_receiptsUpdated_initiated');\n                            }\n                            else if (transaction.state === CdvPurchase.TransactionState.FINISHED) {\n                                this.lastCallTimeForState[tokenWithState] = now;\n                                this.delegate.finishedCallbacks.trigger(transaction, 'adapterListener_receiptsUpdated_finished');\n                            }\n                            else if (transaction.state === CdvPurchase.TransactionState.PENDING) {\n                                this.lastCallTimeForState[tokenWithState] = now;\n                                this.delegate.pendingCallbacks.trigger(transaction, 'adapterListener_receiptsUpdated_pending');\n                            }\n                        }\n                        this.lastTransactionState[transactionToken] = transaction.state;\n                    });\n                });\n            }\n        }\n        Internal.StoreAdapterListener = StoreAdapterListener;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /**\n         * Manage a list of callbacks\n         */\n        class Callbacks {\n            /**\n             * @param className - Type of callbacks (used to help with debugging)\n             * @param finalStateMode - If true, newly registered callbacks will be called immediately when the event was already triggered.\n             */\n            constructor(logger, className, finalStateMode = false) {\n                /** List of registered callbacks */\n                this.callbacks = [];\n                /** Number of times those callbacks have been triggered */\n                this.numTriggers = 0;\n                this.logger = logger;\n                this.className = className;\n                this.finalStateMode = finalStateMode;\n            }\n            /** Add a callback to the list */\n            push(callback, callbackName) {\n                if (this.finalStateMode && this.numTriggers > 0) {\n                    callback(this.lastTriggerArgument);\n                }\n                else {\n                    // Detecting double registration to help with debugging issues\n                    for (const existing of this.callbacks) {\n                        if (existing.callback === callback) {\n                            throw new Error('REGISTERING THE SAME CALLBACK TWICE? This is indicative of a bug in your integration.');\n                        }\n                    }\n                    this.callbacks.push({ callback, callbackName });\n                }\n            }\n            /** Call all registered callbacks with the given value */\n            trigger(value, reason) {\n                this.lastTriggerArgument = value;\n                this.numTriggers++;\n                const callbacks = this.callbacks;\n                if (this.finalStateMode) {\n                    // in final state mode, callbacks are only triggered once\n                    this.callbacks = [];\n                }\n                callbacks.forEach(callback => {\n                    CdvPurchase.Utils.safeCall(this.logger, this.className, callback.callback, value, callback.callbackName, reason);\n                });\n            }\n            /** Remove a callback from the list */\n            remove(callback) {\n                this.callbacks = this.callbacks.filter(el => el.callback !== callback);\n            }\n        }\n        Internal.Callbacks = Callbacks;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** @internal */\n    let Internal;\n    (function (Internal) {\n        /**\n         * Ready callbacks\n         */\n        class ReadyCallbacks {\n            constructor(logger) {\n                /** True when the plugin is ready */\n                this.isReady = false;\n                /** Callbacks when the store is ready */\n                this.readyCallbacks = [];\n                this.logger = logger;\n            }\n            /** Register a callback to be called when the plugin is ready. */\n            add(cb) {\n                if (this.isReady)\n                    return setTimeout(cb, 0);\n                this.readyCallbacks.push(cb);\n            }\n            /** Calls the ready callbacks */\n            trigger(reason) {\n                this.isReady = true;\n                this.readyCallbacks.forEach(cb => CdvPurchase.Utils.safeCall(this.logger, 'ready()', cb, undefined, undefined, reason));\n                this.readyCallbacks = [];\n            }\n            remove(cb) {\n                this.readyCallbacks = this.readyCallbacks.filter(el => el !== cb);\n            }\n        }\n        Internal.ReadyCallbacks = ReadyCallbacks;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        function isValidRegisteredProduct(product) {\n            if (typeof product !== 'object')\n                return false;\n            return product.hasOwnProperty('platform')\n                && product.hasOwnProperty('id')\n                && product.hasOwnProperty('type');\n        }\n        class RegisteredProducts {\n            constructor() {\n                this.list = [];\n            }\n            find(platform, id) {\n                return this.list.find(rp => rp.platform === platform && rp.id === id);\n            }\n            add(product) {\n                const errors = [];\n                const products = Array.isArray(product) ? product : [product];\n                const newProducts = products.filter(p => !this.find(p.platform, p.id));\n                for (const p of newProducts) {\n                    if (isValidRegisteredProduct(p))\n                        this.list.push(p);\n                    else\n                        errors.push(CdvPurchase.storeError(CdvPurchase.ErrorCode.LOAD, 'Invalid parameter to \"register\", expected \"id\", \"type\" and \"platform\". '\n                            + 'Got: ' + JSON.stringify(p), null, null));\n                }\n                return errors;\n            }\n            byPlatform() {\n                const byPlatform = {};\n                this.list.forEach(p => {\n                    byPlatform[p.platform] = (byPlatform[p.platform] || []).concat(p);\n                });\n                return Object.keys(byPlatform).map(platform => ({\n                    platform: platform,\n                    products: byPlatform[platform]\n                }));\n            }\n        }\n        Internal.RegisteredProducts = RegisteredProducts;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** @internal */\n    let Internal;\n    (function (Internal) {\n        /**\n         * Helper class to monitor changes in transaction states.\n         *\n         * @example\n         * const monitor = monitors.start(transaction, (state) => {\n         *   // ... transaction state has changed\n         * });\n         * monitor.stop();\n         */\n        class TransactionStateMonitors {\n            constructor(when) {\n                this.monitors = [];\n                this.isListening = false;\n                this.when = when;\n            }\n            findMonitors(transaction) {\n                return this.monitors.filter(monitor => monitor.transaction.platform === transaction.platform\n                    && monitor.transaction.transactionId === transaction.transactionId);\n            }\n            startListening() {\n                if (this.isListening) {\n                    return;\n                }\n                this.isListening = true;\n                this.when\n                    .approved(transaction => this.callOnChange(transaction), 'transactionStateMonitors_callOnChange')\n                    .finished(transaction => this.callOnChange(transaction), 'transactionStateMonitors_callOnChange');\n            }\n            callOnChange(transaction) {\n                this.findMonitors(transaction).forEach(monitor => {\n                    if (monitor.lastChange !== transaction.state) {\n                        monitor.lastChange = transaction.state;\n                        monitor.onChange(transaction.state);\n                    }\n                });\n            }\n            /**\n             * Start monitoring the provided transaction for state changes.\n             */\n            start(transaction, onChange) {\n                this.startListening();\n                const monitorId = CdvPurchase.Utils.uuidv4();\n                this.monitors.push({ monitorId, transaction, onChange, lastChange: transaction.state });\n                setTimeout(onChange, 0, transaction.state);\n                return {\n                    transaction,\n                    stop: () => this.stop(monitorId),\n                };\n            }\n            stop(monitorId) {\n                this.monitors = this.monitors.filter(m => m.monitorId !== monitorId);\n            }\n        }\n        Internal.TransactionStateMonitors = TransactionStateMonitors;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        class ReceiptsMonitor {\n            constructor(controller) {\n                this.hasCalledReceiptsVerified = false;\n                this.controller = controller;\n                this.log = controller.log.child('ReceiptsMonitor');\n            }\n            callReceiptsVerified() {\n                if (this.hasCalledReceiptsVerified)\n                    return;\n                this.hasCalledReceiptsVerified = true;\n                this.log.info('receiptsVerified()');\n                // ensure those 2 events are called in order.\n                this.controller.when().receiptsReady(() => {\n                    setTimeout(() => {\n                        this.controller.receiptsVerified();\n                    }, 0);\n                }, 'receiptsMonitor_callReceiptsVerified');\n            }\n            launch() {\n                const check = () => {\n                    this.log.debug(`check(${this.controller.numValidationResponses()}/${this.controller.numValidationRequests()})`);\n                    if (this.controller.numValidationRequests() === this.controller.numValidationResponses()) {\n                        if (this.intervalChecker !== undefined) {\n                            clearInterval(this.intervalChecker);\n                            this.intervalChecker = undefined;\n                        }\n                        this.controller.off(check);\n                        this.callReceiptsVerified();\n                    }\n                };\n                this.controller.when()\n                    .verified(check, 'receiptsMonitor_check')\n                    .unverified(check, 'receiptsMonitor_check')\n                    .receiptsReady(() => {\n                    this.log.debug('receiptsReady...');\n                    if (!this.controller.hasLocalReceipts() || !this.controller.hasValidator()) {\n                        setTimeout(() => {\n                            check();\n                        }, 0);\n                    }\n                    // check every 10s, to handle cases where neither \"verified\" nor \"unverified\" have been triggered.\n                    this.intervalChecker = setInterval(() => {\n                        this.log.debug('keep checking every 10s...');\n                        check();\n                    }, 10000);\n                }, 'receiptsMonitor_setup');\n            }\n        }\n        Internal.ReceiptsMonitor = ReceiptsMonitor;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /**\n         * Send a notification when a subscription expires.\n         *\n         * The platform doesn't send notifications when a subscription expires.\n         *\n         * However this is useful, so let's do just that.\n         */\n        class ExpiryMonitor {\n            /** Track active local transactions */\n            // activeTransactions: {\n            //   [transactionId: string]: true;\n            // } = {};\n            /** Track notified local transactions */\n            // notifiedTransactions: {\n            //   [transactionId: string]: true;\n            // } = {};\n            constructor(controller) {\n                /** Track active verified purchases */\n                this.activePurchases = {};\n                /** Track notified verified purchases */\n                this.notifiedPurchases = {};\n                this.controller = controller;\n            }\n            launch() {\n                this.interval = setInterval(() => {\n                    var _a, _b;\n                    const now = +new Date();\n                    // Check for verified purchases expiry\n                    for (const receipt of this.controller.verifiedReceipts) {\n                        const gracePeriod = (_a = ExpiryMonitor.GRACE_PERIOD_MS[receipt.platform]) !== null && _a !== void 0 ? _a : ExpiryMonitor.GRACE_PERIOD_MS.DEFAULT;\n                        for (const purchase of receipt.collection) {\n                            if (purchase.expiryDate) {\n                                const expiryDate = purchase.expiryDate + gracePeriod;\n                                const transactionId = (_b = purchase.transactionId) !== null && _b !== void 0 ? _b : `${expiryDate}`;\n                                if (expiryDate > now) {\n                                    this.activePurchases[transactionId] = true;\n                                }\n                                if (expiryDate < now && this.activePurchases[transactionId] && !this.notifiedPurchases[transactionId]) {\n                                    this.notifiedPurchases[transactionId] = true;\n                                    this.controller.onVerifiedPurchaseExpired(purchase, receipt);\n                                }\n                            }\n                        }\n                    }\n                    // Check for local purchases expiry\n                    // for (const receipt of this.controller.localReceipts) {\n                    //   for (const transaction of receipt.transactions) {\n                    //     if (transaction.expirationDate) {\n                    //       const expirationDate = +transaction.expirationDate + ExpiryMonitor.GRACE_PERIOD_MS;\n                    //       const transactionId = transaction.transactionId ?? `${expirationDate}`;\n                    //       if (expirationDate > now) {\n                    //         this.activeTransactions[transactionId] = true;\n                    //       }\n                    //       if (expirationDate < now && this.activeTransactions[transactionId] && !this.notifiedTransactions[transactionId]) {\n                    //         this.notifiedTransactions[transactionId] = true;\n                    //         this.controller.onTransactionExpired(transaction);\n                    //       }\n                    //     }\n                    //   }\n                    // }\n                }, ExpiryMonitor.INTERVAL_MS);\n            }\n        }\n        /** Time between checks for newly expired subscriptions */\n        ExpiryMonitor.INTERVAL_MS = 10000;\n        /**\n         * Extra time until re-validating an expired subscription.\n         *\n         * The platform will take unspecified amount of time to report the renewal via their APIs.\n         * Values below have been selected via trial-and-error, might require tweaking.\n         */\n        ExpiryMonitor.GRACE_PERIOD_MS = {\n            DEFAULT: 60000,\n            \"ios-appstore\": 60000,\n            \"android-playstore\": 30000,\n        };\n        Internal.ExpiryMonitor = ExpiryMonitor;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"types.ts\" />\n/// <reference path=\"utils/compatibility.ts\" />\n/// <reference path=\"utils/platform-name.ts\" />\n/// <reference path=\"validator/validator.ts\" />\n/// <reference path=\"log.ts\" />\n/// <reference path=\"internal/adapters.ts\" />\n/// <reference path=\"internal/adapter-listener.ts\" />\n/// <reference path=\"internal/callbacks.ts\" />\n/// <reference path=\"internal/ready.ts\" />\n/// <reference path=\"internal/register.ts\" />\n/// <reference path=\"internal/transaction-monitor.ts\" />\n/// <reference path=\"internal/receipts-monitor.ts\" />\n/// <reference path=\"internal/expiry-monitor.ts\" />\n/**\n * Namespace for the cordova-plugin-purchase plugin.\n *\n * All classes, enumerations and variables defined by the plugin are in this namespace.\n *\n * Throughout the documentation, in order to keep examples readable, we omit the `CdvPurchase` prefix.\n *\n * When you see, for example `ProductType.PAID_SUBSCRIPTION`, it refers to `CdvPurchase.ProductType.PAID_SUBSCRIPTION`.\n *\n * In the files that interact with the plugin, I recommend creating those shortcuts (and more if needed):\n *\n * ```ts\n * const {store, ProductType, Platform, LogLevel} = CdvPurchase;\n * ```\n */\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Current release number of the plugin.\n     */\n    CdvPurchase.PLUGIN_VERSION = '13.12.1';\n    /**\n     * Entry class of the plugin.\n     */\n    class Store {\n        constructor() {\n            /**\n             * Payment platform adapters.\n             */\n            this.adapters = new CdvPurchase.Internal.Adapters();\n            /**\n             * List of registered products.\n             *\n             * Products are added to this list of products by {@link Store.register}, an internal job will defer loading to the platform adapters.\n             */\n            this.registeredProducts = new CdvPurchase.Internal.RegisteredProducts();\n            /** Logger */\n            this.log = new CdvPurchase.Logger(this);\n            /**\n             * Verbosity level used by the plugin logger\n             *\n             * Set to:\n             *\n             *  - LogLevel.QUIET or 0 to disable all logging (default)\n             *  - LogLevel.ERROR or 1 to show only error messages\n             *  - LogLevel.WARNING or 2 to show warnings and errors\n             *  - LogLevel.INFO or 3 to also show information messages\n             *  - LogLevel.DEBUG or 4 to enable internal debugging messages.\n             *\n             * @see {@link LogLevel}\n             */\n            this.verbosity = CdvPurchase.LogLevel.ERROR;\n            /** List of callbacks for the \"ready\" events */\n            this._readyCallbacks = new CdvPurchase.Internal.ReadyCallbacks(this.log);\n            /** Callbacks when a product definition was updated */\n            this.updatedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'productUpdated()');\n            /** Callback when a receipt was updated */\n            this.updatedReceiptsCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'receiptUpdated()');\n            /** Callbacks when a product is owned */\n            // private ownedCallbacks = new Callbacks<Product>();\n            /** Callbacks when a transaction is initiated */\n            this.initiatedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'initiated()');\n            /** Callbacks when a transaction has been approved */\n            this.approvedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'approved()');\n            /** Callbacks when a transaction has been finished */\n            this.finishedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'finished()');\n            /** Callbacks when a transaction is pending */\n            this.pendingCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'pending()');\n            /** Callbacks when a receipt has been validated */\n            this.verifiedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'verified()');\n            /** Callbacks when a receipt has been validated */\n            this.unverifiedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'unverified()');\n            /** Callbacks when all receipts have been loaded */\n            this.receiptsReadyCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'receiptsReady()', true);\n            /** Callbacks when all receipts have been verified */\n            this.receiptsVerifiedCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'receiptsVerified()', true);\n            /** Callbacks for errors */\n            this.errorCallbacks = new CdvPurchase.Internal.Callbacks(this.log, 'error()');\n            this.initializedHasBeenCalled = false;\n            /** Stores the last time the store was updated (or initialized), to skip calls in quick succession. */\n            this.lastUpdate = 0;\n            /**\n             * Avoid invoking store.update() if the most recent call occurred within this specific number of milliseconds.\n             */\n            this.minTimeBetweenUpdates = 600000;\n            /**\n             * Version of the plugin currently installed.\n             */\n            this.version = CdvPurchase.PLUGIN_VERSION;\n            const store = this;\n            this.listener = new CdvPurchase.Internal.StoreAdapterListener({\n                updatedCallbacks: this.updatedCallbacks,\n                updatedReceiptCallbacks: this.updatedReceiptsCallbacks,\n                initiatedCallbacks: this.initiatedCallbacks,\n                approvedCallbacks: this.approvedCallbacks,\n                finishedCallbacks: this.finishedCallbacks,\n                pendingCallbacks: this.pendingCallbacks,\n                receiptsReadyCallbacks: this.receiptsReadyCallbacks,\n            }, this.log);\n            this.transactionStateMonitors = new CdvPurchase.Internal.TransactionStateMonitors(this.when());\n            this._validator = new CdvPurchase.Internal.Validator({\n                adapters: this.adapters,\n                getApplicationUsername: this.getApplicationUsername.bind(this),\n                get localReceipts() { return store.localReceipts; },\n                get validator() { return store.validator; },\n                get validator_privacy_policy() { return store.validator_privacy_policy; },\n                verifiedCallbacks: this.verifiedCallbacks,\n                unverifiedCallbacks: this.unverifiedCallbacks,\n                finish: (receipt) => this.finish(receipt),\n            }, this.log);\n            new CdvPurchase.Internal.ReceiptsMonitor({\n                hasLocalReceipts: () => this.localReceipts.length > 0,\n                hasValidator: () => !!this.validator,\n                numValidationRequests: () => this._validator.numRequests,\n                numValidationResponses: () => this._validator.numResponses,\n                off: this.off.bind(this),\n                when: this.when.bind(this),\n                receiptsVerified: () => { store.receiptsVerifiedCallbacks.trigger(undefined, 'receipts_monitor_controller'); },\n                log: this.log,\n            }).launch();\n            this.expiryMonitor = new CdvPurchase.Internal.ExpiryMonitor({\n                // get localReceipts() { return store.localReceipts; },\n                get verifiedReceipts() { return store.verifiedReceipts; },\n                // onTransactionExpired(transaction) {\n                // store.approvedCallbacks.trigger(transaction);\n                // },\n                onVerifiedPurchaseExpired(verifiedPurchase, receipt) {\n                    store.verify(receipt.sourceReceipt);\n                },\n            });\n            this.expiryMonitor.launch();\n        }\n        /**\n         * Retrieve a platform adapter.\n         *\n         * The platform adapter has to have been initialized before.\n         *\n         * @see {@link initialize}\n         */\n        getAdapter(platform) {\n            return this.adapters.find(platform);\n        }\n        /**\n         * Get the application username as a string by either calling or returning {@link Store.applicationUsername}\n        */\n        getApplicationUsername() {\n            if (this.applicationUsername instanceof Function)\n                return this.applicationUsername();\n            return this.applicationUsername;\n        }\n        /**\n         * Register a product.\n         *\n         * @example\n         * store.register([{\n         *       id: 'subscription1',\n         *       type: ProductType.PAID_SUBSCRIPTION,\n         *       platform: Platform.APPLE_APPSTORE,\n         *   }, {\n         *       id: 'subscription1',\n         *       type: ProductType.PAID_SUBSCRIPTION,\n         *       platform: Platform.GOOGLE_PLAY,\n         *   }, {\n         *       id: 'consumable1',\n         *       type: ProductType.CONSUMABLE,\n         *       platform: Platform.BRAINTREE,\n         *   }]);\n         */\n        register(product) {\n            const errors = this.registeredProducts.add(product);\n            errors.forEach(error => {\n                CdvPurchase.store.errorCallbacks.trigger(error, 'register_error');\n                this.log.error(error);\n            });\n        }\n        /**\n         * Call to initialize the in-app purchase plugin.\n         *\n         * @param platforms - List of payment platforms to initialize, default to Store.defaultPlatform().\n         */\n        initialize(platforms = [this.defaultPlatform()]) {\n            return __awaiter(this, void 0, void 0, function* () {\n                if (this.initializedHasBeenCalled) {\n                    this.log.warn('store.initialized() has been called already.');\n                    return [];\n                }\n                this.log.info('initialize(' + JSON.stringify(platforms) + ') v' + CdvPurchase.PLUGIN_VERSION);\n                this.initializedHasBeenCalled = true;\n                this.lastUpdate = +new Date();\n                const store = this;\n                const ret = this.adapters.initialize(platforms, {\n                    error: this.triggerError.bind(this),\n                    get verbosity() { return store.verbosity; },\n                    getApplicationUsername() { return store.getApplicationUsername(); },\n                    get listener() { return store.listener; },\n                    get log() { return store.log; },\n                    get registeredProducts() { return store.registeredProducts; },\n                    apiDecorators: {\n                        canPurchase: this.canPurchase.bind(this),\n                        owned: this.owned.bind(this),\n                        finish: this.finish.bind(this),\n                        order: this.order.bind(this),\n                        verify: this.verify.bind(this),\n                    },\n                });\n                ret.then(() => {\n                    this._readyCallbacks.trigger('initialize_promise_resolved');\n                    this.listener.setSupportedPlatforms(this.adapters.list.filter(a => a.isSupported).map(a => a.id));\n                });\n                return ret;\n            });\n        }\n        /**\n         * @deprecated - use store.initialize(), store.update() or store.restorePurchases()\n         */\n        refresh() {\n            throw new Error(\"use store.initialize() or store.update()\");\n        }\n        /**\n         * Call to refresh the price of products and status of purchases.\n         */\n        update() {\n            var _a;\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info('update()');\n                if (!this._readyCallbacks.isReady) {\n                    this.log.warn('Do not call store.update() at startup! It is meant to reload the price of products (if needed) long after initialization.');\n                    return;\n                }\n                const now = +new Date();\n                if (this.lastUpdate > now - this.minTimeBetweenUpdates) {\n                    this.log.info('Skipping store.update() as the last call occurred less than store.minTimeBetweenUpdates millis ago.');\n                    return;\n                }\n                this.lastUpdate = now;\n                // Load products metadata\n                for (const registration of this.registeredProducts.byPlatform()) {\n                    const products = yield ((_a = this.adapters.findReady(registration.platform)) === null || _a === void 0 ? void 0 : _a.loadProducts(registration.products));\n                    products === null || products === void 0 ? void 0 : products.forEach(p => {\n                        if (p instanceof CdvPurchase.Product)\n                            this.updatedCallbacks.trigger(p, 'update_has_loaded_products');\n                    });\n                }\n            });\n        }\n        /**\n         * Register a callback to be called when the plugin is ready.\n         *\n         * This happens when all the platforms are initialized and their products loaded.\n         */\n        ready(cb) { this._readyCallbacks.add(cb); }\n        /** true if the plugin is initialized and ready */\n        get isReady() { return this._readyCallbacks.isReady; }\n        /**\n         * Register event callbacks.\n         *\n         * Events overview:\n         * - `productUpdated`: Called when product metadata is loaded from the store\n         * - `receiptUpdated`: Called when local receipt information changes (ownership status change, for example)\n         * - `verified`: Called after successful receipt validation (requires a receipt validator)\n         *\n         * @example\n         * // Monitor ownership with receipt validation\n         * store.when()\n         *      .approved(transaction => transaction.verify())\n         *      .verified(receipt => {\n         *          if (store.owned(\"my-product\")) {\n         *              // Product is owned and verified\n         *          }\n         *      });\n         *\n         * @example\n         * // Monitor ownership without receipt validation\n         * store.when().receiptUpdated(receipt => {\n         *   if (store.owned(\"my-product\")) {\n         *     // Product is owned according to local data\n         *   }\n         * });\n         */\n        when() {\n            const ret = {\n                productUpdated: (cb, callbackName) => (this.updatedCallbacks.push(cb, callbackName), ret),\n                receiptUpdated: (cb, callbackName) => (this.updatedReceiptsCallbacks.push(cb, callbackName), ret),\n                updated: (cb, callbackName) => (this.updatedCallbacks.push(cb, callbackName), this.updatedReceiptsCallbacks.push(cb, callbackName), ret),\n                // owned: (cb: Callback<Product>) => (this.ownedCallbacks.push(cb), ret),\n                approved: (cb, callbackName) => (this.approvedCallbacks.push(cb, callbackName), ret),\n                initiated: (cb, callbackName) => (this.initiatedCallbacks.push(cb, callbackName), ret),\n                pending: (cb, callbackName) => (this.pendingCallbacks.push(cb, callbackName), ret),\n                finished: (cb, callbackName) => (this.finishedCallbacks.push(cb, callbackName), ret),\n                verified: (cb, callbackName) => (this.verifiedCallbacks.push(cb, callbackName), ret),\n                unverified: (cb, callbackName) => (this.unverifiedCallbacks.push(cb, callbackName), ret),\n                receiptsReady: (cb, callbackName) => (this.receiptsReadyCallbacks.push(cb, callbackName), ret),\n                receiptsVerified: (cb, callbackName) => (this.receiptsVerifiedCallbacks.push(cb, callbackName), ret),\n            };\n            return ret;\n        }\n        /**\n         * Remove a callback from any listener it might have been added to.\n         */\n        off(callback) {\n            this.updatedCallbacks.remove(callback);\n            this.updatedReceiptsCallbacks.remove(callback);\n            this.approvedCallbacks.remove(callback);\n            this.finishedCallbacks.remove(callback);\n            this.pendingCallbacks.remove(callback);\n            this.verifiedCallbacks.remove(callback);\n            this.unverifiedCallbacks.remove(callback);\n            this.receiptsReadyCallbacks.remove(callback);\n            this.receiptsVerifiedCallbacks.remove(callback);\n            this.errorCallbacks.remove(callback);\n            this._readyCallbacks.remove(callback);\n        }\n        /**\n         * Setup a function to be notified of changes to a transaction state.\n         *\n         * @param transaction The transaction to monitor.\n         * @param onChange Function to be called when the transaction status changes.\n         * @return A monitor which can be stopped with `monitor.stop()`\n         *\n         * @example\n         * const monitor = store.monitor(transaction, state => {\n         *   console.log('new state: ' + state);\n         *   if (state === TransactionState.FINISHED)\n         *     monitor.stop();\n         * });\n         */\n        monitor(transaction, onChange, callbackName) {\n            return this.transactionStateMonitors.start(transaction, CdvPurchase.Utils.safeCallback(this.log, 'monitor()', onChange, callbackName, 'transactionStateMonitors_stateChanged'));\n        }\n        /**\n         * List of all active products.\n         *\n         * Products are active if their details have been successfully loaded from the store.\n         */\n        get products() {\n            // concatenate products all all active platforms\n            return [].concat(...this.adapters.list.map(a => a.products));\n        }\n        /**\n         * Find a product from its id and platform\n         *\n         * @param productId Product identifier on the platform.\n         * @param platform The product the product exists in. Can be omitted if you're only using a single payment platform.\n         */\n        get(productId, platform) {\n            var _a;\n            return (_a = this.adapters.findReady(platform)) === null || _a === void 0 ? void 0 : _a.products.find(p => p.id === productId);\n        }\n        /**\n         * List of all receipts present on the device.\n         */\n        get localReceipts() {\n            // concatenate products all all active platforms\n            return [].concat(...this.adapters.list.map(a => a.receipts));\n        }\n        /** List of all transaction from the local receipts. */\n        get localTransactions() {\n            const ret = [];\n            for (const receipt of this.localReceipts) {\n                ret.push(...receipt.transactions);\n            }\n            return ret;\n        }\n        /**\n         * List of receipts verified with the receipt validation service.\n         *\n         * Those receipt contains more information and are generally more up-to-date than the local ones.\n         */\n        get verifiedReceipts() {\n            return this._validator.verifiedReceipts;\n        }\n        /**\n         * List of all purchases from the verified receipts.\n         */\n        get verifiedPurchases() {\n            return CdvPurchase.Internal.VerifiedReceipts.getVerifiedPurchases(this.verifiedReceipts);\n        }\n        /**\n         * Find the last verified purchase for a given product, from those verified by the receipt validator.\n         */\n        findInVerifiedReceipts(product) {\n            return CdvPurchase.Internal.VerifiedReceipts.find(this.verifiedReceipts, product);\n        }\n        /**\n         * Find the latest transaction for a given product, from those reported by the device.\n         */\n        findInLocalReceipts(product) {\n            return CdvPurchase.Internal.LocalReceipts.find(this.localReceipts, product);\n        }\n        /** Return true if a product or offer can be purchased */\n        canPurchase(offer) {\n            const product = (offer instanceof CdvPurchase.Offer) ? this.get(offer.productId, offer.platform) : offer;\n            const adapter = this.adapters.findReady(offer.platform);\n            if (!(adapter === null || adapter === void 0 ? void 0 : adapter.checkSupport('order')))\n                return false;\n            return CdvPurchase.Internal.LocalReceipts.canPurchase(this.localReceipts, product);\n        }\n        /**\n         * Return true if a product is owned\n         *\n         * Important: The value will be false when the app starts and will only become\n         * true after purchase receipts have been loaded and validated. Without receipt validation,\n         * it might remain false depending on the platform, make sure to store the ownership status\n         * of non-consumable products in some way.\n         *\n         * @param product - The product object or identifier of the product.\n         */\n        owned(product) {\n            return CdvPurchase.Internal.owned({\n                product: typeof product === 'string' ? { id: product } : product,\n                verifiedReceipts: this.validator ? this.verifiedReceipts : undefined,\n                localReceipts: this.localReceipts,\n            });\n        }\n        /**\n         * Place an order for a given offer.\n         */\n        order(offer, additionalData) {\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info(`order(${offer.productId})`);\n                const adapter = this.adapters.findReady(offer.platform);\n                if (!adapter)\n                    return CdvPurchase.storeError(CdvPurchase.ErrorCode.PAYMENT_NOT_ALLOWED, 'Adapter not found or not ready (' + offer.platform + ')', offer.platform, null);\n                const ret = yield adapter.order(offer, additionalData || {});\n                if (ret && 'isError' in ret)\n                    CdvPurchase.store.triggerError(ret);\n                return ret;\n            });\n        }\n        /**\n         * Request a payment.\n         *\n         * A payment is a custom amount to charge the user. Make sure the selected payment platform\n         * supports Payment Requests.\n         *\n         * @param paymentRequest Parameters of the payment request\n         * @param additionalData Additional parameters\n         */\n        requestPayment(paymentRequest, additionalData) {\n            var _a, _b, _c, _d, _e;\n            const adapter = this.adapters.findReady(paymentRequest.platform);\n            if (!adapter)\n                return CdvPurchase.PaymentRequestPromise.failed(CdvPurchase.ErrorCode.PAYMENT_NOT_ALLOWED, 'Adapter not found or not ready (' + paymentRequest.platform + ')', paymentRequest.platform, null);\n            // fill-in missing total amount as the sum of all items.\n            if (!paymentRequest.amountMicros) {\n                paymentRequest.amountMicros = 0;\n                for (const item of paymentRequest.items) {\n                    paymentRequest.amountMicros += (_b = (_a = item === null || item === void 0 ? void 0 : item.pricing) === null || _a === void 0 ? void 0 : _a.priceMicros) !== null && _b !== void 0 ? _b : 0;\n                }\n            }\n            // fill-in the missing if set in the items.\n            if (!paymentRequest.currency) {\n                for (const item of paymentRequest.items) {\n                    if ((_c = item === null || item === void 0 ? void 0 : item.pricing) === null || _c === void 0 ? void 0 : _c.currency) {\n                        paymentRequest.currency = item.pricing.currency;\n                    }\n                }\n            }\n            else {\n                for (const item of paymentRequest.items) {\n                    if ((_d = item === null || item === void 0 ? void 0 : item.pricing) === null || _d === void 0 ? void 0 : _d.currency) {\n                        if (paymentRequest.currency !== item.pricing.currency) {\n                            return CdvPurchase.PaymentRequestPromise.failed(CdvPurchase.ErrorCode.PAYMENT_INVALID, 'Currencies do not match', paymentRequest.platform, item.id);\n                        }\n                    }\n                    else if (item === null || item === void 0 ? void 0 : item.pricing) {\n                        item.pricing.currency = paymentRequest.currency;\n                    }\n                }\n            }\n            // fill-in item amount when there's just 1 item.\n            if (paymentRequest.items.length === 1) {\n                const item = paymentRequest.items[0];\n                if (item && !item.pricing) {\n                    item.pricing = {\n                        priceMicros: (_e = paymentRequest.amountMicros) !== null && _e !== void 0 ? _e : 0,\n                        currency: paymentRequest.currency,\n                    };\n                }\n            }\n            const promise = new CdvPurchase.PaymentRequestPromise();\n            adapter.requestPayment(paymentRequest, additionalData).then(result => {\n                promise.trigger(result);\n                if (result instanceof CdvPurchase.Transaction) {\n                    const onStateChange = (state) => {\n                        promise.trigger(result);\n                        if (result.state === CdvPurchase.TransactionState.FINISHED)\n                            monitor.stop();\n                    };\n                    const monitor = this.monitor(result, onStateChange, 'requestPayment_onStateChange');\n                }\n            });\n            return promise;\n        }\n        /**\n         * Returns true if a platform supports the requested functionality.\n         *\n         * @example\n         * store.checkSupport(Platform.APPLE_APPSTORE, 'requestPayment');\n         * // => false\n         */\n        checkSupport(platform, functionality) {\n            const adapter = this.adapters.find(platform);\n            if (!adapter)\n                return false; // the selected adapter hasn't been initialized\n            return adapter.checkSupport(functionality);\n        }\n        /**\n         * Verify a receipt or transacting with the receipt validation service.\n         *\n         * This will be called from the Receipt or Transaction objects using the API decorators.\n         */\n        verify(receiptOrTransaction) {\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info(`verify(${receiptOrTransaction.className})`);\n                this._validator.add(receiptOrTransaction);\n                // Run validation after 200ms, so if the same receipt is to be validated multiple times it will just create one call.\n                setTimeout(() => this._validator.run(), 200);\n            });\n        }\n        /**\n         * Finalize a transaction.\n         *\n         * This will be called from the Receipt, Transaction or VerifiedReceipt objects using the API decorators.\n         */\n        finish(receipt) {\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info(`finish(${receipt.className})`);\n                const transactions = receipt instanceof CdvPurchase.VerifiedReceipt\n                    ? receipt.sourceReceipt.transactions\n                    : receipt instanceof CdvPurchase.Receipt\n                        ? receipt.transactions\n                        : [receipt];\n                transactions.forEach(transaction => {\n                    var _a;\n                    const adapter = (_a = this.adapters.findReady(transaction.platform)) === null || _a === void 0 ? void 0 : _a.finish(transaction);\n                });\n            });\n        }\n        /**\n         * Replay the users transactions.\n         *\n         * This method exists to cover an Apple AppStore requirement.\n         */\n        restorePurchases() {\n            return __awaiter(this, void 0, void 0, function* () {\n                let error;\n                for (const adapter of this.adapters.list) {\n                    if (adapter.ready) {\n                        error = error !== null && error !== void 0 ? error : yield adapter.restorePurchases();\n                    }\n                }\n                return error;\n            });\n        }\n        /**\n         * Open the subscription management interface for the selected platform.\n         *\n         * If platform is not specified, the first available platform will be used.\n         *\n         * @example\n         * const activeSubscription: Purchase = // ...\n         * store.manageSubscriptions(activeSubscription.platform);\n         */\n        manageSubscriptions(platform) {\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info('manageSubscriptions()');\n                const adapter = this.adapters.findReady(platform);\n                if (!adapter)\n                    return CdvPurchase.storeError(CdvPurchase.ErrorCode.SETUP, \"Found no adapter ready to handle 'manageSubscription'\", platform !== null && platform !== void 0 ? platform : null, null);\n                return adapter.manageSubscriptions();\n            });\n        }\n        /**\n         * Opens the billing methods page on AppStore, Play, Microsoft, ...\n         *\n         * From this page, the user can update their payment methods.\n         *\n         * If platform is not specified, the first available platform will be used.\n         *\n         * @example\n         * if (purchase.isBillingRetryPeriod)\n         *     store.manageBilling(purchase.platform);\n         */\n        manageBilling(platform) {\n            return __awaiter(this, void 0, void 0, function* () {\n                this.log.info('manageBilling()');\n                const adapter = this.adapters.findReady(platform);\n                if (!adapter)\n                    return CdvPurchase.storeError(CdvPurchase.ErrorCode.SETUP, \"Found no adapter ready to handle 'manageBilling'\", platform !== null && platform !== void 0 ? platform : null, null);\n                return adapter.manageBilling();\n            });\n        }\n        /**\n         * The default payment platform to use depending on the OS.\n         *\n         * - on iOS: `APPLE_APPSTORE`\n         * - on Android: `GOOGLE_PLAY`\n         */\n        defaultPlatform() {\n            switch (CdvPurchase.Utils.platformId()) {\n                case 'android': return CdvPurchase.Platform.GOOGLE_PLAY;\n                case 'ios': return CdvPurchase.Platform.APPLE_APPSTORE;\n                default: return CdvPurchase.Platform.TEST;\n            }\n        }\n        /**\n         * Register an error handler.\n         *\n         * @param error An error callback that takes the error as an argument\n         *\n         * @example\n         * store.error(function(error) {\n         *   console.error('CdvPurchase ERROR: ' + error.message);\n         * });\n         */\n        error(error) {\n            this.errorCallbacks.push(error);\n        }\n        /**\n         * Trigger an error event.\n         *\n         * @internal\n         */\n        triggerError(error) {\n            this.errorCallbacks.trigger(error, 'triggerError');\n        }\n    }\n    CdvPurchase.Store = Store;\n})(CdvPurchase || (CdvPurchase = {}));\n// Create the CdvPurchase.store object at startup.\nif (window.cordova) {\n    setTimeout(initCDVPurchase, 0); // somehow with Cordova this needs to be delayed.\n}\nelse {\n    initCDVPurchase();\n}\n/** @private */\nfunction initCDVPurchase() {\n    var _a;\n    console.log('Create CdvPurchase...');\n    const oldStore = (_a = window.CdvPurchase) === null || _a === void 0 ? void 0 : _a.store;\n    window.CdvPurchase = CdvPurchase;\n    if (oldStore) {\n        window.CdvPurchase.store = oldStore;\n    }\n    else {\n        window.CdvPurchase.store = new CdvPurchase.Store();\n    }\n    // Let's maximize backward compatibility\n    Object.assign(window.CdvPurchase.store, CdvPurchase.LogLevel, CdvPurchase.ProductType, CdvPurchase.ErrorCode, CdvPurchase.Platform);\n}\n// Ensure utility are included when compiling typescript.\n/// <reference path=\"utils/format-billing-cycle.ts\" />\n/// <reference path=\"store.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** Types of In-App Products */\n    let ProductType;\n    (function (ProductType) {\n        /** Type: An consumable product, that can be purchased multiple time */\n        ProductType[\"CONSUMABLE\"] = \"consumable\";\n        /** Type: A non-consumable product, that can purchased only once and the user keeps forever */\n        ProductType[\"NON_CONSUMABLE\"] = \"non consumable\";\n        /** @deprecated use PAID_SUBSCRIPTION */\n        ProductType[\"FREE_SUBSCRIPTION\"] = \"free subscription\";\n        /** Type: An auto-renewable subscription */\n        ProductType[\"PAID_SUBSCRIPTION\"] = \"paid subscription\";\n        /** Type: An non-renewing subscription */\n        ProductType[\"NON_RENEWING_SUBSCRIPTION\"] = \"non renewing subscription\";\n        /** Type: The application bundle */\n        ProductType[\"APPLICATION\"] = \"application\";\n    })(ProductType = CdvPurchase.ProductType || (CdvPurchase.ProductType = {}));\n    /**\n     * Type of recurring payment\n     *\n     * - FINITE_RECURRING: Payment recurs for a fixed number of billing period set in `paymentPhase.cycles`.\n     * - INFINITE_RECURRING: Payment recurs for infinite billing periods unless cancelled.\n     * - NON_RECURRING: A one time charge that does not repeat.\n     */\n    let RecurrenceMode;\n    (function (RecurrenceMode) {\n        RecurrenceMode[\"NON_RECURRING\"] = \"NON_RECURRING\";\n        RecurrenceMode[\"FINITE_RECURRING\"] = \"FINITE_RECURRING\";\n        RecurrenceMode[\"INFINITE_RECURRING\"] = \"INFINITE_RECURRING\";\n    })(RecurrenceMode = CdvPurchase.RecurrenceMode || (CdvPurchase.RecurrenceMode = {}));\n    /** Mode of payment */\n    let PaymentMode;\n    (function (PaymentMode) {\n        /** Used for subscriptions, pay at the beginning of each billing period */\n        PaymentMode[\"PAY_AS_YOU_GO\"] = \"PayAsYouGo\";\n        /** Pay the whole amount up front */\n        PaymentMode[\"UP_FRONT\"] = \"UpFront\";\n        /** Nothing to be paid */\n        PaymentMode[\"FREE_TRIAL\"] = \"FreeTrial\";\n    })(PaymentMode = CdvPurchase.PaymentMode || (CdvPurchase.PaymentMode = {}));\n    /**\n     * Purchase platforms supported by the plugin\n     */\n    let Platform;\n    (function (Platform) {\n        /** Apple AppStore */\n        Platform[\"APPLE_APPSTORE\"] = \"ios-appstore\";\n        /** Google Play */\n        Platform[\"GOOGLE_PLAY\"] = \"android-playstore\";\n        /** Windows Store */\n        Platform[\"WINDOWS_STORE\"] = \"windows-store-transaction\";\n        /** Braintree */\n        Platform[\"BRAINTREE\"] = \"braintree\";\n        // /** Stripe */\n        // STRIPE = 'stripe',\n        /** Test platform */\n        Platform[\"TEST\"] = \"test\";\n    })(Platform = CdvPurchase.Platform || (CdvPurchase.Platform = {}));\n    /**\n     * Possible states of a transaction.\n     *\n     * ```\n     * INITIATED → PENDING (optional) → APPROVED → FINISHED\n     * ```\n     */\n    let TransactionState;\n    (function (TransactionState) {\n        // REQUESTED = 'requested',\n        TransactionState[\"INITIATED\"] = \"initiated\";\n        TransactionState[\"PENDING\"] = \"pending\";\n        TransactionState[\"APPROVED\"] = \"approved\";\n        TransactionState[\"CANCELLED\"] = \"cancelled\";\n        TransactionState[\"FINISHED\"] = \"finished\";\n        // OWNED = 'owned',\n        // EXPIRED = 'expired',\n        TransactionState[\"UNKNOWN_STATE\"] = \"\";\n    })(TransactionState = CdvPurchase.TransactionState || (CdvPurchase.TransactionState = {}));\n    /** Whether or not the user intends to let the subscription auto-renew. */\n    let RenewalIntent;\n    (function (RenewalIntent) {\n        /** The user intends to let the subscription expire without renewing. */\n        RenewalIntent[\"LAPSE\"] = \"Lapse\";\n        /** The user intends to renew the subscription. */\n        RenewalIntent[\"RENEW\"] = \"Renew\";\n    })(RenewalIntent = CdvPurchase.RenewalIntent || (CdvPurchase.RenewalIntent = {}));\n    /** Whether or not the user was notified or agreed to a price change */\n    let PriceConsentStatus;\n    (function (PriceConsentStatus) {\n        PriceConsentStatus[\"NOTIFIED\"] = \"Notified\";\n        PriceConsentStatus[\"AGREED\"] = \"Agreed\";\n    })(PriceConsentStatus = CdvPurchase.PriceConsentStatus || (CdvPurchase.PriceConsentStatus = {}));\n    /** Reason why a subscription has been canceled */\n    let CancelationReason;\n    (function (CancelationReason) {\n        /** Not canceled */\n        CancelationReason[\"NOT_CANCELED\"] = \"\";\n        /** Subscription canceled by the developer. */\n        CancelationReason[\"DEVELOPER\"] = \"Developer\";\n        /** Subscription canceled by the system for an unspecified reason. */\n        CancelationReason[\"SYSTEM\"] = \"System\";\n        /** Subscription upgraded or downgraded to a new subscription. */\n        CancelationReason[\"SYSTEM_REPLACED\"] = \"System.Replaced\";\n        /** Product not available for purchase at the time of renewal. */\n        CancelationReason[\"SYSTEM_PRODUCT_UNAVAILABLE\"] = \"System.ProductUnavailable\";\n        /** Billing error; for example customer’s payment information is no longer valid. */\n        CancelationReason[\"SYSTEM_BILLING_ERROR\"] = \"System.BillingError\";\n        /** Transaction is gone; It has been deleted. */\n        CancelationReason[\"SYSTEM_DELETED\"] = \"System.Deleted\";\n        /** Subscription canceled by the user for an unspecified reason. */\n        CancelationReason[\"CUSTOMER\"] = \"Customer\";\n        /** Customer canceled their transaction due to an actual or perceived issue within your app. */\n        CancelationReason[\"CUSTOMER_TECHNICAL_ISSUES\"] = \"Customer.TechnicalIssues\";\n        /** Customer did not agree to a recent price increase. See also priceConsentStatus. */\n        CancelationReason[\"CUSTOMER_PRICE_INCREASE\"] = \"Customer.PriceIncrease\";\n        /** Customer canceled for cost-related reasons. */\n        CancelationReason[\"CUSTOMER_COST\"] = \"Customer.Cost\";\n        /** Customer claimed to have found a better app. */\n        CancelationReason[\"CUSTOMER_FOUND_BETTER_APP\"] = \"Customer.FoundBetterApp\";\n        /** Customer did not feel he is using this service enough. */\n        CancelationReason[\"CUSTOMER_NOT_USEFUL_ENOUGH\"] = \"Customer.NotUsefulEnough\";\n        /** Subscription canceled for another reason; for example, if the customer made the purchase accidentally. */\n        CancelationReason[\"CUSTOMER_OTHER_REASON\"] = \"Customer.OtherReason\";\n        /** Subscription canceled for unknown reasons. */\n        CancelationReason[\"UNKNOWN\"] = \"Unknown\";\n    })(CancelationReason = CdvPurchase.CancelationReason || (CdvPurchase.CancelationReason = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"utils/non-enumerable.ts\" />\n/// <reference path=\"product.ts\" />\n/// <reference path=\"types.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * One of the available offers to purchase a given product\n     */\n    class Offer {\n        /** @internal */\n        constructor(options, decorator) {\n            /** className, used to make sure we're passing an actual instance of the \"Offer\" class. */\n            this.className = 'Offer';\n            this.id = options.id;\n            this.pricingPhases = options.pricingPhases;\n            // Object.defineProperty(this, 'product', { enumerable: false, get: () => options.product });\n            Object.defineProperty(this, 'productId', { enumerable: true, get: () => options.product.id });\n            Object.defineProperty(this, 'productType', { enumerable: true, get: () => options.product.type });\n            Object.defineProperty(this, 'productGroup', { enumerable: true, get: () => options.product.group });\n            Object.defineProperty(this, 'platform', { enumerable: true, get: () => options.product.platform });\n            Object.defineProperty(this, 'order', { enumerable: false, get: () => (additionalData) => decorator.order(this, additionalData) });\n            Object.defineProperty(this, 'canPurchase', { enumerable: false, get: () => decorator.canPurchase(this) });\n        }\n        /** Identifier of the product related to this offer */\n        get productId() { return ''; }\n        /** Type of the product related to this offer */\n        get productType() { return CdvPurchase.ProductType.APPLICATION; }\n        /** Group the product related to this offer is member of */\n        get productGroup() { return undefined; }\n        /** Platform this offer is available from */\n        get platform() { return CdvPurchase.Platform.TEST; }\n        /**\n         * Initiate a purchase of this offer.\n         *\n         * @example\n         * store.get(\"my-product\").getOffer().order();\n         */\n        order(additionalData) {\n            return __awaiter(this, void 0, void 0, function* () {\n                // Pseudo implementation to make typescript happy.\n                // see Object.defineProperty in the constructor for the actual implementation.\n                return;\n            });\n        }\n        /**\n         * true if the offer can be purchased.\n         */\n        get canPurchase() {\n            // Pseudo implementation to make typescript happy.\n            // see Object.defineProperty in the constructor for the actual implementation.\n            return false;\n        }\n    }\n    CdvPurchase.Offer = Offer;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    class PaymentRequestPromise {\n        constructor() {\n            this.failedCallbacks = new CdvPurchase.Internal.PromiseLike();\n            this.initiatedCallbacks = new CdvPurchase.Internal.PromiseLike();\n            this.approvedCallbacks = new CdvPurchase.Internal.PromiseLike();\n            this.finishedCallbacks = new CdvPurchase.Internal.PromiseLike();\n            this.cancelledCallback = new CdvPurchase.Internal.PromiseLike();\n        }\n        failed(callback) {\n            this.failedCallbacks.push(callback);\n            return this;\n        }\n        initiated(callback) {\n            this.initiatedCallbacks.push(callback);\n            return this;\n        }\n        approved(callback) {\n            this.approvedCallbacks.push(callback);\n            return this;\n        }\n        finished(callback) {\n            this.finishedCallbacks.push(callback);\n            return this;\n        }\n        cancelled(callback) {\n            this.cancelledCallback.push(callback);\n            return this;\n        }\n        /** @internal */\n        trigger(argument) {\n            if (!argument) {\n                this.cancelledCallback.resolve();\n            }\n            else if ('isError' in argument) {\n                this.failedCallbacks.resolve(argument);\n            }\n            else {\n                switch (argument.state) {\n                    case CdvPurchase.TransactionState.INITIATED:\n                        this.initiatedCallbacks.resolve(argument);\n                        break;\n                    case CdvPurchase.TransactionState.APPROVED:\n                        this.approvedCallbacks.resolve(argument);\n                        break;\n                    case CdvPurchase.TransactionState.FINISHED:\n                        this.finishedCallbacks.resolve(argument);\n                        break;\n                }\n            }\n            return this;\n        }\n        /**\n         * Return a failed promise.\n         *\n         * @internal\n         */\n        static failed(code, message, platform, productId) {\n            return new PaymentRequestPromise().trigger(CdvPurchase.storeError(code, message, platform, productId));\n        }\n        /**\n         * Return a failed promise.\n         *\n         * @internal\n         */\n        static cancelled() {\n            return new PaymentRequestPromise().trigger();\n        }\n        /**\n         * Return an initiated transaction.\n         *\n         * @internal\n         */\n        static initiated(transaction) {\n            return new PaymentRequestPromise().trigger(transaction);\n        }\n    }\n    CdvPurchase.PaymentRequestPromise = PaymentRequestPromise;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    class Receipt {\n        /** @internal */\n        constructor(platform, decorator) {\n            /** @internal */\n            this.className = 'Receipt';\n            /** List of transactions contained in the receipt, ordered by date ascending. */\n            this.transactions = [];\n            this.platform = platform;\n            Object.defineProperty(this, 'verify', { 'enumerable': false, get() { return () => decorator.verify(this); } });\n            Object.defineProperty(this, 'finish', { 'enumerable': false, get() { return () => decorator.finish(this); } });\n        }\n        /** Verify a receipt */\n        verify() {\n            return __awaiter(this, void 0, void 0, function* () { });\n        }\n        /** Finish all transactions in a receipt */\n        finish() {\n            return __awaiter(this, void 0, void 0, function* () { });\n        }\n        /** Return true if the receipt contains the given transaction */\n        hasTransaction(value) {\n            return !!this.transactions.find(t => t === value);\n        }\n        /** Return the last transaction in this receipt */\n        lastTransaction() {\n            return this.transactions[this.transactions.length - 1];\n        }\n    }\n    CdvPurchase.Receipt = Receipt;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Transaction as reported by the device\n     *\n     * @see {@link Receipt}\n     * @see {@link store.localTransactions}\n     */\n    class Transaction {\n        /** @internal */\n        constructor(platform, parentReceipt, decorator) {\n            /** @internal */\n            this.className = 'Transaction';\n            /** Transaction identifier. */\n            this.transactionId = '';\n            /** State this transaction is in */\n            this.state = CdvPurchase.TransactionState.UNKNOWN_STATE;\n            /** Purchased products */\n            this.products = [];\n            this.platform = platform;\n            Object.defineProperty(this, 'finish', { 'enumerable': false, get() { return () => decorator.finish(this); } });\n            Object.defineProperty(this, 'verify', { 'enumerable': false, get() { return () => decorator.verify(this); } });\n            Object.defineProperty(this, 'parentReceipt', { 'enumerable': false, get() { return parentReceipt; } });\n        }\n        /**\n         * Finish a transaction.\n         *\n         * When the application has delivered the product, it should finalizes the order.\n         * Only after that, money will be transferred to your account.\n         * This method ensures that no customers is charged for a product that couldn't be delivered.\n         *\n         * @example\n         * store.when()\n         *   .approved(transaction => transaction.verify())\n         *   .verified(receipt => receipt.finish())\n         */\n        finish() {\n            return __awaiter(this, void 0, void 0, function* () { });\n        } // actual implementation in the constructor\n        /**\n         * Verify a transaction.\n         *\n         * This will trigger a call to the receipt validation service for the attached receipt.\n         * Once the receipt has been verified, you can finish the transaction.\n         *\n         * @example\n         * store.when()\n         *   .approved(transaction => transaction.verify())\n         *   .verified(receipt => receipt.finish())\n         */\n        verify() {\n            return __awaiter(this, void 0, void 0, function* () { });\n        } // actual implementation in the constructor\n        /**\n         * Return the receipt this transaction is part of.\n         */\n        get parentReceipt() { return {}; } // actual implementation in the constructor\n    }\n    CdvPurchase.Transaction = Transaction;\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /** Analyze the list of local receipts. */\n        class LocalReceipts {\n            /**\n             * Find the latest transaction for a given product, from those reported by the device.\n             */\n            static find(localReceipts, product) {\n                var _a, _b;\n                if (!product)\n                    return undefined;\n                let found;\n                for (const receipt of localReceipts) {\n                    if (product.platform && receipt.platform !== product.platform)\n                        continue;\n                    for (const transaction of receipt.transactions) {\n                        for (const trProducts of transaction.products) {\n                            if (trProducts.id === product.id) {\n                                // No matching transaction has been found or the tested one is newer than the already found one?\n                                // Then we chose the tested one.\n                                if (!found || ((_a = transaction.purchaseDate) !== null && _a !== void 0 ? _a : 0) < ((_b = found.purchaseDate) !== null && _b !== void 0 ? _b : 1))\n                                    found = transaction;\n                            }\n                        }\n                    }\n                }\n                return found;\n            }\n            /** Return true if a product is owned */\n            static isOwned(localReceipts, product) {\n                if (!product)\n                    return false;\n                const transaction = LocalReceipts.find(localReceipts, product);\n                if (!transaction)\n                    return false;\n                if (transaction.isConsumed)\n                    return false;\n                if (transaction.isPending)\n                    return false;\n                if (transaction.expirationDate)\n                    return transaction.expirationDate.getTime() > +new Date();\n                return true;\n            }\n            static canPurchase(localReceipts, product) {\n                if (!product)\n                    return false;\n                const transaction = LocalReceipts.find(localReceipts, product);\n                if (!transaction)\n                    return true;\n                if (transaction.isConsumed)\n                    return true;\n                if (transaction.expirationDate)\n                    return transaction.expirationDate.getTime() <= +new Date();\n                return true;\n            }\n        }\n        Internal.LocalReceipts = LocalReceipts;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /**\n         * Return true if a product is owned.\n         *\n         * Will use the list of verified receipts if provided.\n         * Will only use the list of local receipts if verifiedReceipt is undefined.\n         */\n        function owned(options) {\n            if (options.verifiedReceipts !== undefined) {\n                return Internal.VerifiedReceipts.isOwned(options.verifiedReceipts, options.product);\n            }\n            else if (options.localReceipts !== undefined) {\n                return Internal.LocalReceipts.isOwned(options.localReceipts, options.product);\n            }\n            else {\n                return false;\n            }\n        }\n        Internal.owned = owned;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        class PromiseLike {\n            constructor() {\n                this.resolved = false;\n                /** List of registered callbacks */\n                this.callbacks = [];\n            }\n            /** Add a callback to the list */\n            push(callback) {\n                if (this.resolved)\n                    setTimeout(callback, 0, this.resolvedArgument);\n                else\n                    this.callbacks.push(callback);\n            }\n            /** Call all registered callbacks with the given value */\n            resolve(value) {\n                if (this.resolved)\n                    return; // do not resolve twice\n                this.resolved = true;\n                this.resolvedArgument = value;\n                this.callbacks.forEach(cb => setTimeout(cb, 0, value));\n                this.callbacks = [];\n            }\n        }\n        Internal.PromiseLike = PromiseLike;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /**\n         * Retry failed requests\n         *\n         * When setup and/or load failed, the plugin will retry over and over till it can connect\n         * to the store.\n         *\n         * However, to be nice with the battery, it'll double the retry timeout each time.\n         *\n         * Special case, when the device goes online, it'll trigger all retry callback in the queue.\n         */\n        class Retry {\n            constructor(minTimeout = 5000, maxTimeout = 120000) {\n                this.maxTimeout = 120000;\n                this.minTimeout = 5000;\n                this.retryTimeout = 5000;\n                this.retries = [];\n                this.minTimeout = minTimeout;\n                this.maxTimeout = maxTimeout;\n                this.retryTimeout = minTimeout;\n                // From https://github.com/apache/cordova-plugin-network-information\n                // This event fires when an application goes online, and the device becomes connected to the Internet.\n                document.addEventListener(\"online\", () => {\n                    const a = this.retries;\n                    this.retries = [];\n                    this.retryTimeout = this.minTimeout;\n                    for (var i = 0; i < a.length; ++i) {\n                        clearTimeout(a[i].tid);\n                        a[i].fn.call(this);\n                    }\n                }, false);\n            }\n            retry(fn) {\n                var tid = setTimeout(() => {\n                    this.retries = this.retries.filter(function (o) {\n                        return tid !== o.tid;\n                    });\n                    fn();\n                }, this.retryTimeout);\n                this.retries.push({ tid: tid, fn: fn });\n                this.retryTimeout *= 2;\n                // Max out the waiting time to 2 minutes.\n                if (this.retryTimeout > this.maxTimeout)\n                    this.retryTimeout = this.maxTimeout;\n            }\n        }\n        Internal.Retry = Retry;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Internal;\n    (function (Internal) {\n        /** Analyze the list of local receipts. */\n        class VerifiedReceipts {\n            /**\n             * Find the last verified purchase for a given product, from those verified by the receipt validator.\n             */\n            static find(verifiedReceipts, product) {\n                var _a, _b;\n                if (!product)\n                    return undefined;\n                let found;\n                for (const receipt of verifiedReceipts) {\n                    if (product.platform && receipt.platform !== product.platform)\n                        continue;\n                    for (const purchase of receipt.collection) {\n                        if (purchase.id === product.id) {\n                            if (((_a = found === null || found === void 0 ? void 0 : found.purchaseDate) !== null && _a !== void 0 ? _a : 0) < ((_b = purchase.purchaseDate) !== null && _b !== void 0 ? _b : 1))\n                                found = purchase;\n                        }\n                    }\n                }\n                return found;\n            }\n            /** Return true if a product is owned, based on the content of the list of verified receipts  */\n            static isOwned(verifiedReceipts, product) {\n                if (!product)\n                    return false;\n                const purchase = VerifiedReceipts.find(verifiedReceipts, product);\n                if (!purchase)\n                    return false;\n                if (purchase === null || purchase === void 0 ? void 0 : purchase.isExpired)\n                    return false;\n                if (purchase === null || purchase === void 0 ? void 0 : purchase.expiryDate) {\n                    return (purchase.expiryDate > +new Date());\n                }\n                return true;\n            }\n            static getVerifiedPurchases(verifiedReceipts) {\n                var _a, _b, _c, _d;\n                const indexed = {};\n                for (const receipt of verifiedReceipts) {\n                    for (const purchase of receipt.collection) {\n                        const key = receipt.platform + ':' + purchase.id;\n                        const existing = indexed[key];\n                        if (!existing || (existing && ((_b = (_a = existing.lastRenewalDate) !== null && _a !== void 0 ? _a : existing.purchaseDate) !== null && _b !== void 0 ? _b : 0) < ((_d = (_c = purchase.lastRenewalDate) !== null && _c !== void 0 ? _c : purchase.purchaseDate) !== null && _d !== void 0 ? _d : 0))) {\n                            indexed[key] = Object.assign(Object.assign({}, purchase), { platform: receipt.platform });\n                        }\n                    }\n                }\n                return Object.keys(indexed).map(key => indexed[key]);\n            }\n        }\n        Internal.VerifiedReceipts = VerifiedReceipts;\n    })(Internal = CdvPurchase.Internal || (CdvPurchase.Internal = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Define types for ApplePay\n     *\n     * At the moment Apple Pay is only supported as an extension for Braintree.\n     */\n    let ApplePay;\n    (function (ApplePay) {\n        /** The fields that describe a contact. */\n        let ContactField;\n        (function (ContactField) {\n            ContactField[\"Name\"] = \"name\";\n            ContactField[\"EmailAddress\"] = \"emailAddress\";\n            ContactField[\"PhoneNumber\"] = \"phoneNumber\";\n            ContactField[\"PostalAddress\"] = \"postalAddress\";\n            ContactField[\"PhoneticName\"] = \"phoneticName\";\n        })(ContactField = ApplePay.ContactField || (ApplePay.ContactField = {}));\n        /** A type that represents a payment method. */\n        let PaymentNetwork;\n        (function (PaymentNetwork) {\n            /** An American Express payment card. */\n            PaymentNetwork[\"Amex\"] = \"Amex\";\n            /** A QR code used for payment. */\n            PaymentNetwork[\"Barcode\"] = \"Barcode\";\n            /** A Cartes Bancaires payment card. */\n            PaymentNetwork[\"CartesBancaires\"] = \"CartesBancaires\";\n            /** A China Union Pay payment card. */\n            PaymentNetwork[\"ChinaUnionPay\"] = \"ChinaUnionPay\";\n            /** The Dankort payment card. */\n            PaymentNetwork[\"Dankort\"] = \"Dankort\";\n            /** A Discover payment card. */\n            PaymentNetwork[\"Discover\"] = \"Discover\";\n            /** The electronic funds transfer at point of sale (EFTPOS) payment method. */\n            PaymentNetwork[\"Eftpos\"] = \"Eftpos\";\n            /** An Electron debit card. */\n            PaymentNetwork[\"Electron\"] = \"Electron\";\n            /** The Elo payment card. */\n            PaymentNetwork[\"Elo\"] = \"Elo\";\n            /** A Girocard payment method. */\n            PaymentNetwork[\"Girocard\"] = \"Girocard\";\n            /** An iD payment card. */\n            PaymentNetwork[\"IDCredit\"] = \"IDCredit\";\n            /** The Interac payment method. */\n            PaymentNetwork[\"Interac\"] = \"Interac\";\n            /** A JCB payment card. */\n            PaymentNetwork[\"JCB\"] = \"JCB\";\n            /** A mada payment card. */\n            PaymentNetwork[\"Mada\"] = \"Mada\";\n            /** A Maestro payment card. */\n            PaymentNetwork[\"Maestro\"] = \"Maestro\";\n            /** A MasterCard payment card. */\n            PaymentNetwork[\"MasterCard\"] = \"MasterCard\";\n            /** A Mir payment card. */\n            PaymentNetwork[\"Mir\"] = \"Mir\";\n            /** A Nanaco payment card. */\n            PaymentNetwork[\"Nanaco\"] = \"Nanaco\";\n            /** Store credit and debit cards. */\n            PaymentNetwork[\"PrivateLabel\"] = \"PrivateLabel\";\n            /** A QUICPay payment card. */\n            PaymentNetwork[\"QuicPay\"] = \"QuicPay\";\n            /** A Suica payment card. */\n            PaymentNetwork[\"Suica\"] = \"Suica\";\n            /** A Visa payment card. */\n            PaymentNetwork[\"Visa\"] = \"Visa\";\n            /** A Visa V Pay payment card. */\n            PaymentNetwork[\"VPay\"] = \"VPay\";\n            /** A WAON payment card. */\n            PaymentNetwork[\"Waon\"] = \"Waon\";\n        })(PaymentNetwork = ApplePay.PaymentNetwork || (ApplePay.PaymentNetwork = {}));\n        /** Capabilities for processing payment. */\n        let MerchantCapability;\n        (function (MerchantCapability) {\n            /** Support for the 3-D Secure protocol. */\n            MerchantCapability[\"ThreeDS\"] = \"3DS\";\n            /** Support for the EMV protocol. */\n            MerchantCapability[\"EMV\"] = \"EMV\";\n            /** Support for credit cards. */\n            MerchantCapability[\"Credit\"] = \"Credit\";\n            /** Support for debit cards. */\n            MerchantCapability[\"Debit\"] = \"Debit\";\n        })(MerchantCapability = ApplePay.MerchantCapability || (ApplePay.MerchantCapability = {}));\n    })(ApplePay = CdvPurchase.ApplePay || (CdvPurchase.ApplePay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"../../types.ts\" />\n/// <reference path=\"../../product.ts\" />\n/// <reference path=\"../../receipt.ts\" />\n/// <reference path=\"../../offer.ts\" />\n/// <reference path=\"../../transaction.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Apple AppStore adapter using StoreKit version 1\n     */\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        /**\n         * In the first stages of a purchase, the transaction doesn't have an identifier.\n         *\n         * In the meantime, we generate a virtual transaction identifier.\n         */\n        function virtualTransactionId(productId) {\n            return `virtual.${productId}`;\n        }\n        /**\n         * Adapter for Apple AppStore using StoreKit version 1\n         */\n        class Adapter {\n            constructor(context, options) {\n                var _a, _b;\n                this.id = CdvPurchase.Platform.APPLE_APPSTORE;\n                this.name = 'AppStore';\n                this.ready = false;\n                this._canMakePayments = false;\n                /**\n                 * Set to true to force a full refresh of the receipt when preparing a receipt validation call.\n                 *\n                 * This is typically done when placing an order and restoring purchases.\n                 */\n                this.forceReceiptReload = false;\n                /** List of products loaded from AppStore */\n                this._products = [];\n                this.validProducts = {};\n                this._paymentMonitor = () => { };\n                this.supportsParallelLoading = true;\n                /** True iff the appStoreReceipt is already being initialized */\n                this._appStoreReceiptLoading = false;\n                /** List of functions waiting for the appStoreReceipt to be initialized */\n                this._appStoreReceiptCallbacks = [];\n                this.context = context;\n                this.bridge = new AppleAppStore.Bridge.Bridge();\n                this.log = context.log.child('AppleAppStore');\n                this.discountEligibilityDeterminer = options.discountEligibilityDeterminer;\n                this.needAppReceipt = (_a = options.needAppReceipt) !== null && _a !== void 0 ? _a : true;\n                this.autoFinish = (_b = options.autoFinish) !== null && _b !== void 0 ? _b : false;\n                this.pseudoReceipt = new CdvPurchase.Receipt(CdvPurchase.Platform.APPLE_APPSTORE, this.context.apiDecorators);\n                this.receiptsUpdated = CdvPurchase.Utils.createDebouncer(() => {\n                    this._receiptsUpdated();\n                }, 300);\n            }\n            get products() { return this._products; }\n            /** Find a given product from ID */\n            getProduct(id) { return this._products.find(p => p.id === id); }\n            get receipts() {\n                if (!this.isSupported)\n                    return [];\n                return (this._receipt ? [this._receipt] : [])\n                    .concat(this.pseudoReceipt ? this.pseudoReceipt : []);\n            }\n            addValidProducts(registerProducts, validProducts) {\n                validProducts.forEach(vp => {\n                    const rp = registerProducts.find(p => p.id === vp.id);\n                    if (!rp)\n                        return;\n                    this.validProducts[vp.id] = Object.assign(Object.assign({}, vp), rp);\n                });\n            }\n            /** Returns true on iOS, the only platform supported by this adapter */\n            get isSupported() {\n                return CdvPurchase.Utils.platformId() === 'ios';\n            }\n            upsertTransactionInProgress(productId, state) {\n                const transactionId = virtualTransactionId(productId);\n                return new Promise(resolve => {\n                    const existing = this.pseudoReceipt.transactions.find(t => t.transactionId === transactionId);\n                    if (existing) {\n                        existing.state = state;\n                        existing.refresh(productId);\n                        resolve(existing);\n                    }\n                    else {\n                        const tr = new AppleAppStore.SKTransaction(CdvPurchase.Platform.APPLE_APPSTORE, this.pseudoReceipt, this.context.apiDecorators);\n                        tr.state = state;\n                        tr.transactionId = transactionId;\n                        tr.refresh(productId);\n                        this.pseudoReceipt.transactions.push(tr);\n                        resolve(tr);\n                    }\n                });\n            }\n            /** Remove a transaction from the pseudo receipt */\n            removeTransactionInProgress(productId) {\n                const transactionId = virtualTransactionId(productId);\n                this.pseudoReceipt.transactions = this.pseudoReceipt.transactions.filter(t => t.transactionId !== transactionId);\n            }\n            /** Insert or update a transaction in the pseudo receipt, based on data collected from the native side */\n            upsertTransaction(productId, transactionId, state) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return new Promise(resolve => {\n                        this.initializeAppReceipt(() => {\n                            var _a;\n                            if (!this._receipt) {\n                                // this should not happen\n                                this.log.warn('Failed to load the application receipt, cannot proceed with handling the purchase');\n                                return;\n                            }\n                            const existing = (_a = this._receipt) === null || _a === void 0 ? void 0 : _a.transactions.find(t => t.transactionId === transactionId);\n                            if (existing) {\n                                existing.state = state;\n                                existing.refresh(productId);\n                                resolve(existing);\n                            }\n                            else {\n                                const tr = new AppleAppStore.SKTransaction(CdvPurchase.Platform.APPLE_APPSTORE, this._receipt, this.context.apiDecorators);\n                                tr.state = state;\n                                tr.transactionId = transactionId;\n                                tr.refresh(productId);\n                                this._receipt.transactions.push(tr);\n                                resolve(tr);\n                            }\n                        });\n                    });\n                });\n            }\n            removeTransaction(transactionId) {\n                if (this._receipt) {\n                    this._receipt.transactions = this._receipt.transactions.filter(t => t.transactionId !== transactionId);\n                }\n            }\n            /** Notify the store that the receipts have been updated */\n            _receiptsUpdated() {\n                if (this._receipt) {\n                    this.log.debug(\"receipt updated and ready.\");\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this._receipt, this.pseudoReceipt]);\n                    this.context.listener.receiptsReady(CdvPurchase.Platform.APPLE_APPSTORE);\n                }\n                else {\n                    this.log.debug(\"receipt updated.\");\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this.pseudoReceipt]);\n                }\n            }\n            setPaymentMonitor(fn) {\n                this._paymentMonitor = fn;\n            }\n            callPaymentMonitor(status, code, message) {\n                this._paymentMonitor(status);\n            }\n            initialize() {\n                return new Promise(resolve => {\n                    this.log.info('bridge.init');\n                    const bridgeLogger = this.log.child('Bridge');\n                    this.bridge.init({\n                        autoFinish: this.autoFinish,\n                        debug: this.context.verbosity === CdvPurchase.LogLevel.DEBUG,\n                        log: msg => bridgeLogger.debug(msg),\n                        error: (code, message, options) => {\n                            this.log.error('ERROR: ' + code + ' - ' + message);\n                            if (code === CdvPurchase.ErrorCode.PAYMENT_CANCELLED) {\n                                // When the user closes the payment sheet, this generates a\n                                // PAYMENT_CANCELLED error that isn't an error anymore since version 13\n                                // of the plugin.\n                                this.callPaymentMonitor('cancelled', CdvPurchase.ErrorCode.PAYMENT_CANCELLED, message);\n                                return;\n                            }\n                            else {\n                                this.context.error(appStoreError(code, message, (options === null || options === void 0 ? void 0 : options.productId) || null));\n                            }\n                        },\n                        ready: () => {\n                            this.log.info('ready');\n                        },\n                        purchased: (transactionIdentifier, productId, originalTransactionIdentifier, transactionDate, discountId) => __awaiter(this, void 0, void 0, function* () {\n                            this.log.info('purchase: id:' + transactionIdentifier + ' product:' + productId + ' originalTransaction:' + originalTransactionIdentifier + ' - date:' + transactionDate + ' - discount:' + discountId);\n                            // we can add the transaction to the receipt here\n                            const transaction = yield this.upsertTransaction(productId, transactionIdentifier, CdvPurchase.TransactionState.APPROVED);\n                            transaction.refresh(productId, originalTransactionIdentifier, transactionDate, discountId);\n                            this.removeTransactionInProgress(productId);\n                            this.receiptsUpdated.call();\n                            this.callPaymentMonitor('purchased');\n                        }),\n                        purchaseEnqueued: (productId, quantity) => __awaiter(this, void 0, void 0, function* () {\n                            this.log.info('purchaseEnqueued: ' + productId + ' - ' + quantity);\n                            // let create a temporary transaction\n                            yield this.upsertTransactionInProgress(productId, CdvPurchase.TransactionState.INITIATED);\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this.pseudoReceipt]);\n                        }),\n                        purchaseFailed: (productId, code, message) => {\n                            this.log.info('purchaseFailed: ' + productId + ' - ' + code + ' - ' + message);\n                            this.removeTransactionInProgress(productId);\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this.pseudoReceipt]);\n                            this.callPaymentMonitor('failed', code, message);\n                        },\n                        purchasing: (productId) => __awaiter(this, void 0, void 0, function* () {\n                            // purchase has been requested, but there's no transactionIdentifier yet.\n                            // we can create a dummy transaction\n                            this.log.info('purchasing: ' + productId);\n                            yield this.upsertTransactionInProgress(productId, CdvPurchase.TransactionState.INITIATED);\n                            // In order to prevent a receipt validation attempt here\n                            // (which might happen if it hasn't been possible earlier)\n                            // We should add \"purchasing\" transactions into a second, pseudo receipt.\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this.pseudoReceipt]);\n                        }),\n                        deferred: (productId) => __awaiter(this, void 0, void 0, function* () {\n                            this.log.info('deferred: ' + productId);\n                            yield this.upsertTransactionInProgress(productId, CdvPurchase.TransactionState.PENDING);\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [this.pseudoReceipt]);\n                            this.callPaymentMonitor('deferred');\n                        }),\n                        finished: (transactionIdentifier, productId) => __awaiter(this, void 0, void 0, function* () {\n                            // An issue occurs here if finished is triggered the \"debounced\" receiptUpdated call has\n                            // been performed for the APPROVED event. Because the transaction will go straight to\n                            // FINISHED, skipping validation.\n                            //\n                            // This was observed specifically when \"autoFinish\" is set.\n                            //\n                            // In order to get rid of that bug, we want to wait for processing of the previous\n                            // receiptUpdated call.\n                            //\n                            // A side effect will be that when there are many \"finished\" transactions, how could we process\n                            // them all in batch?\n                            yield this.receiptsUpdated.wait();\n                            this.log.info('finish: ' + transactionIdentifier + ' - ' + productId);\n                            this.removeTransactionInProgress(productId);\n                            yield this.upsertTransaction(productId, transactionIdentifier, CdvPurchase.TransactionState.FINISHED);\n                            this.receiptsUpdated.call();\n                        }),\n                        restored: (transactionIdentifier, productId) => __awaiter(this, void 0, void 0, function* () {\n                            this.log.info('restore: ' + transactionIdentifier + ' - ' + productId);\n                            yield this.upsertTransaction(productId, transactionIdentifier, CdvPurchase.TransactionState.APPROVED);\n                            this.receiptsUpdated.call();\n                        }),\n                        receiptsRefreshed: (receipt) => {\n                            this.log.info('receiptsRefreshed');\n                            if (this._receipt)\n                                this._receipt.refresh(receipt, this.needAppReceipt, this.context.apiDecorators);\n                        },\n                        restoreFailed: (errorCode) => {\n                            this.log.info('restoreFailed: ' + errorCode);\n                            if (this.onRestoreCompleted) {\n                                this.onRestoreCompleted(appStoreError(errorCode, 'Restore purchases failed', null));\n                                this.onRestoreCompleted = undefined;\n                            }\n                        },\n                        restoreCompleted: () => {\n                            this.log.info('restoreCompleted');\n                            if (this.onRestoreCompleted) {\n                                this.onRestoreCompleted(undefined);\n                                this.onRestoreCompleted = undefined;\n                            }\n                        },\n                    }, () => __awaiter(this, void 0, void 0, function* () {\n                        this.log.info('bridge.init done');\n                        yield this.canMakePayments();\n                        resolve(undefined);\n                    }), (code, message) => {\n                        this.log.info('bridge.init failed: ' + code + ' - ' + message);\n                        resolve(appStoreError(code, message, null));\n                    });\n                });\n            }\n            loadReceipts() {\n                return new Promise((resolve) => {\n                    setTimeout(() => {\n                        this.initializeAppReceipt(() => {\n                            this.receiptsUpdated.call();\n                            if (this._receipt) {\n                                resolve([this._receipt, this.pseudoReceipt]);\n                            }\n                            else {\n                                resolve([this.pseudoReceipt]);\n                            }\n                        });\n                    }, 300);\n                });\n            }\n            canMakePayments() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return new Promise(resolve => {\n                        this.bridge.canMakePayments(() => {\n                            this._canMakePayments = true;\n                            resolve(true);\n                        }, (message) => {\n                            this.log.warn(`canMakePayments: ${message}`);\n                            this._canMakePayments = false;\n                            resolve(false);\n                        });\n                    });\n                });\n            }\n            /**\n             * Create the application receipt\n             */\n            initializeAppReceipt(callback) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (this._receipt) {\n                        this.log.debug('initializeAppReceipt() => already initialized.');\n                        return callback(undefined);\n                    }\n                    this._appStoreReceiptCallbacks.push(callback);\n                    if (this._appStoreReceiptLoading) {\n                        this.log.debug('initializeAppReceipt() => already loading.');\n                        return;\n                    }\n                    this._appStoreReceiptLoading = true;\n                    const nativeData = yield this.loadAppStoreReceipt();\n                    const callCallbacks = (arg) => {\n                        const callbacks = this._appStoreReceiptCallbacks;\n                        this._appStoreReceiptCallbacks = [];\n                        callbacks.forEach(cb => {\n                            cb(arg);\n                        });\n                    };\n                    if (!(nativeData === null || nativeData === void 0 ? void 0 : nativeData.appStoreReceipt)) {\n                        this.log.warn('no appStoreReceipt');\n                        this._appStoreReceiptLoading = false;\n                        callCallbacks(appStoreError(CdvPurchase.ErrorCode.REFRESH, 'No appStoreReceipt', null));\n                        return;\n                    }\n                    this._receipt = new AppleAppStore.SKApplicationReceipt(nativeData, this.needAppReceipt, this.context.apiDecorators);\n                    callCallbacks(undefined);\n                });\n            }\n            prepareReceipt(nativeData) {\n                if (nativeData === null || nativeData === void 0 ? void 0 : nativeData.appStoreReceipt) {\n                    if (!this._receipt) {\n                        this._receipt = new AppleAppStore.SKApplicationReceipt(nativeData, this.needAppReceipt, this.context.apiDecorators);\n                    }\n                    else {\n                        this._receipt.refresh(nativeData, this.needAppReceipt, this.context.apiDecorators);\n                    }\n                }\n            }\n            /** Promisified loading of the AppStore receipt */\n            loadAppStoreReceipt() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    let resolved = false;\n                    return new Promise(resolve => {\n                        var _a;\n                        if (((_a = this.bridge.appStoreReceipt) === null || _a === void 0 ? void 0 : _a.appStoreReceipt) && !this.forceReceiptReload) {\n                            this.log.debug('using cached appstore receipt');\n                            return resolve(this.bridge.appStoreReceipt);\n                        }\n                        this.log.debug('loading appstore receipt...');\n                        this.forceReceiptReload = false;\n                        this.bridge.loadReceipts(receipt => {\n                            this.log.debug('appstore receipt loaded');\n                            if (!resolved)\n                                resolve(receipt);\n                            resolved = true;\n                        }, (code, message) => {\n                            // this should not happen: native side never triggers an error\n                            this.log.warn('Failed to load appStoreReceipt: ' + code + ' - ' + message);\n                            if (!resolved)\n                                resolve(undefined);\n                            resolved = true;\n                        });\n                        // If the receipt cannot be loaded, timeout after 5 seconds\n                        setTimeout(function () {\n                            if (!resolved)\n                                resolve(undefined);\n                            resolved = true;\n                        }, 5000);\n                    }).then(result => {\n                        this.context.listener.receiptsReady(CdvPurchase.Platform.APPLE_APPSTORE);\n                        return result;\n                    }).catch(reason => {\n                        this.context.listener.receiptsReady(CdvPurchase.Platform.APPLE_APPSTORE);\n                        return reason;\n                    });\n                });\n            }\n            loadEligibility(validProducts) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.debug('load eligibility: ' + JSON.stringify(validProducts));\n                    if (!this.discountEligibilityDeterminer) {\n                        this.log.debug('No discount eligibility determiner, skipping...');\n                        return new AppleAppStore.Internal.DiscountEligibilities([], []);\n                    }\n                    const eligibilityRequests = [];\n                    validProducts.forEach(valid => {\n                        var _a, _b, _c;\n                        (_a = valid.discounts) === null || _a === void 0 ? void 0 : _a.forEach(discount => {\n                            eligibilityRequests.push({\n                                productId: valid.id,\n                                discountId: discount.id,\n                                discountType: discount.type,\n                            });\n                        });\n                        if (((_c = (_b = valid.discounts) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) === 0 && valid.introPrice) {\n                            // sometime apple returns the discounts in the deprecated \"introductory\" info\n                            // we create a special \"discount\" with the id \"intro\" to check for eligibility.\n                            eligibilityRequests.push({\n                                productId: valid.id,\n                                discountId: 'intro',\n                                discountType: 'Introductory',\n                            });\n                        }\n                    });\n                    if (eligibilityRequests.length > 0) {\n                        const applicationReceipt = yield this.loadAppStoreReceipt();\n                        if (!applicationReceipt || !applicationReceipt.appStoreReceipt) {\n                            this.log.debug('no receipt, assuming introductory price are available.');\n                            return new AppleAppStore.Internal.DiscountEligibilities(eligibilityRequests, eligibilityRequests.map(r => r.discountType === \"Introductory\"));\n                        }\n                        else {\n                            this.log.debug('calling discount eligibility determiner.');\n                            const response = yield this.callDiscountEligibilityDeterminer(applicationReceipt, eligibilityRequests);\n                            this.log.debug('response: ' + JSON.stringify(response));\n                            return new AppleAppStore.Internal.DiscountEligibilities(eligibilityRequests, response);\n                        }\n                    }\n                    else {\n                        return new AppleAppStore.Internal.DiscountEligibilities([], []);\n                    }\n                });\n            }\n            callDiscountEligibilityDeterminer(applicationReceipt, eligibilityRequests) {\n                return new Promise(resolve => {\n                    if (!this.discountEligibilityDeterminer)\n                        return resolve([]);\n                    this.discountEligibilityDeterminer(applicationReceipt, eligibilityRequests, resolve);\n                });\n            }\n            loadProducts(products) {\n                return new Promise(resolve => {\n                    this.log.info('bridge.load');\n                    this.bridge.load(products.map(p => p.id), (validProducts, invalidProducts) => __awaiter(this, void 0, void 0, function* () {\n                        this.log.info('bridge.loaded: ' + JSON.stringify({ validProducts, invalidProducts }));\n                        this.addValidProducts(products, validProducts);\n                        const eligibilities = yield this.loadEligibility(validProducts);\n                        this.log.info('eligibilities ready: ' + JSON.stringify(eligibilities));\n                        // for any valid product that includes a discount, check the eligibility.\n                        const ret = products.map(p => {\n                            if (invalidProducts.indexOf(p.id) >= 0) {\n                                this.log.debug(`${p.id} is invalid`);\n                                return appStoreError(CdvPurchase.ErrorCode.INVALID_PRODUCT_ID, 'Product not found in AppStore. #400', p.id);\n                            }\n                            else {\n                                const valid = validProducts.find(v => v.id === p.id);\n                                this.log.debug(`${p.id} is valid: ${JSON.stringify(valid)}`);\n                                if (!valid)\n                                    return appStoreError(CdvPurchase.ErrorCode.INVALID_PRODUCT_ID, 'Product not found in AppStore. #404', p.id);\n                                let product = this.getProduct(p.id);\n                                if (product) {\n                                    this.log.debug('refreshing existing product');\n                                    product === null || product === void 0 ? void 0 : product.refresh(valid, this.context.apiDecorators, eligibilities);\n                                }\n                                else {\n                                    this.log.debug('registering new product');\n                                    product = new AppleAppStore.SKProduct(valid, p, this.context.apiDecorators, eligibilities);\n                                    this._products.push(product);\n                                }\n                                return product;\n                            }\n                        });\n                        this.log.debug(`Products loaded: ${JSON.stringify(ret)}`);\n                        resolve(ret);\n                    }), (code, message) => {\n                        return products.map(p => appStoreError(code, message, null));\n                    });\n                });\n            }\n            order(offer, additionalData) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    let resolved = false;\n                    return new Promise(resolve => {\n                        var _a;\n                        const callResolve = (result) => {\n                            if (resolved)\n                                return;\n                            this.setPaymentMonitor(() => { });\n                            resolved = true;\n                            resolve(result);\n                        };\n                        this.log.info('order');\n                        const discountId = offer.id !== AppleAppStore.DEFAULT_OFFER_ID ? offer.id : undefined;\n                        const discount = (_a = additionalData === null || additionalData === void 0 ? void 0 : additionalData.appStore) === null || _a === void 0 ? void 0 : _a.discount;\n                        if (discountId && !discount) {\n                            return callResolve(appStoreError(CdvPurchase.ErrorCode.MISSING_OFFER_PARAMS, 'Missing additionalData.appStore.discount when ordering a discount offer', offer.productId));\n                        }\n                        if (discountId && ((discount === null || discount === void 0 ? void 0 : discount.id) !== discountId)) {\n                            return callResolve(appStoreError(CdvPurchase.ErrorCode.INVALID_OFFER_IDENTIFIER, 'Offer identifier does not match additionalData.appStore.discount.id', offer.productId));\n                        }\n                        this.setPaymentMonitor((status, code, message) => {\n                            this.log.info('order.paymentMonitor => ' + status + ' ' + (code !== null && code !== void 0 ? code : '') + ' ' + (message !== null && message !== void 0 ? message : ''));\n                            if (resolved)\n                                return;\n                            switch (status) {\n                                case 'cancelled':\n                                    callResolve(appStoreError(code !== null && code !== void 0 ? code : CdvPurchase.ErrorCode.PAYMENT_CANCELLED, message !== null && message !== void 0 ? message : 'The user cancelled the order.', offer.productId));\n                                    break;\n                                case 'failed':\n                                    // note, \"failed\" might be triggered before \"cancelled\",\n                                    // so we'll give some time to catch the \"cancelled\" event.\n                                    setTimeout(() => {\n                                        callResolve(appStoreError(code !== null && code !== void 0 ? code : CdvPurchase.ErrorCode.PURCHASE, message !== null && message !== void 0 ? message : 'Purchase failed', offer.productId));\n                                    }, 500);\n                                    break;\n                                case 'purchased':\n                                case 'deferred':\n                                    callResolve(undefined);\n                                    break;\n                            }\n                        });\n                        const success = () => {\n                            this.log.info('order.success');\n                            // We'll monitor the payment before resolving.\n                        };\n                        const error = () => {\n                            this.log.info('order.error');\n                            callResolve(appStoreError(CdvPurchase.ErrorCode.PURCHASE, 'Failed to place order', offer.productId));\n                        };\n                        // When we switch AppStore user, the cached receipt isn't from the new user.\n                        // so after a purchase, we want to make sure we're using the receipt from the logged in user.\n                        this.forceReceiptReload = true;\n                        this.bridge.purchase(offer.productId, 1, this.context.getApplicationUsername(), discount, success, error);\n                    });\n                });\n            }\n            finish(transaction) {\n                return new Promise(resolve => {\n                    this.log.info('finish(' + transaction.transactionId + ')');\n                    if (transaction.transactionId === AppleAppStore.APPLICATION_VIRTUAL_TRANSACTION_ID || transaction.transactionId === virtualTransactionId(transaction.products[0].id)) {\n                        // this is a virtual transaction, nothing to do.\n                        transaction.state = CdvPurchase.TransactionState.FINISHED;\n                        this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [transaction.parentReceipt]);\n                        return resolve(undefined);\n                    }\n                    const success = () => {\n                        transaction.state = CdvPurchase.TransactionState.FINISHED;\n                        this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [transaction.parentReceipt]);\n                        resolve(undefined);\n                    };\n                    const error = (msg) => {\n                        var _a, _b;\n                        if (msg === null || msg === void 0 ? void 0 : msg.includes('[#CdvPurchase:100]')) {\n                            // already finished\n                            success();\n                        }\n                        else {\n                            resolve(appStoreError(CdvPurchase.ErrorCode.FINISH, 'Failed to finish transaction', (_b = (_a = transaction.products[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null));\n                        }\n                    };\n                    this.bridge.finish(transaction.transactionId, success, error);\n                });\n            }\n            refreshReceipt() {\n                return new Promise(resolve => {\n                    const success = (receipt) => {\n                        // at that point, the receipt should have been refreshed.\n                        resolve(receipt);\n                    };\n                    const error = (code, message) => {\n                        resolve(appStoreError(code, message, null));\n                    };\n                    this.bridge.refreshReceipts(success, error);\n                });\n            }\n            receiptValidationBody(receipt) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (receipt.platform !== CdvPurchase.Platform.APPLE_APPSTORE)\n                        return;\n                    if (receipt !== this._receipt)\n                        return; // do not validate the pseudo receipt\n                    const skReceipt = receipt;\n                    let applicationReceipt = skReceipt.nativeData;\n                    if (this.forceReceiptReload) {\n                        const nativeData = yield this.loadAppStoreReceipt();\n                        this.forceReceiptReload = false;\n                        if (nativeData) {\n                            applicationReceipt = nativeData;\n                            this.prepareReceipt(nativeData);\n                        }\n                    }\n                    if (!skReceipt.nativeData.appStoreReceipt) {\n                        this.log.info('Cannot prepare the receipt validation body, because appStoreReceipt is missing. Refreshing...');\n                        const result = yield this.refreshReceipt();\n                        if (!result || 'isError' in result) {\n                            this.log.warn('Failed to refresh receipt, cannot run receipt validation.');\n                            if (result)\n                                this.log.error(result);\n                            return;\n                        }\n                        this.log.info('Receipt refreshed.');\n                        applicationReceipt = result;\n                    }\n                    const transaction = skReceipt.transactions.slice(-1)[0];\n                    return {\n                        id: applicationReceipt.bundleIdentifier,\n                        type: CdvPurchase.ProductType.APPLICATION,\n                        // send all products and offers so validator get pricing information\n                        products: CdvPurchase.Utils.objectValues(this.validProducts).map(vp => new AppleAppStore.SKProduct(vp, vp, this.context.apiDecorators, { isEligible: () => true })),\n                        transaction: {\n                            type: 'ios-appstore',\n                            id: transaction === null || transaction === void 0 ? void 0 : transaction.transactionId,\n                            appStoreReceipt: applicationReceipt.appStoreReceipt,\n                        }\n                    };\n                });\n            }\n            handleReceiptValidationResponse(_receipt, response) {\n                var _a, _b;\n                return __awaiter(this, void 0, void 0, function* () {\n                    // we can add the purchaseDate to the application transaction\n                    let localReceiptUpdated = false;\n                    if (response.ok) {\n                        const vTransaction = (_a = response.data) === null || _a === void 0 ? void 0 : _a.transaction;\n                        if ((vTransaction === null || vTransaction === void 0 ? void 0 : vTransaction.type) === 'ios-appstore' && 'original_application_version' in vTransaction) {\n                            (_b = this._receipt) === null || _b === void 0 ? void 0 : _b.transactions.forEach(t => {\n                                if (t.transactionId === AppleAppStore.APPLICATION_VIRTUAL_TRANSACTION_ID) {\n                                    if (vTransaction.original_purchase_date_ms) {\n                                        t.purchaseDate = new Date(parseInt(vTransaction.original_purchase_date_ms));\n                                        localReceiptUpdated = true;\n                                    }\n                                }\n                            });\n                        }\n                    }\n                    if (localReceiptUpdated)\n                        this.context.listener.receiptsUpdated(CdvPurchase.Platform.APPLE_APPSTORE, [_receipt]);\n                });\n            }\n            requestPayment(payment, additionalData) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return appStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'requestPayment not supported', null);\n                });\n            }\n            manageSubscriptions() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.bridge.manageSubscriptions();\n                    return;\n                });\n            }\n            manageBilling() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.bridge.manageBilling();\n                    return;\n                });\n            }\n            checkSupport(functionality) {\n                if (functionality === 'order')\n                    return this._canMakePayments;\n                const supported = [\n                    'order', 'manageBilling', 'manageSubscriptions'\n                ];\n                return supported.indexOf(functionality) >= 0;\n            }\n            restorePurchases() {\n                return new Promise(resolve => {\n                    this.onRestoreCompleted = (error) => {\n                        this.onRestoreCompleted = undefined;\n                        this.bridge.refreshReceipts(obj => {\n                            resolve(error);\n                        }, (code, message) => {\n                            resolve(error || appStoreError(code, message, null));\n                        });\n                    };\n                    this.forceReceiptReload = true;\n                    this.bridge.restore();\n                });\n            }\n            presentCodeRedemptionSheet() {\n                return new Promise(resolve => {\n                    this.bridge.presentCodeRedemptionSheet(resolve);\n                });\n            }\n        }\n        AppleAppStore.Adapter = Adapter;\n        function appStoreError(code, message, productId) {\n            return CdvPurchase.storeError(code, message, CdvPurchase.Platform.APPLE_APPSTORE, productId);\n        }\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        let Bridge;\n        (function (Bridge_1) {\n            /** No-operation function, used as a default for callbacks */\n            const noop = (args) => { };\n            /** Logger */\n            let log = noop;\n            /** Execute a native method */\n            function exec(methodName, options, success, error) {\n                window.cordova.exec(success, error, \"InAppPurchase\", methodName, options);\n            }\n            ;\n            /** Execute a javascript-side method in a try-catch block */\n            function protectCall(callback, context, ...args) {\n                if (!callback) {\n                    return;\n                }\n                try {\n                    // const args = Array.prototype.slice.call(arguments, 2);\n                    callback.apply(this, args);\n                }\n                catch (err) {\n                    log('exception in ' + context + ': \"' + err + '\"');\n                }\n            }\n            ;\n            class Bridge {\n                constructor() {\n                    /** Transactions for a given product */\n                    this.transactionsForProduct = {};\n                    /** True when the SDK has been initialized */\n                    this.initialized = false;\n                    /** List of registered product identifiers */\n                    this.registeredProducts = [];\n                    /** True if \"restoreCompleted\" or \"restoreFailed\" should be called when restore is done */\n                    this.needRestoreNotification = false;\n                    /*\n                    private eventQueue: {\n                        state: TransactionState;\n                        errorCode: ErrorCode | undefined;\n                        errorText: string | undefined;\n                        transactionIdentifier: string;\n                        productId: string;\n                        /** @deprecated *\n                        transactionReceipt: never;\n                        originalTransactionIdentifier: string | undefined;\n                        transactionDate: string;\n                        discountId: string;\n                    }[] = [];\n    \n                    private timer: number | null = null;\n                    */\n                    /** List of transaction updates to process */\n                    this.pendingUpdates = [];\n                    /** @deprecated */\n                    this.onPurchased = false;\n                    /** @deprecated */\n                    this.onFailed = false;\n                    /** @deprecated */\n                    this.onRestored = false;\n                    window.storekit = this; // used by native to communicate with this bridge\n                    this.options = {\n                        error: noop,\n                        ready: noop,\n                        purchased: noop,\n                        purchaseEnqueued: noop,\n                        purchasing: noop,\n                        purchaseFailed: noop,\n                        deferred: noop,\n                        finished: noop,\n                        restored: noop,\n                        receiptsRefreshed: noop,\n                        restoreFailed: noop,\n                        restoreCompleted: noop,\n                    };\n                    // if (window.localStorage && window.localStorage.sk_transactionForProduct)\n                    // this.transactionsForProduct = JSON.parse(window.localStorage.sk_transactionForProduct);\n                    // Remove support for receipt.forTransaction(...)\n                    // `appStoreReceipt` is now the only supported receipt format on iOS (drops support for iOS <= 6)\n                    // if (window.localStorage.sk_receiptForTransaction)\n                    // delete window.localStorage.sk_receiptForTransaction;\n                }\n                /**\n                 * Initialize the AppStore bridge.\n                 *\n                 * This calls the native \"setup\" method from the \"InAppPurchase\" Objective-C class.\n                 *\n                 * @param options Options for the bridge\n                 * @param success Called when the bridge is ready\n                 * @param error Called when the bridge failed to initialize\n                 */\n                init(options, success, error) {\n                    this.options = {\n                        error: options.error || noop,\n                        ready: options.ready || noop,\n                        purchased: options.purchased || noop,\n                        purchaseEnqueued: options.purchaseEnqueued || noop,\n                        purchasing: options.purchasing || noop,\n                        purchaseFailed: options.purchaseFailed || noop,\n                        deferred: options.deferred || noop,\n                        finished: options.finished || noop,\n                        restored: options.restored || noop,\n                        receiptsRefreshed: options.receiptsRefreshed || noop,\n                        restoreFailed: options.restoreFailed || noop,\n                        restoreCompleted: options.restoreCompleted || noop,\n                    };\n                    if (options.debug) {\n                        exec('debug', [], noop, noop);\n                        log = options.log || function (msg) {\n                            console.log(\"[CdvPurchase.AppAppStore.Bridge] \" + msg);\n                        };\n                    }\n                    if (options.autoFinish) {\n                        exec('autoFinish', [], noop, noop);\n                    }\n                    const setupOk = () => {\n                        log('setup ok');\n                        protectCall(this.options.ready, 'options.ready');\n                        protectCall(success, 'init.success');\n                        this.initialized = true;\n                        setTimeout(() => this.processPendingTransactions(), 50);\n                    };\n                    const setupFailed = (err) => {\n                        log('setup failed');\n                        // protectCall(this.options.error, 'options.error', ErrorCode.SETUP, 'Setup failed');\n                        protectCall(error, 'init.error', CdvPurchase.ErrorCode.SETUP, 'Setup failed: ' + err);\n                    };\n                    exec('setup', [], setupOk, setupFailed);\n                }\n                processPendingTransactions() {\n                    log('processing pending transactions');\n                    exec('processPendingTransactions', [], () => {\n                        this.finalizeTransactionUpdates();\n                    }, undefined);\n                }\n                /**\n                 * Makes an in-app purchase.\n                 *\n                 * @param {String} productId The product identifier. e.g. \"com.example.MyApp.myproduct\"\n                 * @param {int} quantity Quantity of product to purchase\n                 */\n                purchase(productId, quantity, applicationUsername, discount, success, error) {\n                    quantity = (quantity | 0) || 1;\n                    const options = this.options;\n                    // Many people forget to load information about their products from apple's servers before allowing\n                    // users to purchase them... leading them to spam us with useless issues and comments.\n                    // Let's chase them down!\n                    if (this.registeredProducts.indexOf(productId) < 0) {\n                        const msg = 'Purchasing ' + productId + ' failed.  Ensure the product was loaded first with Bridge.load(...)!';\n                        log(msg);\n                        if (typeof options.error === 'function') {\n                            protectCall(options.error, 'options.error', CdvPurchase.ErrorCode.PURCHASE, 'Trying to purchase a unknown product.', { productId, quantity });\n                        }\n                        return;\n                    }\n                    const purchaseOk = () => {\n                        log('Purchase enqueued ' + productId);\n                        if (typeof options.purchaseEnqueued === 'function') {\n                            protectCall(options.purchaseEnqueued, 'options.purchaseEnqueued', productId, quantity);\n                        }\n                        protectCall(success, 'purchase.success');\n                    };\n                    const purchaseFailed = () => {\n                        const errMsg = 'Purchase failed: ' + productId;\n                        log(errMsg);\n                        if (typeof options.error === 'function') {\n                            protectCall(options.error, 'options.error', CdvPurchase.ErrorCode.PURCHASE, errMsg, { productId, quantity });\n                        }\n                        protectCall(error, 'purchase.error');\n                    };\n                    exec('purchase', [productId, quantity, applicationUsername, discount || {}], purchaseOk, purchaseFailed);\n                }\n                /**\n                 * Checks if device/user is allowed to make in-app purchases\n                 */\n                canMakePayments(success, error) {\n                    return exec(\"canMakePayments\", [], success, error);\n                }\n                /**\n                 * Asks the payment queue to restore previously completed purchases.\n                 *\n                 * The restored transactions are passed to the onRestored callback, so make sure you define a handler for that first.\n                 */\n                restore(callback) {\n                    this.needRestoreNotification = true;\n                    exec('restoreCompletedTransactions', [], callback, callback);\n                }\n                manageSubscriptions(callback) {\n                    exec('manageSubscriptions', [], callback, callback);\n                }\n                manageBilling(callback) {\n                    exec('manageBilling', [], callback, callback);\n                }\n                presentCodeRedemptionSheet(callback) {\n                    exec('presentCodeRedemptionSheet', [], callback, callback);\n                }\n                /**\n                 * Retrieves localized product data, including price (as localized\n                 * string), name, description of multiple products.\n                 *\n                 * @param {Array} productIds\n                 *   An array of product identifier strings.\n                 *\n                 * @param {Function} callback\n                 *   Called once with the result of the products request. Signature:\n                 *\n                 *     function(validProducts, invalidProductIds)\n                 *\n                 *   where validProducts receives an array of objects of the form:\n                 *\n                 *     {\n                 *       id: \"<productId>\",\n                 *       title: \"<localised title>\",\n                 *       description: \"<localised escription>\",\n                 *       price: \"<localised price>\"\n                 *     }\n                 *\n                 *  and invalidProductIds receives an array of product identifier\n                 *  strings which were rejected by the app store.\n                 */\n                load(productIds, success, error) {\n                    const options = this.options;\n                    if (typeof productIds === \"string\") {\n                        productIds = [productIds];\n                    }\n                    if (!productIds) {\n                        // Empty array, nothing to do.\n                        protectCall(success, 'load.success', [], []);\n                    }\n                    else if (!productIds.length) {\n                        // Empty array, nothing to do.\n                        protectCall(success, 'load.success', [], []);\n                    }\n                    else {\n                        if (typeof productIds[0] !== 'string') {\n                            const msg = 'invalid productIds given to store.load: ' + JSON.stringify(productIds);\n                            log(msg);\n                            protectCall(options.error, 'options.error', CdvPurchase.ErrorCode.LOAD, msg);\n                            protectCall(error, 'load.error', CdvPurchase.ErrorCode.LOAD, msg);\n                            return;\n                        }\n                        log('load ' + JSON.stringify(productIds));\n                        const loadOk = (array) => {\n                            const valid = array[0];\n                            const invalid = array[1];\n                            log('load ok: { valid:' + JSON.stringify(valid) + ' invalid:' + JSON.stringify(invalid) + ' }');\n                            protectCall(success, 'load.success', valid, invalid);\n                        };\n                        const loadFailed = (errMessage) => {\n                            log('load failed');\n                            log(errMessage);\n                            const message = 'Load failed: ' + errMessage;\n                            protectCall(options.error, 'options.error', CdvPurchase.ErrorCode.LOAD, message);\n                            protectCall(error, 'load.error', CdvPurchase.ErrorCode.LOAD, message);\n                        };\n                        this.registeredProducts = this.registeredProducts.concat(productIds);\n                        exec('load', [productIds], loadOk, loadFailed);\n                    }\n                }\n                /*\n                 * Finish an unfinished transaction.\n                 *\n                 * @param {String} transactionId\n                 *    Identifier of the transaction to finish.\n                 *\n                 * You have to call this method manually except when using the autoFinish option.\n                 */\n                finish(transactionId, success, error) {\n                    exec('finishTransaction', [transactionId], success, error);\n                }\n                finalizeTransactionUpdates() {\n                    for (let i = 0; i < this.pendingUpdates.length; ++i) {\n                        const args = this.pendingUpdates[i];\n                        this.transactionUpdated(args.state, args.errorCode, args.errorText, args.transactionIdentifier, args.productId, args.transactionReceipt, args.originalTransactionIdentifier, args.transactionDate, args.discountId);\n                    }\n                    this.pendingUpdates = [];\n                }\n                lastTransactionUpdated() {\n                    // no more pending transactions\n                }\n                // This is called from native.\n                //\n                // Note that it may eventually be called before initialization... unfortunately.\n                // In this case, we'll just keep pending updates in a list for later processing.\n                transactionUpdated(state, errorCode, errorText, transactionIdentifier, productId, transactionReceipt, originalTransactionIdentifier, transactionDate, discountId) {\n                    if (!this.initialized) {\n                        this.pendingUpdates.push({ state, errorCode, errorText, transactionIdentifier, productId, transactionReceipt, originalTransactionIdentifier, transactionDate, discountId });\n                        return;\n                    }\n                    log(\"transaction updated:\" + transactionIdentifier + \" state:\" + state + \" product:\" + productId);\n                    if (productId && transactionIdentifier) {\n                        if (this.transactionsForProduct[productId]) {\n                            this.transactionsForProduct[productId].push(transactionIdentifier);\n                        }\n                        else {\n                            this.transactionsForProduct[productId] = [transactionIdentifier];\n                        }\n                    }\n                    switch (state) {\n                        case \"PaymentTransactionStatePurchasing\":\n                            protectCall(this.options.purchasing, 'options.purchasing', productId);\n                            return;\n                        case \"PaymentTransactionStatePurchased\":\n                            protectCall(this.options.purchased, 'options.purchase', transactionIdentifier, productId, originalTransactionIdentifier, transactionDate, discountId);\n                            return;\n                        case \"PaymentTransactionStateDeferred\":\n                            protectCall(this.options.deferred, 'options.deferred', productId);\n                            return;\n                        case \"PaymentTransactionStateFailed\":\n                            protectCall(this.options.purchaseFailed, 'options.purchaseFailed', productId, errorCode || CdvPurchase.ErrorCode.UNKNOWN, errorText || 'ERROR');\n                            protectCall(this.options.error, 'options.error', errorCode || CdvPurchase.ErrorCode.UNKNOWN, errorText || 'ERROR', { productId });\n                            return;\n                        case \"PaymentTransactionStateRestored\":\n                            protectCall(this.options.restored, 'options.restore', transactionIdentifier, productId);\n                            return;\n                        case \"PaymentTransactionStateFinished\":\n                            protectCall(this.options.finished, 'options.finish', transactionIdentifier, productId);\n                            return;\n                    }\n                }\n                restoreCompletedTransactionsFinished() {\n                    if (!this.needRestoreNotification)\n                        return;\n                    this.needRestoreNotification = false;\n                    protectCall(this.options.restoreCompleted, 'options.restoreCompleted');\n                }\n                restoreCompletedTransactionsFailed(errorCode) {\n                    if (!this.needRestoreNotification)\n                        return;\n                    this.needRestoreNotification = false;\n                    protectCall(this.options.restoreFailed, 'options.restoreFailed', errorCode);\n                }\n                parseReceiptArgs(args) {\n                    const base64 = args[0];\n                    const bundleIdentifier = args[1];\n                    const bundleShortVersion = args[2];\n                    const bundleNumericVersion = args[3];\n                    const bundleSignature = args[4];\n                    log('infoPlist: ' + bundleIdentifier + \",\" + bundleShortVersion + \",\" + bundleNumericVersion + \",\" + bundleSignature);\n                    return {\n                        appStoreReceipt: base64,\n                        bundleIdentifier: bundleIdentifier,\n                        bundleShortVersion: bundleShortVersion,\n                        bundleNumericVersion: bundleNumericVersion,\n                        bundleSignature: bundleSignature\n                    };\n                }\n                refreshReceipts(successCb, errorCb) {\n                    const loaded = (args) => {\n                        const data = this.parseReceiptArgs(args);\n                        this.appStoreReceipt = data;\n                        protectCall(this.options.receiptsRefreshed, 'options.receiptsRefreshed', data);\n                        protectCall(successCb, \"refreshReceipts.success\", data);\n                    };\n                    const error = (errMessage) => {\n                        log('refresh receipt failed: ' + errMessage);\n                        if (errMessage.includes(\"(@AMSErrorDomain:100)\")) {\n                            log('authentication failed, indicated by the string \"(@AMSErrorDomain:100)\"');\n                        }\n                        protectCall(this.options.error, 'options.error', CdvPurchase.ErrorCode.REFRESH_RECEIPTS, 'Failed to refresh receipt: ' + errMessage);\n                        protectCall(errorCb, \"refreshReceipts.error\", CdvPurchase.ErrorCode.REFRESH_RECEIPTS, 'Failed to refresh receipt: ' + errMessage);\n                    };\n                    this.appStoreReceipt = null;\n                    log('refreshing appStoreReceipt');\n                    exec('appStoreRefreshReceipt', [], loaded, error);\n                }\n                loadReceipts(callback, errorCb) {\n                    const loaded = (args) => {\n                        const data = this.parseReceiptArgs(args);\n                        this.appStoreReceipt = data;\n                        protectCall(callback, 'loadReceipts.callback', data);\n                    };\n                    const error = (errMessage) => {\n                        // should not happen (native side never triggers an error)\n                        // log('load failed: ' + errMessage);\n                        // protectCall(this.options.error, 'options.error', ErrorCode.LOAD_RECEIPTS, 'Failed to load receipt: ' + errMessage);\n                        // protectCall(errorCb, 'loadReceipts.error', ErrorCode.LOAD_RECEIPTS, 'Failed to load receipt: ' + errMessage);\n                    };\n                    log('loading appStoreReceipt');\n                    exec('appStoreReceipt', [], loaded, error);\n                }\n            }\n            Bridge_1.Bridge = Bridge;\n        })(Bridge = AppleAppStore.Bridge || (AppleAppStore.Bridge = {}));\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Apple AppStore adapter using StoreKit version 1\n     */\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        /** @internal */\n        let Internal;\n        (function (Internal) {\n            class DiscountEligibilities {\n                constructor(request, response) {\n                    this.request = request;\n                    this.response = response;\n                }\n                isEligible(productId, discountType, discountId) {\n                    var _a;\n                    for (let i = 0; i < this.request.length; ++i) {\n                        const req = this.request[i];\n                        if (req.productId === productId && req.discountId === discountId && req.discountType === discountType) {\n                            return (_a = this.response[i]) !== null && _a !== void 0 ? _a : false;\n                        }\n                    }\n                    // No request for this product, let's say it's eligible.\n                    return true;\n                }\n            }\n            Internal.DiscountEligibilities = DiscountEligibilities;\n        })(Internal = AppleAppStore.Internal || (AppleAppStore.Internal = {}));\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Apple AppStore adapter using StoreKit version 1\n     */\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        AppleAppStore.DEFAULT_OFFER_ID = '$';\n        class SKOffer extends CdvPurchase.Offer {\n            constructor(options, decorator) {\n                super(options, decorator);\n                this.offerType = options.offerType;\n            }\n        }\n        AppleAppStore.SKOffer = SKOffer;\n        class SKProduct extends CdvPurchase.Product {\n            constructor(validProduct, p, decorator, eligibilities) {\n                super(p, decorator);\n                this.raw = validProduct;\n                this.refresh(validProduct, decorator, eligibilities);\n            }\n            removeIneligibleDiscounts(eligibilities) {\n                this.offers = this.offers.filter(offer => {\n                    const skOffer = offer;\n                    if (skOffer.offerType === 'Default')\n                        return true;\n                    return eligibilities.isEligible(this.id, skOffer.offerType, offer.id);\n                });\n            }\n            refresh(valid, decorator, eligibilities) {\n                var _a;\n                this.raw = valid;\n                this.title = valid.title;\n                this.description = valid.description;\n                this.countryCode = valid.countryCode;\n                if (valid.group)\n                    this.group = valid.group;\n                this.removeIneligibleDiscounts(eligibilities);\n                // default offer\n                const finalPhase = {\n                    price: valid.price,\n                    priceMicros: valid.priceMicros,\n                    currency: valid.currency,\n                    billingPeriod: formatBillingPeriod(valid.billingPeriod, valid.billingPeriodUnit),\n                    paymentMode: this.type === CdvPurchase.ProductType.PAID_SUBSCRIPTION ? CdvPurchase.PaymentMode.PAY_AS_YOU_GO : CdvPurchase.PaymentMode.UP_FRONT,\n                    recurrenceMode: this.type === CdvPurchase.ProductType.PAID_SUBSCRIPTION ? CdvPurchase.RecurrenceMode.INFINITE_RECURRING : CdvPurchase.RecurrenceMode.NON_RECURRING,\n                };\n                // discounts\n                (_a = valid.discounts) === null || _a === void 0 ? void 0 : _a.forEach(discount => {\n                    if (eligibilities.isEligible(valid.id, discount.type, discount.id)) {\n                        const pricingPhases = [];\n                        const numCycles = discount.paymentMode === CdvPurchase.PaymentMode.PAY_AS_YOU_GO ? discount.period : 1;\n                        const numPeriods = discount.paymentMode === CdvPurchase.PaymentMode.PAY_AS_YOU_GO ? 1 : discount.period;\n                        const discountPhase = {\n                            price: discount.price,\n                            priceMicros: discount.priceMicros,\n                            currency: valid.currency,\n                            billingPeriod: formatBillingPeriod(numPeriods, discount.periodUnit),\n                            billingCycles: numCycles,\n                            paymentMode: discount.paymentMode,\n                            recurrenceMode: CdvPurchase.RecurrenceMode.FINITE_RECURRING,\n                        };\n                        pricingPhases.push(discountPhase);\n                        pricingPhases.push(finalPhase);\n                        this.addOffer(new SKOffer({ id: discount.id, product: this, pricingPhases, offerType: discount.type }, decorator));\n                    }\n                });\n                if (!hasIntroductoryOffer(this)) {\n                    const defaultPhases = [];\n                    // According to specs, intro price should be in the discounts array, but it turns out\n                    // it's not always the case (when there are no discount offers maybe?)...\n                    if (valid.introPrice && valid.introPriceMicros !== undefined && eligibilities.isEligible(valid.id, 'Introductory', 'intro')) {\n                        const introPrice = {\n                            price: valid.introPrice,\n                            priceMicros: valid.introPriceMicros,\n                            currency: valid.currency,\n                            billingPeriod: formatBillingPeriod(valid.introPricePeriod, valid.introPricePeriodUnit),\n                            paymentMode: valid.introPricePaymentMode,\n                            recurrenceMode: CdvPurchase.RecurrenceMode.FINITE_RECURRING,\n                            billingCycles: 1,\n                        };\n                        defaultPhases.push(introPrice);\n                    }\n                    defaultPhases.push(finalPhase);\n                    this.addOffer(new SKOffer({\n                        id: AppleAppStore.DEFAULT_OFFER_ID,\n                        product: this,\n                        pricingPhases: defaultPhases,\n                        offerType: 'Default',\n                    }, decorator));\n                }\n                function hasIntroductoryOffer(product) {\n                    return product.offers.filter(offer => {\n                        const skOffer = offer;\n                        return (skOffer.offerType === 'Introductory') || (skOffer.offerType === 'Default' && skOffer.pricingPhases.length > 1);\n                        // return (offer as SKOffer).offerType === 'Introductory';\n                    }).length > 0;\n                }\n                /**\n                 * Return ISO form of an IPeriodUnit + number of periods\n                 */\n                function formatBillingPeriod(numPeriods, period) {\n                    if (numPeriods && period)\n                        return `P${numPeriods}${period[0]}`;\n                    else\n                        return undefined;\n                }\n            }\n        }\n        AppleAppStore.SKProduct = SKProduct;\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        /**\n         * Transaction ID used for the application virtual transaction\n         */\n        AppleAppStore.APPLICATION_VIRTUAL_TRANSACTION_ID = 'appstore.application';\n        /**\n         * StoreKit 1 exposes a single receipt that contains all transactions.\n         */\n        class SKApplicationReceipt extends CdvPurchase.Receipt {\n            constructor(applicationReceipt, needApplicationReceipt, decorator) {\n                super(CdvPurchase.Platform.APPLE_APPSTORE, decorator);\n                this.nativeData = applicationReceipt;\n                this.refresh(this.nativeData, needApplicationReceipt, decorator);\n            }\n            refresh(nativeData, needApplicationReceipt, decorator) {\n                this.nativeData = nativeData;\n                if (needApplicationReceipt) {\n                    const existing = this.transactions.find(t => t.transactionId === AppleAppStore.APPLICATION_VIRTUAL_TRANSACTION_ID);\n                    if (existing) {\n                        return;\n                    }\n                    const t = new CdvPurchase.Transaction(CdvPurchase.Platform.APPLE_APPSTORE, this, decorator);\n                    t.transactionId = AppleAppStore.APPLICATION_VIRTUAL_TRANSACTION_ID;\n                    t.state = CdvPurchase.TransactionState.APPROVED;\n                    t.products.push({\n                        id: nativeData.bundleIdentifier,\n                    });\n                    this.transactions.push(t);\n                }\n            }\n        }\n        AppleAppStore.SKApplicationReceipt = SKApplicationReceipt;\n        /** StoreKit transaction */\n        class SKTransaction extends CdvPurchase.Transaction {\n            refresh(productId, originalTransactionIdentifier, transactionDate, discountId) {\n                if (productId)\n                    this.products = [{ id: productId, offerId: discountId }];\n                if (originalTransactionIdentifier)\n                    this.originalTransactionId = originalTransactionIdentifier;\n                if (transactionDate)\n                    this.purchaseDate = new Date(+transactionDate);\n            }\n        }\n        AppleAppStore.SKTransaction = SKTransaction;\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let AppleAppStore;\n    (function (AppleAppStore) {\n        let VerifyReceipt;\n        (function (VerifyReceipt) {\n            /** The reason a subscription expired.\n             * https://developer.apple.com/documentation/appstorereceipts/expiration_intent\n             */\n            let AppleExpirationIntent;\n            (function (AppleExpirationIntent) {\n                /** The customer voluntarily canceled their subscription. */\n                AppleExpirationIntent[\"CANCELED\"] = \"1\";\n                /** Billing error; for example, the customer\"s payment information was no longer valid. */\n                AppleExpirationIntent[\"BILLING_ERROR\"] = \"2\";\n                /** The customer did not agree to a recent price increase. */\n                AppleExpirationIntent[\"PRICE_INCREASE\"] = \"3\";\n                /** The product was not available for purchase at the time of renewal. */\n                AppleExpirationIntent[\"PRODUCT_NOT_AVAILABLE\"] = \"4\";\n                /** Unknown error. */\n                AppleExpirationIntent[\"UNKNOWN\"] = \"5\";\n            })(AppleExpirationIntent = VerifyReceipt.AppleExpirationIntent || (VerifyReceipt.AppleExpirationIntent = {}));\n        })(VerifyReceipt = AppleAppStore.VerifyReceipt || (AppleAppStore.VerifyReceipt = {}));\n    })(AppleAppStore = CdvPurchase.AppleAppStore || (CdvPurchase.AppleAppStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        // export type Nonce = {\n        //     type: PaymentMethod.THREE_D_SECURE;\n        //     value: string;\n        // };\n        // export type NonceProvider = (type: PaymentMethod, callback: Callback<Nonce | IError>) => void;\n        // export enum PaymentMethod {\n        //     THREE_D_SECURE = 'THREE_D_SECURE',\n        // }\n        class BraintreeReceipt extends CdvPurchase.Receipt {\n            constructor(paymentRequest, dropInResult, decorator) {\n                // Now we have to send this to the server + the request\n                // result.paymentDescription; // \"1111\"\n                // result.paymentMethodType; // \"VISA\"\n                // result.deviceData; // undefined\n                // result.paymentMethodNonce; // {\"isDefault\":false,\"nonce\":\"tokencc_bh_rdjmsc_76vjtq_9tzsv3_4467mg_tt4\"}\n                var _a, _b, _c;\n                super(CdvPurchase.Platform.BRAINTREE, decorator);\n                const transaction = new CdvPurchase.Transaction(CdvPurchase.Platform.BRAINTREE, this, decorator);\n                transaction.purchaseDate = new Date();\n                transaction.products = ((_a = paymentRequest.items) === null || _a === void 0 ? void 0 : _a.filter(p => p).map(product => ({ id: (product === null || product === void 0 ? void 0 : product.id) || '' }))) || [];\n                transaction.state = CdvPurchase.TransactionState.APPROVED;\n                transaction.transactionId = (_c = (_b = dropInResult.paymentMethodNonce) === null || _b === void 0 ? void 0 : _b.nonce) !== null && _c !== void 0 ? _c : `UNKNOWN_${dropInResult.paymentMethodType}_${dropInResult.paymentDescription}`;\n                this.transactions = [transaction];\n                this.dropInResult = dropInResult;\n                this.paymentRequest = paymentRequest;\n                this.refresh(paymentRequest, dropInResult, decorator);\n            }\n            refresh(paymentRequest, dropInResult, decorator) {\n                var _a, _b;\n                this.dropInResult = dropInResult;\n                this.paymentRequest = paymentRequest;\n                const transaction = new CdvPurchase.Transaction(CdvPurchase.Platform.BRAINTREE, this, decorator);\n                transaction.products = paymentRequest.items.filter(p => p).map(product => ({ id: (product === null || product === void 0 ? void 0 : product.id) || '' }));\n                transaction.state = CdvPurchase.TransactionState.APPROVED;\n                transaction.transactionId = (_b = (_a = dropInResult.paymentMethodNonce) === null || _a === void 0 ? void 0 : _a.nonce) !== null && _b !== void 0 ? _b : `UNKNOWN_${dropInResult.paymentMethodType}_${dropInResult.paymentDescription}`;\n                transaction.amountMicros = paymentRequest.amountMicros;\n                transaction.currency = paymentRequest.currency;\n                this.transactions = [transaction];\n            }\n        }\n        Braintree.BraintreeReceipt = BraintreeReceipt;\n        class Adapter {\n            constructor(context, options) {\n                this.id = CdvPurchase.Platform.BRAINTREE;\n                this.name = 'BrainTree';\n                this.ready = false;\n                this.products = [];\n                this._receipts = [];\n                this.supportsParallelLoading = false;\n                this.context = context;\n                this.log = context.log.child(\"Braintree\");\n                this.options = options;\n            }\n            get receipts() { return this._receipts; }\n            get isSupported() {\n                return Braintree.IosBridge.Bridge.isSupported() || Braintree.AndroidBridge.Bridge.isSupported();\n            }\n            /**\n             * Initialize the Braintree Adapter.\n             */\n            initialize() {\n                return new Promise(resolve => {\n                    this.log.info(\"initialize()\");\n                    if (Braintree.IosBridge.Bridge.isSupported()) {\n                        this.log.info(\"instantiating ios bridge...\");\n                        this.iosBridge = new Braintree.IosBridge.Bridge(this.log, (callback) => {\n                            if (this.options.tokenizationKey)\n                                callback(this.options.tokenizationKey);\n                            else if (this.options.clientTokenProvider)\n                                this.options.clientTokenProvider(callback);\n                            else\n                                callback(braintreeError(CdvPurchase.ErrorCode.CLIENT_INVALID, 'Braintree iOS Bridge requires a clientTokenProvider or tokenizationKey'));\n                        }, this.options.applePay);\n                        this.iosBridge.initialize(this.context, resolve);\n                    }\n                    else if (Braintree.AndroidBridge.Bridge.isSupported() && !this.androidBridge) {\n                        this.log.info(\"instantiating android bridge...\");\n                        this.androidBridge = new Braintree.AndroidBridge.Bridge(this.log);\n                        this.log.info(\"calling android bridge -> initialize...\");\n                        const auth = this.options.tokenizationKey\n                            ? this.options.tokenizationKey\n                            : this.options.clientTokenProvider\n                                ? this.options.clientTokenProvider\n                                : '';\n                        this.androidBridge.initialize(auth, resolve);\n                    }\n                    else {\n                        this.log.info(\"platform not supported...\");\n                        resolve(undefined);\n                    }\n                    this.context.listener.receiptsReady(CdvPurchase.Platform.BRAINTREE);\n                });\n            }\n            loadProducts(products) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return products.map(p => braintreeError(CdvPurchase.ErrorCode.PRODUCT_NOT_AVAILABLE, 'N/A'));\n                });\n            }\n            loadReceipts() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.context.listener.receiptsReady(CdvPurchase.Platform.BRAINTREE);\n                    return [];\n                });\n            }\n            order(offer) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return braintreeError(CdvPurchase.ErrorCode.UNKNOWN, 'N/A: Not implemented with Braintree');\n                });\n            }\n            finish(transaction) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    transaction.state = CdvPurchase.TransactionState.FINISHED;\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.TEST, [transaction.parentReceipt]);\n                    return;\n                });\n            }\n            manageSubscriptions() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.info('N/A: manageSubscriptions() is not available with Braintree');\n                    return;\n                });\n            }\n            manageBilling() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.info('N/A: manageBilling() is not available with Braintree');\n                    return;\n                });\n            }\n            // async getNonce(paymentMethod: PaymentMethod): Promise<Nonce | IError> {\n            //     return new Promise(resolve => {\n            //         if (this.options.nonceProvider) {\n            //             this.options.nonceProvider(paymentMethod, resolve);\n            //         }\n            //         else {\n            //             resolve({\n            //                 code: ErrorCode.UNAUTHORIZED_REQUEST_DATA,\n            //                 message: 'Braintree requires a nonceProvider',\n            //             });\n            //         }\n            //     });\n            // }\n            launchDropIn(paymentRequest, dropInRequest) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (this.androidBridge)\n                        return this.androidBridge.launchDropIn(dropInRequest);\n                    if (this.iosBridge)\n                        return this.iosBridge.launchDropIn(paymentRequest, dropInRequest);\n                    return braintreeError(CdvPurchase.ErrorCode.PURCHASE, 'Braintree is not available');\n                });\n            }\n            requestPayment(paymentRequest, additionalData) {\n                var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.info(\"requestPayment()\" + JSON.stringify(paymentRequest));\n                    const dropInRequest = ((_a = additionalData === null || additionalData === void 0 ? void 0 : additionalData.braintree) === null || _a === void 0 ? void 0 : _a.dropInRequest) || {};\n                    // Apple Pay\n                    if (!(yield Braintree.IosBridge.ApplePayPlugin.isSupported(this.log))) {\n                        this.log.info(\"Apple Pay is not supported.\");\n                        dropInRequest.applePayDisabled = true;\n                    }\n                    // Google Pay\n                    if (this.options.googlePay || dropInRequest.googlePayRequest) {\n                        const googlePay = Object.assign(Object.assign({}, ((_b = this.options.googlePay) !== null && _b !== void 0 ? _b : {})), ((_c = dropInRequest.googlePayRequest) !== null && _c !== void 0 ? _c : {}));\n                        if (!googlePay.transactionInfo) {\n                            googlePay.transactionInfo = {\n                                currencyCode: ((_d = paymentRequest.currency) !== null && _d !== void 0 ? _d : ''),\n                                totalPrice: ((_e = paymentRequest.amountMicros) !== null && _e !== void 0 ? _e : 0) / 1000000,\n                                totalPriceStatus: Braintree.GooglePay.TotalPriceStatus.FINAL,\n                            };\n                        }\n                        dropInRequest.googlePayRequest = googlePay;\n                    }\n                    // 3DS\n                    if (this.options.threeDSecure || dropInRequest.threeDSecureRequest) {\n                        const threeDS = Object.assign(Object.assign({}, ((_f = this.options.threeDSecure) !== null && _f !== void 0 ? _f : {})), ((_g = dropInRequest.threeDSecureRequest) !== null && _g !== void 0 ? _g : {}));\n                        if (!threeDS.amount) {\n                            threeDS.amount = asDecimalString((_h = paymentRequest.amountMicros) !== null && _h !== void 0 ? _h : 0);\n                        }\n                        if (!threeDS.billingAddress && paymentRequest.billingAddress) {\n                            threeDS.billingAddress = {\n                                givenName: paymentRequest.billingAddress.givenName,\n                                surname: paymentRequest.billingAddress.surname,\n                                countryCodeAlpha2: paymentRequest.billingAddress.countryCode,\n                                postalCode: paymentRequest.billingAddress.postalCode,\n                                locality: paymentRequest.billingAddress.locality,\n                                streetAddress: paymentRequest.billingAddress.streetAddress1,\n                                extendedAddress: paymentRequest.billingAddress.streetAddress2,\n                                line3: paymentRequest.billingAddress.streetAddress3,\n                                phoneNumber: paymentRequest.billingAddress.phoneNumber,\n                                region: paymentRequest.billingAddress.region,\n                            };\n                        }\n                        if (!threeDS.email) {\n                            threeDS.email = paymentRequest.email;\n                        }\n                        dropInRequest.threeDSecureRequest = threeDS;\n                    }\n                    const response = yield this.launchDropIn(paymentRequest, dropInRequest);\n                    if (!dropInResponseIsOK(response))\n                        return dropInResponseError(this.log, response);\n                    const dropInResult = response;\n                    this.log.info(\"launchDropIn success: \" + JSON.stringify({ paymentRequest, dropInResult }));\n                    if (!((_j = dropInResult.paymentMethodNonce) === null || _j === void 0 ? void 0 : _j.nonce)) {\n                        return braintreeError(CdvPurchase.ErrorCode.BAD_RESPONSE, 'launchDropIn returned no paymentMethodNonce');\n                    }\n                    let receipt = this._receipts.find(r => { var _a, _b; return ((_a = r.dropInResult.paymentMethodNonce) === null || _a === void 0 ? void 0 : _a.nonce) === ((_b = dropInResult.paymentMethodNonce) === null || _b === void 0 ? void 0 : _b.nonce); });\n                    if (receipt) {\n                        receipt.refresh(paymentRequest, dropInResult, this.context.apiDecorators);\n                    }\n                    else {\n                        receipt = new BraintreeReceipt(paymentRequest, dropInResult, this.context.apiDecorators);\n                        this.receipts.push(receipt);\n                    }\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.BRAINTREE, [receipt]);\n                    return receipt.transactions[0];\n                });\n            }\n            receiptValidationBody(receipt) {\n                var _a, _b, _c, _d, _e;\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (!isBraintreeReceipt(receipt)) {\n                        this.log.error(\"Unexpected error, expecting a BraintreeReceipt: \" + JSON.stringify(receipt));\n                        return;\n                    }\n                    this.log.info(\"create receiptValidationBody for: \" + JSON.stringify(receipt));\n                    return {\n                        id: (_c = (_b = (_a = receipt.paymentRequest.items) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : 'unknown',\n                        type: CdvPurchase.ProductType.CONSUMABLE,\n                        priceMicros: receipt.paymentRequest.amountMicros,\n                        currency: receipt.paymentRequest.currency,\n                        products: [],\n                        transaction: {\n                            type: CdvPurchase.Platform.BRAINTREE,\n                            deviceData: receipt.dropInResult.deviceData,\n                            id: 'nonce',\n                            paymentMethodNonce: (_e = (_d = receipt.dropInResult.paymentMethodNonce) === null || _d === void 0 ? void 0 : _d.nonce) !== null && _e !== void 0 ? _e : '',\n                            paymentDescription: receipt.dropInResult.paymentDescription,\n                            paymentMethodType: receipt.dropInResult.paymentMethodType,\n                        }\n                    };\n                });\n            }\n            /**\n             * Handle a response from a receipt validation process.\n             *\n             * @param receipt The receipt being validated.\n             * @param response The response payload from the receipt validation process.\n             * @returns A promise that resolves when the response has been handled.\n             */\n            handleReceiptValidationResponse(receipt, response) {\n                var _a;\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.info(\"receipt validation response: \" + JSON.stringify(response));\n                    if ((response === null || response === void 0 ? void 0 : response.data) && ('transaction' in response.data)) {\n                        if (response.data.transaction.type === 'braintree') {\n                            const lCustomerId = (_a = response.data.transaction.data.transaction) === null || _a === void 0 ? void 0 : _a.customer.id;\n                            if (lCustomerId && !Braintree.customerId) {\n                                this.log.info(\"customerId updated: \" + lCustomerId);\n                                Braintree.customerId = lCustomerId;\n                            }\n                        }\n                    }\n                });\n            }\n            checkSupport(functionality) {\n                return functionality === 'requestPayment';\n            }\n            restorePurchases() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return undefined;\n                });\n            }\n        }\n        Braintree.Adapter = Adapter;\n        function asDecimalString(amountMicros) {\n            const amountCents = '' + (amountMicros / 10000);\n            return (amountCents.slice(0, -2) || '0') + '.' + (amountCents.slice(-2, -1) || '0') + (amountCents.slice(-1) || '0');\n        }\n        function isBraintreeReceipt(receipt) {\n            return receipt.platform === CdvPurchase.Platform.BRAINTREE;\n        }\n        const dropInResponseIsOK = (response) => {\n            return (!!response) && !('code' in response && 'message' in response);\n        };\n        /**\n         * Returns the error response from Drop In\n         *\n         * If the \"error\" is that the user cancelled the payment, then returns undefined\n         * (as per the specification for requestPayment)\n         */\n        const dropInResponseError = (log, response) => {\n            if (!response) {\n                log.warn(\"launchDropIn failed: no response\");\n                return braintreeError(CdvPurchase.ErrorCode.BAD_RESPONSE, 'Braintree failed to launch drop in');\n            }\n            else {\n                // Failed\n                if (response.code === CdvPurchase.ErrorCode.PAYMENT_CANCELLED) {\n                    log.info(\"User cancelled the payment request\");\n                    return undefined;\n                }\n                log.warn(\"launchDropIn failed: \" + JSON.stringify(response));\n                return response;\n            }\n        };\n        function braintreeError(code, message) {\n            return CdvPurchase.storeError(code, message, CdvPurchase.Platform.BRAINTREE, null);\n        }\n        Braintree.braintreeError = braintreeError;\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        /**\n         * Cordova plugin ID for the braintree plugin.\n         */\n        const PLUGIN_ID = 'BraintreePlugin';\n        let AndroidBridge;\n        (function (AndroidBridge) {\n            /**\n             * Bridge to access native functions.\n             *\n             * This tries to export pretty raw functions from the underlying native SDKs.\n             */\n            class Bridge {\n                constructor(log) {\n                    this.log = log.child(\"AndroidBridge\");\n                }\n                /** Receive asynchronous messages from the native side */\n                listener(msg) {\n                    // Handle changes to purchase that are being notified\n                    // through the PurchasesUpdatedListener on the native side (android)\n                    this.log.debug('listener: ' + JSON.stringify(msg));\n                    if (!msg || !msg.type) {\n                        return;\n                    }\n                    if (msg.type === \"getClientToken\") {\n                        this.getClientToken();\n                    }\n                    else if (msg.type === \"ready\") {\n                    }\n                }\n                // Braintree reported an error\n                // private onError(message: string) {\n                //     this.log.warn(\"Braintree reported an error: \" + message);\n                //     // TODO - bubble that up to the client\n                // }\n                /*\n                 * Initialize the braintree client.\n                 *\n                 * @param clientTokenProvider Provide clientTokens to the SDK when it needs them.\n                 */\n                initialize(clientTokenProvider, callback) {\n                    try {\n                        // Set a listener (see \"listener()\" function above)\n                        if (typeof clientTokenProvider === 'string') {\n                            const token = clientTokenProvider;\n                            this.clientTokenProvider = (callback) => { callback(token); };\n                        }\n                        else {\n                            this.clientTokenProvider = clientTokenProvider;\n                        }\n                        this.log.info(\"exec.setListener()\");\n                        const listener = this.listener.bind(this);\n                        window.cordova.exec(listener, null, PLUGIN_ID, \"setListener\", []);\n                        callback(undefined);\n                    }\n                    catch (err) {\n                        this.log.warn(\"initialization failed: \" + (err === null || err === void 0 ? void 0 : err.message));\n                        callback(Braintree.braintreeError(CdvPurchase.ErrorCode.SETUP, 'Failed to initialize Braintree Android Bridge: ' + (err === null || err === void 0 ? void 0 : err.message)));\n                    }\n                }\n                /**\n                 * Fetches a client token and sends it to the SDK.\n                 *\n                 * This method is called by the native side when the SDK requests a Client Token.\n                 */\n                getClientToken() {\n                    this.log.info(\"getClientToken()\");\n                    if (this.clientTokenProvider) {\n                        this.log.debug(\"clientTokenProvider set, calling.\");\n                        this.clientTokenProvider((value) => {\n                            if (typeof value === 'string') {\n                                window.cordova.exec(null, null, PLUGIN_ID, \"onClientTokenSuccess\", [value]);\n                            }\n                            else {\n                                window.cordova.exec(null, null, PLUGIN_ID, \"onClientTokenFailure\", [value.code, value.message]);\n                            }\n                        });\n                    }\n                    else {\n                        this.log.debug(\"clientTokenProvider not set, retrying later...\");\n                        setTimeout(() => this.getClientToken(), 1000); // retry after 1s (over and over)\n                    }\n                }\n                /** Returns true on Android, the only platform supported by this Braintree bridge */\n                static isSupported() {\n                    return CdvPurchase.Utils.platformId() === 'android';\n                }\n                isApplePaySupported() {\n                    return __awaiter(this, void 0, void 0, function* () {\n                        return false;\n                    });\n                }\n                launchDropIn(dropInRequest) {\n                    return new Promise(resolve => {\n                        window.cordova.exec((result) => {\n                            this.log.info(\"dropInSuccess: \" + JSON.stringify(result));\n                            resolve(result);\n                        }, (err) => {\n                            this.log.info(\"dropInFailure: \" + err);\n                            const errCode = err.split(\"|\")[0];\n                            const errMessage = err.split(\"|\").slice(1).join('');\n                            if (errCode === \"UserCanceledException\") {\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.PAYMENT_CANCELLED, errMessage));\n                            }\n                            else if (errCode === \"AuthorizationException\") {\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.UNAUTHORIZED_REQUEST_DATA, errMessage));\n                            }\n                            else {\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.UNKNOWN, err));\n                            }\n                        }, PLUGIN_ID, \"launchDropIn\", [dropInRequest]);\n                    });\n                }\n            }\n            AndroidBridge.Bridge = Bridge;\n            // /**\n            //  * Successful callback result for the presentDropInPaymentUI method.\n            //  */\n            // interface PaymentUIResult {\n            //     /**\n            //      * Indicates if the user used the cancel button to close the dialog without\n            //      * completing the payment.\n            //      */\n            //     userCancelled: boolean;\n            //     /**\n            //      * The nonce for the payment transaction (if a payment was completed).\n            //      */\n            //     nonce: string;\n            //     /**\n            //      * The payment type (if a payment was completed).\n            //      */\n            //     type: string;\n            //     /**\n            //      * A description of the payment method (if a payment was completed).\n            //      */\n            //     localizedDescription: string;\n            //     /**\n            //      * Information about the credit card used to complete a payment (if a credit card was used).\n            //      */\n            //     card: {\n            //         /**\n            //          * The last two digits of the credit card used.\n            //          */\n            //         lastTwo: string;\n            //         /**\n            //          * An enumerated value used to indicate the type of credit card used.\n            //          *\n            //          * Can be one of the following values:\n            //          *\n            //          * BTCardNetworkUnknown\n            //          * BTCardNetworkAMEX\n            //          * BTCardNetworkDinersClub\n            //          * BTCardNetworkDiscover\n            //          * BTCardNetworkMasterCard\n            //          * BTCardNetworkVisa\n            //          * BTCardNetworkJCB\n            //          * BTCardNetworkLaser\n            //          * BTCardNetworkMaestro\n            //          * BTCardNetworkUnionPay\n            //          * BTCardNetworkSolo\n            //          * BTCardNetworkSwitch\n            //          * BTCardNetworkUKMaestro\n            //          */\n            //         network: string;\n            //     };\n            //     /**\n            //      * Information about the PayPal account used to complete a payment (if a PayPal account was used).\n            //      */\n            //     payPalAccount: {\n            //         email: string;\n            //         firstName: string;\n            //         lastName: string;\n            //         phone: string;\n            //         billingAddress: string;\n            //         shippingAddress: string;\n            //         clientMetadataId: string;\n            //         payerId: string;\n            //     };\n            //     /**\n            //      * Information about the Apple Pay card used to complete a payment (if Apple Pay was used).\n            //      */\n            //     applePaycard: {\n            //     };\n            //     /**\n            //      * Information about 3D Secure card used to complete a payment (if 3D Secure was used).\n            //      */\n            //     threeDSecureInfo: {\n            //         liabilityShifted: boolean;\n            //         liabilityShiftPossible: boolean;\n            //     };\n            //     /**\n            //      * Information about Venmo account used to complete a payment (if a Venmo account was used).\n            //      */\n            //     venmoAccount: {\n            //         username: string;\n            //     };\n            // }\n        })(AndroidBridge = Braintree.AndroidBridge || (Braintree.AndroidBridge = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        let IosBridge;\n        (function (IosBridge) {\n            /**\n             * Cordova plugin ID for the braintree-applepay plugin.\n             */\n            const PLUGIN_ID = 'BraintreeApplePayPlugin';\n            /**\n             * Bridge to the cordova-plugin-purchase-braintree-applepay plugin\n             */\n            class ApplePayPlugin {\n                /**\n                 * Retrieve the plugin definition.\n                 *\n                 * Useful to check if it is installed.\n                 */\n                static get() {\n                    return window.CdvPurchaseBraintreeApplePay;\n                }\n                /**\n                 * Initiate a payment with Apple Pay.\n                 */\n                static requestPayment(request) {\n                    return new Promise(resolve => {\n                        var _a;\n                        if (!((_a = ApplePayPlugin.get()) === null || _a === void 0 ? void 0 : _a.installed)) {\n                            return resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.SETUP, 'cordova-plugin-purchase-braintree-applepay does not appear to be installed.'));\n                        }\n                        else {\n                            const success = (result) => {\n                                resolve(result);\n                            };\n                            const failure = (err) => {\n                                const message = err !== null && err !== void 0 ? err : 'payment request failed';\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.PURCHASE, 'Braintree+ApplePay ERROR: ' + message));\n                            };\n                            window.cordova.exec(success, failure, PLUGIN_ID, 'presentDropInPaymentUI', [request]);\n                        }\n                    });\n                }\n                /**\n                 * Returns true if the device supports Apple Pay.\n                 *\n                 * This does not necessarily mean the user has a card setup already.\n                 */\n                static isSupported(log) {\n                    return new Promise(resolve => {\n                        var _a;\n                        if (CdvPurchase.Utils.platformId() !== 'ios') {\n                            log.info('BraintreeApplePayPlugin is only available for ios.');\n                            return resolve(false);\n                        }\n                        if (!((_a = ApplePayPlugin.get()) === null || _a === void 0 ? void 0 : _a.installed)) {\n                            log.info('BraintreeApplePayPlugin does not appear to be installed.');\n                            return resolve(false);\n                        }\n                        try {\n                            window.cordova.exec((result) => {\n                                resolve(result);\n                            }, () => {\n                                log.info('BraintreeApplePayPlugin is not available.');\n                                resolve(false);\n                            }, PLUGIN_ID, \"isApplePaySupported\", []);\n                        }\n                        catch (err) {\n                            log.info('BraintreeApplePayPlugin is not installed.');\n                            resolve(false);\n                        }\n                    });\n                }\n            }\n            IosBridge.ApplePayPlugin = ApplePayPlugin;\n        })(IosBridge = Braintree.IosBridge || (Braintree.IosBridge = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        /**\n         * Cordova plugin ID for the braintree ios plugin.\n         */\n        const PLUGIN_ID = 'BraintreePlugin';\n        let IosBridge;\n        (function (IosBridge) {\n            class Bridge {\n                constructor(log, clientTokenProvider, applePayOptions) {\n                    this.log = log.child(\"IosBridge\");\n                    this.clientTokenProvider = clientTokenProvider;\n                    this.applePayOptions = applePayOptions;\n                }\n                initialize(verbosity, callback) {\n                    window.cordova.exec(null, null, \"BraintreePlugin\", \"setVerbosity\", [verbosity.verbosity]);\n                    window.cordova.exec(message => this.log.debug('(Native) ' + message), null, \"BraintreePlugin\", \"setLogger\", []);\n                    setTimeout(() => callback(undefined), 0);\n                }\n                continueDropInForApplePay(paymentRequest, DropInRequest, dropInResult) {\n                    var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n                    return __awaiter(this, void 0, void 0, function* () {\n                        const request = ((_b = (_a = this.applePayOptions) === null || _a === void 0 ? void 0 : _a.preparePaymentRequest) === null || _b === void 0 ? void 0 : _b.call(_a, paymentRequest)) || {\n                            merchantCapabilities: [CdvPurchase.ApplePay.MerchantCapability.ThreeDS],\n                        };\n                        if (!request.paymentSummaryItems) {\n                            const items = paymentRequest.items.filter(p => p).map((product, index) => {\n                                var _a, _b, _c;\n                                return ({\n                                    type: 'final',\n                                    label: (product === null || product === void 0 ? void 0 : product.title) || (product === null || product === void 0 ? void 0 : product.id) || `Item #${index + 1}`,\n                                    amount: `${Math.round(((_c = (_b = (_a = product === null || product === void 0 ? void 0 : product.pricing) === null || _a === void 0 ? void 0 : _a.priceMicros) !== null && _b !== void 0 ? _b : paymentRequest.amountMicros) !== null && _c !== void 0 ? _c : 0) / 10000) / 100}`,\n                                });\n                            });\n                            const total = {\n                                type: 'final',\n                                label: (_d = (_c = this.applePayOptions) === null || _c === void 0 ? void 0 : _c.companyName) !== null && _d !== void 0 ? _d : 'Total',\n                                amount: `${Math.round(((_e = paymentRequest.amountMicros) !== null && _e !== void 0 ? _e : 0) / 10000) / 100}`,\n                            };\n                            request.paymentSummaryItems = [...items, total];\n                        }\n                        const result = yield IosBridge.ApplePayPlugin.requestPayment(request);\n                        this.log.info('Result from Apple Pay: ' + JSON.stringify(result));\n                        if ('isError' in result)\n                            return result;\n                        if (result.userCancelled) {\n                            return Braintree.braintreeError(CdvPurchase.ErrorCode.PAYMENT_CANCELLED, 'User cancelled the payment request');\n                        }\n                        return {\n                            paymentMethodNonce: {\n                                isDefault: false,\n                                nonce: (_g = (_f = result.applePayCardNonce) === null || _f === void 0 ? void 0 : _f.nonce) !== null && _g !== void 0 ? _g : '',\n                                type: (_j = (_h = result.applePayCardNonce) === null || _h === void 0 ? void 0 : _h.type) !== null && _j !== void 0 ? _j : '',\n                            },\n                            paymentMethodType: dropInResult.paymentMethodType,\n                            deviceData: dropInResult.deviceData,\n                            paymentDescription: dropInResult.paymentDescription,\n                        };\n                    });\n                }\n                launchDropIn(paymentRequest, dropInRequest) {\n                    return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n                        const onSuccess = (result) => {\n                            this.log.info(\"dropInSuccess: \" + JSON.stringify(result));\n                            if (result.paymentMethodType === Braintree.DropIn.PaymentMethod.APPLE_PAY) {\n                                this.log.info(\"it's an ApplePay request, we have to process it.\");\n                                this.continueDropInForApplePay(paymentRequest, dropInRequest, result).then(resolve);\n                            }\n                            else {\n                                resolve(result);\n                            }\n                        };\n                        const onError = (errorString) => {\n                            this.log.info(\"dropInFailure: \" + errorString);\n                            const [errCode, errMessage] = errorString.split('|');\n                            if (errCode === \"UserCanceledException\") {\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.PAYMENT_CANCELLED, errMessage));\n                            }\n                            else {\n                                resolve(Braintree.braintreeError(CdvPurchase.ErrorCode.UNKNOWN, 'ERROR ' + errCode + ': ' + errMessage));\n                            }\n                        };\n                        this.clientTokenProvider((clientToken) => {\n                            if (typeof clientToken === 'string')\n                                window.cordova.exec(onSuccess, onError, \"BraintreePlugin\", \"launchDropIn\", [clientToken, dropInRequest]);\n                            else // failed to get token\n                                resolve(clientToken);\n                        });\n                    }));\n                }\n                braintreePlugin() {\n                    return window.CdvPurchaseBraintree;\n                }\n                static isSupported() {\n                    return CdvPurchase.Utils.platformId() === 'ios';\n                }\n            }\n            IosBridge.Bridge = Bridge;\n        })(IosBridge = Braintree.IosBridge || (Braintree.IosBridge = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        let DropIn;\n        (function (DropIn) {\n            /** How a field will behave in CardForm. */\n            let CardFormFieldStatus;\n            (function (CardFormFieldStatus) {\n                CardFormFieldStatus[CardFormFieldStatus[\"DISABLED\"] = 0] = \"DISABLED\";\n                CardFormFieldStatus[CardFormFieldStatus[\"OPTIONAL\"] = 1] = \"OPTIONAL\";\n                CardFormFieldStatus[CardFormFieldStatus[\"REQUIRED\"] = 2] = \"REQUIRED\";\n            })(CardFormFieldStatus = DropIn.CardFormFieldStatus || (DropIn.CardFormFieldStatus = {}));\n        })(DropIn = Braintree.DropIn || (Braintree.DropIn = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        let DropIn;\n        (function (DropIn) {\n            /** Payment method used or selected by the user. */\n            let PaymentMethod;\n            (function (PaymentMethod) {\n                /** Google only */\n                PaymentMethod[\"GOOGLE_PAY\"] = \"GOOGLE_PAY\";\n                /** ios only */\n                PaymentMethod[\"LASER\"] = \"LASER\";\n                /** ios only */\n                PaymentMethod[\"UK_MAESTRO\"] = \"UK_MAESTRO\";\n                /** ios only */\n                PaymentMethod[\"SWITCH\"] = \"SWITCH\";\n                /** ios only */\n                PaymentMethod[\"SOLOR\"] = \"SOLO\";\n                /** ios only */\n                PaymentMethod[\"APPLE_PAY\"] = \"APPLE_PAY\";\n                PaymentMethod[\"AMEX\"] = \"AMEX\";\n                PaymentMethod[\"DINERS_CLUB\"] = \"DINERS_CLUB\";\n                PaymentMethod[\"DISCOVER\"] = \"DISCOVER\";\n                PaymentMethod[\"JCB\"] = \"JCB\";\n                PaymentMethod[\"MAESTRO\"] = \"MAESTRO\";\n                PaymentMethod[\"MASTERCARD\"] = \"MASTERCARD\";\n                PaymentMethod[\"PAYPAL\"] = \"PAYPAL\";\n                PaymentMethod[\"VISA\"] = \"VISA\";\n                PaymentMethod[\"VENMO\"] = \"VENMO\";\n                PaymentMethod[\"UNIONPAY\"] = \"UNIONPAY\";\n                PaymentMethod[\"HIPER\"] = \"HIPER\";\n                PaymentMethod[\"HIPERCARD\"] = \"HIPERCARD\";\n                PaymentMethod[\"UNKNOWN\"] = \"UNKNOWN\";\n            })(PaymentMethod = DropIn.PaymentMethod || (DropIn.PaymentMethod = {}));\n        })(DropIn = Braintree.DropIn || (Braintree.DropIn = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        let GooglePay;\n        (function (GooglePay) {\n            /**\n             * The Google Pay API will collect the billing address for you if required\n             */\n            let BillingAddressFormat;\n            (function (BillingAddressFormat) {\n                /**\n                 * When this format is used, the billing address returned will only contain the minimal info, including name, country code, and postal code.\n                 *\n                 * Note that some countries do not use postal codes, so the postal code field will be empty in those countries.\n                 */\n                BillingAddressFormat[BillingAddressFormat[\"MIN\"] = 0] = \"MIN\";\n                /**\n                 * When this format is used, the billing address returned will be the full address.\n                 *\n                 * Only select this format when it's required to process the order since it can increase friction during the checkout process and can lead to a lower conversion rate.\n                 */\n                BillingAddressFormat[BillingAddressFormat[\"FULL\"] = 1] = \"FULL\";\n            })(BillingAddressFormat = GooglePay.BillingAddressFormat || (GooglePay.BillingAddressFormat = {}));\n            /**\n             * This enum represents the status of the total price of a transaction.\n             *\n             * It can take on one of the following values:\n             * - TotalPriceStatus.NOT_CURRENTLY_KNOWN: The total price is not currently known.\n             * - TotalPriceStatus.ESTIMATED: The total price is an estimate.\n             * - TotalPriceStatus.FINAL: The total price is final.\n             */\n            let TotalPriceStatus;\n            (function (TotalPriceStatus) {\n                /** The total price is not currently known. */\n                TotalPriceStatus[TotalPriceStatus[\"NOT_CURRENTLY_KNOWN\"] = 1] = \"NOT_CURRENTLY_KNOWN\";\n                /** The total price is an estimate. */\n                TotalPriceStatus[TotalPriceStatus[\"ESTIMATED\"] = 2] = \"ESTIMATED\";\n                /** The total price is final. */\n                TotalPriceStatus[TotalPriceStatus[\"FINAL\"] = 3] = \"FINAL\";\n            })(TotalPriceStatus = GooglePay.TotalPriceStatus || (GooglePay.TotalPriceStatus = {}));\n        })(GooglePay = Braintree.GooglePay || (Braintree.GooglePay = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Braintree;\n    (function (Braintree) {\n        let ThreeDSecure;\n        (function (ThreeDSecure) {\n            /** The account type */\n            let AccountType;\n            (function (AccountType) {\n                AccountType[\"UNSPECIFIED\"] = \"00\";\n                AccountType[\"CREDIT\"] = \"01\";\n                AccountType[\"DEBIT\"] = \"02\";\n            })(AccountType = ThreeDSecure.AccountType || (ThreeDSecure.AccountType = {}));\n            /** The shipping method */\n            let ShippingMethod;\n            (function (ShippingMethod) {\n                /** Unspecified */\n                ShippingMethod[ShippingMethod[\"UNSPECIFIED\"] = 0] = \"UNSPECIFIED\";\n                /** Same say */\n                ShippingMethod[ShippingMethod[\"SAME_DAY\"] = 1] = \"SAME_DAY\";\n                /** Overnight / Expedited */\n                ShippingMethod[ShippingMethod[\"EXPEDITED\"] = 2] = \"EXPEDITED\";\n                /** Priority */\n                ShippingMethod[ShippingMethod[\"PRIORITY\"] = 3] = \"PRIORITY\";\n                /** Ground */\n                ShippingMethod[ShippingMethod[\"GROUND\"] = 4] = \"GROUND\";\n                /** Electronic delivery */\n                ShippingMethod[ShippingMethod[\"ELECTRONIC_DELIVERY\"] = 5] = \"ELECTRONIC_DELIVERY\";\n                /** Ship to store */\n                ShippingMethod[ShippingMethod[\"SHIP_TO_STORE\"] = 6] = \"SHIP_TO_STORE\";\n            })(ShippingMethod = ThreeDSecure.ShippingMethod || (ThreeDSecure.ShippingMethod = {}));\n            let Version;\n            (function (Version) {\n                /** 3DS 1.0 */\n                Version[Version[\"V1\"] = 0] = \"V1\";\n                /** 3DS 2.0 */\n                Version[Version[\"V2\"] = 1] = \"V2\";\n            })(Version = ThreeDSecure.Version || (ThreeDSecure.Version = {}));\n        })(ThreeDSecure = Braintree.ThreeDSecure || (Braintree.ThreeDSecure = {}));\n    })(Braintree = CdvPurchase.Braintree || (CdvPurchase.Braintree = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"../../receipt.ts\" />\n/// <reference path=\"../../transaction.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let GooglePlay;\n    (function (GooglePlay) {\n        class Transaction extends CdvPurchase.Transaction {\n            constructor(purchase, parentReceipt, decorator) {\n                super(CdvPurchase.Platform.GOOGLE_PLAY, parentReceipt, decorator);\n                this.nativePurchase = purchase;\n                this.refresh(purchase, true);\n            }\n            static toState(fromConstructor, state, isAcknowledged, isConsumed) {\n                switch (state) {\n                    case GooglePlay.Bridge.PurchaseState.PENDING:\n                        return CdvPurchase.TransactionState.INITIATED;\n                    case GooglePlay.Bridge.PurchaseState.PURCHASED:\n                        // Note: we still want to validate acknowledged non-consumables and subscriptions,\n                        //       so we don't return APPROVED\n                        if (isConsumed)\n                            return CdvPurchase.TransactionState.FINISHED;\n                        else if (isAcknowledged)\n                            return CdvPurchase.TransactionState.APPROVED;\n                        else if (fromConstructor)\n                            return CdvPurchase.TransactionState.INITIATED;\n                        else\n                            return CdvPurchase.TransactionState.APPROVED;\n                    case GooglePlay.Bridge.PurchaseState.UNSPECIFIED_STATE:\n                        return CdvPurchase.TransactionState.UNKNOWN_STATE;\n                }\n            }\n            /**\n             * Refresh the value in the transaction based on the native purchase update\n             */\n            refresh(purchase, fromConstructor) {\n                var _a, _b;\n                this.nativePurchase = purchase;\n                this.transactionId = `${purchase.orderId || purchase.purchaseToken}`;\n                this.purchaseId = `${purchase.purchaseToken}`;\n                this.products = purchase.productIds.map(productId => ({ id: productId }));\n                if (purchase.purchaseTime)\n                    this.purchaseDate = new Date(purchase.purchaseTime);\n                this.isPending = (purchase.getPurchaseState === GooglePlay.Bridge.PurchaseState.PENDING);\n                if (typeof purchase.acknowledged !== 'undefined')\n                    this.isAcknowledged = purchase.acknowledged;\n                if (typeof purchase.consumed !== 'undefined')\n                    this.isConsumed = purchase.consumed;\n                if (typeof purchase.autoRenewing !== 'undefined')\n                    this.renewalIntent = purchase.autoRenewing ? CdvPurchase.RenewalIntent.RENEW : CdvPurchase.RenewalIntent.LAPSE;\n                this.state = Transaction.toState(fromConstructor !== null && fromConstructor !== void 0 ? fromConstructor : false, purchase.getPurchaseState, (_a = this.isAcknowledged) !== null && _a !== void 0 ? _a : false, (_b = this.isConsumed) !== null && _b !== void 0 ? _b : false);\n            }\n        }\n        GooglePlay.Transaction = Transaction;\n        class Receipt extends CdvPurchase.Receipt {\n            /** @internal */\n            constructor(purchase, decorator) {\n                super(CdvPurchase.Platform.GOOGLE_PLAY, decorator);\n                this.transactions = [new Transaction(purchase, this, decorator)];\n                this.purchaseToken = purchase.purchaseToken;\n                this.orderId = purchase.orderId;\n            }\n            /** Refresh the content of the purchase based on the native BridgePurchase */\n            refreshPurchase(purchase) {\n                var _a;\n                (_a = this.transactions[0]) === null || _a === void 0 ? void 0 : _a.refresh(purchase);\n                this.orderId = purchase.orderId;\n            }\n        }\n        GooglePlay.Receipt = Receipt;\n        class Adapter {\n            constructor(context, autoRefreshIntervalMillis = 1000 * 3600 * 24) {\n                /** Adapter identifier */\n                this.id = CdvPurchase.Platform.GOOGLE_PLAY;\n                /** Adapter name */\n                this.name = 'GooglePlay';\n                /** Has the adapter been successfully initialized */\n                this.ready = false;\n                this.supportsParallelLoading = false;\n                this._receipts = [];\n                /** The GooglePlay bridge */\n                this.bridge = new GooglePlay.Bridge.Bridge();\n                /** Prevent double initialization */\n                this.initialized = false;\n                /** Used to retry failed commands */\n                this.retry = new CdvPurchase.Internal.Retry();\n                this.autoRefreshIntervalMillis = 0;\n                if (Adapter._instance)\n                    throw new Error('GooglePlay adapter already initialized');\n                this._products = new GooglePlay.Products(context.apiDecorators);\n                this.autoRefreshIntervalMillis = autoRefreshIntervalMillis;\n                this.context = context;\n                this.log = context.log.child('GooglePlay');\n                Adapter._instance = this;\n            }\n            /** List of products managed by the GooglePlay adapter */\n            get products() { return this._products.products; }\n            get receipts() { return this._receipts; }\n            /** Returns true on Android, the only platform supported by this adapter */\n            get isSupported() {\n                return CdvPurchase.Utils.platformId() === 'android';\n            }\n            initialize() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.log.info(\"Initialize\");\n                    if (this.initializationPromise)\n                        return this.initializationPromise;\n                    return this.initializationPromise = new Promise((resolve) => {\n                        const bridgeLogger = this.log.child('Bridge');\n                        const iabOptions = {\n                            onSetPurchases: this.onSetPurchases.bind(this),\n                            onPurchasesUpdated: this.onPurchasesUpdated.bind(this),\n                            onPurchaseConsumed: this.onPurchaseConsumed.bind(this),\n                            showLog: this.context.verbosity >= CdvPurchase.LogLevel.DEBUG ? true : false,\n                            log: (msg) => bridgeLogger.info(msg),\n                        };\n                        const iabReady = () => {\n                            this.log.debug(\"Ready\");\n                            // Auto-refresh every 24 hours (or autoRefreshIntervalMillis)\n                            if (this.autoRefreshIntervalMillis > 0) {\n                                window.setInterval(() => this.getPurchases(), this.autoRefreshIntervalMillis);\n                            }\n                            resolve(undefined);\n                        };\n                        const iabError = (err) => {\n                            this.initialized = false;\n                            this.context.error(playStoreError(CdvPurchase.ErrorCode.SETUP, \"Init failed - \" + err, null));\n                            this.retry.retry(() => this.initialize());\n                        };\n                        this.bridge.init(iabReady, iabError, iabOptions);\n                    });\n                });\n            }\n            /** Prepare the list of SKUs sorted by type */\n            getSkusOf(products) {\n                const inAppSkus = [];\n                const subsSkus = [];\n                for (const product of products) {\n                    if (product.type === CdvPurchase.ProductType.PAID_SUBSCRIPTION)\n                        subsSkus.push(product.id);\n                    else\n                        inAppSkus.push(product.id);\n                }\n                return { inAppSkus, subsSkus };\n            }\n            /** @inheritdoc */\n            loadReceipts() {\n                return new Promise((resolve) => {\n                    // let's also refresh purchases\n                    this.getPurchases()\n                        .then(err => {\n                        resolve(this._receipts);\n                    });\n                });\n            }\n            /** @inheritDoc */\n            loadProducts(products) {\n                return new Promise((resolve) => {\n                    this.log.debug(\"Load: \" + JSON.stringify(products));\n                    /** Called when a list of product definitions have been loaded */\n                    const iabLoaded = (validProducts) => {\n                        this.log.debug(\"Loaded: \" + JSON.stringify(validProducts));\n                        // Add type check to handle invalid responses\n                        if (!Array.isArray(validProducts)) {\n                            const message = `Invalid product list received: ${JSON.stringify(validProducts)}, retrying later...`;\n                            this.log.warn(message);\n                            this.retry.retry(go);\n                            this.context.error(playStoreError(CdvPurchase.ErrorCode.LOAD, message, null));\n                            return;\n                        }\n                        const ret = products.map(registeredProduct => {\n                            const validProduct = validProducts.find(vp => vp.productId === registeredProduct.id);\n                            if (validProduct && validProduct.productId) {\n                                return this._products.addProduct(registeredProduct, validProduct);\n                            }\n                            else {\n                                return playStoreError(CdvPurchase.ErrorCode.INVALID_PRODUCT_ID, `Product with id ${registeredProduct.id} not found.`, registeredProduct.id);\n                            }\n                        });\n                        resolve(ret);\n                    };\n                    /** Start loading products */\n                    const go = () => {\n                        const { inAppSkus, subsSkus } = this.getSkusOf(products);\n                        this.log.debug(\"getAvailableProducts: \" + JSON.stringify(inAppSkus) + \" | \" + JSON.stringify(subsSkus));\n                        this.bridge.getAvailableProducts(inAppSkus, subsSkus, iabLoaded, (err) => {\n                            // failed to load products, retry later.\n                            this.retry.retry(go);\n                            this.context.error(playStoreError(CdvPurchase.ErrorCode.LOAD, 'Loading product info failed - ' + err + ' - retrying later...', null));\n                        });\n                    };\n                    go();\n                });\n            }\n            /** @inheritDoc */\n            finish(transaction) {\n                return new Promise(resolve => {\n                    const onSuccess = () => {\n                        if (transaction.state !== CdvPurchase.TransactionState.FINISHED) {\n                            transaction.state = CdvPurchase.TransactionState.FINISHED;\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.GOOGLE_PLAY, [transaction.parentReceipt]);\n                        }\n                        resolve(undefined);\n                    };\n                    const firstProduct = transaction.products[0];\n                    if (!firstProduct)\n                        return resolve(playStoreError(CdvPurchase.ErrorCode.FINISH, 'Cannot finish a transaction with no product', null));\n                    const product = this._products.getProduct(firstProduct.id);\n                    if (!product)\n                        return resolve(playStoreError(CdvPurchase.ErrorCode.FINISH, 'Cannot finish transaction, unknown product ' + firstProduct.id, firstProduct.id));\n                    const receipt = this._receipts.find(r => r.hasTransaction(transaction));\n                    if (!receipt)\n                        return resolve(playStoreError(CdvPurchase.ErrorCode.FINISH, 'Cannot finish transaction, linked receipt not found.', product.id));\n                    if (!receipt.purchaseToken)\n                        return resolve(playStoreError(CdvPurchase.ErrorCode.FINISH, 'Cannot finish transaction, linked receipt contains no purchaseToken.', product.id));\n                    const onFailure = (message, code) => resolve(playStoreError(code || CdvPurchase.ErrorCode.UNKNOWN, message, product.id));\n                    if (product.type === CdvPurchase.ProductType.NON_RENEWING_SUBSCRIPTION || product.type === CdvPurchase.ProductType.CONSUMABLE) {\n                        if (!transaction.isConsumed)\n                            return this.bridge.consumePurchase(onSuccess, onFailure, receipt.purchaseToken);\n                    }\n                    else { // subscription and non-consumable\n                        if (!transaction.isAcknowledged)\n                            return this.bridge.acknowledgePurchase(onSuccess, onFailure, receipt.purchaseToken);\n                    }\n                    // nothing to do\n                    resolve(undefined);\n                });\n            }\n            /** Called by the bridge when a purchase has been consumed */\n            onPurchaseConsumed(purchase) {\n                this.log.debug(\"onPurchaseConsumed: \" + purchase.orderId);\n                purchase.acknowledged = true; // consumed is the equivalent of acknowledged for consumables\n                purchase.consumed = true;\n                this.onPurchasesUpdated([purchase]);\n            }\n            /** Called when the platform reports update for some purchases */\n            onPurchasesUpdated(purchases) {\n                this.log.debug(\"onPurchaseUpdated: \" + purchases.map(p => p.orderId).join(', '));\n                // GooglePlay generates one receipt for each purchase\n                purchases.forEach(purchase => {\n                    const existingReceipt = this.receipts.find(r => r.purchaseToken === purchase.purchaseToken);\n                    if (existingReceipt) {\n                        existingReceipt.refreshPurchase(purchase);\n                        this.context.listener.receiptsUpdated(CdvPurchase.Platform.GOOGLE_PLAY, [existingReceipt]);\n                    }\n                    else {\n                        const newReceipt = new Receipt(purchase, this.context.apiDecorators);\n                        this.receipts.push(newReceipt);\n                        this.context.listener.receiptsUpdated(CdvPurchase.Platform.GOOGLE_PLAY, [newReceipt]);\n                        if (newReceipt.transactions[0].state === CdvPurchase.TransactionState.INITIATED && !newReceipt.transactions[0].isPending) {\n                            // For compatibility, we set the state of \"new\" purchases to initiated from the constructor,\n                            // they'll got to \"approved\" when refreshed.\n                            // this way, users receive the \"initiated\" event, then \"approved\"\n                            newReceipt.refreshPurchase(purchase);\n                            this.context.listener.receiptsUpdated(CdvPurchase.Platform.GOOGLE_PLAY, [newReceipt]);\n                        }\n                    }\n                });\n            }\n            /** Called when the platform reports some purchases */\n            onSetPurchases(purchases) {\n                this.log.debug(\"onSetPurchases: \" + JSON.stringify(purchases));\n                this.onPurchasesUpdated(purchases);\n                this.context.listener.receiptsReady(CdvPurchase.Platform.GOOGLE_PLAY);\n            }\n            onPriceChangeConfirmationResult(result) {\n            }\n            /** Refresh purchases from GooglePlay */\n            getPurchases() {\n                return new Promise(resolve => {\n                    this.log.debug('getPurchases');\n                    const success = () => {\n                        this.log.debug('getPurchases success');\n                        setTimeout(() => resolve(undefined), 0);\n                    };\n                    const failure = (message, code) => {\n                        this.log.warn('getPurchases failed: ' + message + ' (' + code + ')');\n                        setTimeout(() => resolve(playStoreError(code || CdvPurchase.ErrorCode.UNKNOWN, message, null)), 0);\n                    };\n                    this.bridge.getPurchases(success, failure);\n                });\n            }\n            /** @inheritDoc */\n            order(offer, additionalData) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return new Promise(resolve => {\n                        this.log.info(\"Order - \" + JSON.stringify(offer));\n                        const buySuccess = () => resolve(undefined);\n                        const buyFailed = (message, code) => {\n                            this.log.warn('Order failed: ' + JSON.stringify({ message, code }));\n                            resolve(playStoreError(code !== null && code !== void 0 ? code : CdvPurchase.ErrorCode.UNKNOWN, message, offer.productId));\n                        };\n                        if (offer.productType === CdvPurchase.ProductType.PAID_SUBSCRIPTION) {\n                            const idAndToken = 'token' in offer ? offer.productId + '@' + offer.token : offer.productId;\n                            // find if the user already owns a product in the same group\n                            const oldPurchaseToken = this.findOldPurchaseToken(offer.productId, offer.productGroup);\n                            if (oldPurchaseToken) {\n                                if (!additionalData.googlePlay)\n                                    additionalData.googlePlay = { oldPurchaseToken };\n                                else if (!additionalData.googlePlay.oldPurchaseToken) {\n                                    additionalData.googlePlay.oldPurchaseToken = oldPurchaseToken;\n                                }\n                            }\n                            this.bridge.subscribe(buySuccess, buyFailed, idAndToken, additionalData);\n                        }\n                        else {\n                            this.bridge.buy(buySuccess, buyFailed, offer.productId, additionalData);\n                        }\n                    });\n                });\n            }\n            /**\n             * Find a purchaseToken for an owned product in the same group as the requested one.\n             *\n             * @param productId - The product identifier to request matching purchaseToken for.\n             * @param productGroup - The group of the product to request matching purchaseToken for.\n             *\n             * @return A purchaseToken, undefined if none have been found.\n             */\n            findOldPurchaseToken(productId, productGroup) {\n                if (!productGroup)\n                    return undefined;\n                const oldReceipt = this._receipts.find(r => {\n                    return !!r.transactions.find(t => {\n                        return !!t.products.find(p => {\n                            const product = this._products.getProduct(p.id);\n                            if (!product)\n                                return false;\n                            if (!CdvPurchase.Internal.LocalReceipts.isOwned([r], product))\n                                return false;\n                            return (p.id === productId) || (productGroup && product.group === productGroup);\n                        });\n                    });\n                });\n                return oldReceipt === null || oldReceipt === void 0 ? void 0 : oldReceipt.purchaseToken;\n            }\n            /**\n             * Prepare for receipt validation\n             */\n            receiptValidationBody(receipt) {\n                var _a;\n                return __awaiter(this, void 0, void 0, function* () {\n                    const transaction = receipt.transactions[0];\n                    if (!transaction)\n                        return;\n                    const productId = (_a = transaction.products[0]) === null || _a === void 0 ? void 0 : _a.id;\n                    if (!productId)\n                        return;\n                    const product = this._products.getProduct(productId);\n                    if (!product)\n                        return;\n                    const purchase = transaction.nativePurchase;\n                    return {\n                        id: productId,\n                        type: product.type,\n                        offers: product.offers,\n                        products: this._products.products,\n                        transaction: {\n                            type: CdvPurchase.Platform.GOOGLE_PLAY,\n                            id: receipt.transactions[0].transactionId,\n                            purchaseToken: purchase.purchaseToken,\n                            signature: purchase.signature,\n                            receipt: purchase.receipt,\n                        }\n                    };\n                });\n            }\n            handleReceiptValidationResponse(receipt, response) {\n                var _a;\n                return __awaiter(this, void 0, void 0, function* () {\n                    if (response === null || response === void 0 ? void 0 : response.ok) {\n                        const transaction = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.transaction;\n                        if ((transaction === null || transaction === void 0 ? void 0 : transaction.type) !== CdvPurchase.Platform.GOOGLE_PLAY)\n                            return;\n                        switch (transaction.kind) {\n                            case 'androidpublisher#productPurchase':\n                                break;\n                            case 'androidpublisher#subscriptionPurchase':\n                                break;\n                            case 'androidpublisher#subscriptionPurchaseV2':\n                                transaction;\n                                break;\n                            case 'fovea#subscriptionGone':\n                                // the transaction doesn't exist anymore\n                                break;\n                        }\n                    }\n                    return; // Nothing specific to do on GooglePlay\n                });\n            }\n            requestPayment(payment, additionalData) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return playStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'requestPayment not supported', null);\n                });\n            }\n            manageSubscriptions() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.bridge.manageSubscriptions();\n                    return;\n                });\n            }\n            manageBilling() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    this.bridge.manageBilling();\n                    return;\n                });\n            }\n            checkSupport(functionality) {\n                const supported = [\n                    'order', 'manageBilling', 'manageSubscriptions'\n                ];\n                return supported.indexOf(functionality) >= 0;\n            }\n            restorePurchases() {\n                return new Promise(resolve => {\n                    this.bridge.getPurchases(() => resolve(undefined), (message, code) => {\n                        this.log.warn('getPurchases() failed: ' + (code !== null && code !== void 0 ? code : 'ERROR') + ': ' + message);\n                        resolve(playStoreError(code !== null && code !== void 0 ? code : CdvPurchase.ErrorCode.UNKNOWN, message, null));\n                    });\n                });\n            }\n        }\n        Adapter.trimProductTitles = true;\n        GooglePlay.Adapter = Adapter;\n        function playStoreError(code, message, productId) {\n            return CdvPurchase.storeError(code, message, CdvPurchase.Platform.GOOGLE_PLAY, productId);\n        }\n    })(GooglePlay = CdvPurchase.GooglePlay || (CdvPurchase.GooglePlay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let GooglePlay;\n    (function (GooglePlay) {\n        let Bridge;\n        (function (Bridge) {\n            /* export namespace V11 {\n                export interface Subscription {\n                    product_format: \"v11.0\";\n                    productId: string;\n                    title: string;\n                    name: string;\n                    billing_period: string;\n                    billing_period_unit: string;\n                    description: string;\n                    price: string;\n                    price_amount_micros: string;\n                    price_currency_code: string;\n                    trial_period: string;\n                    trial_period_unit: string;\n                    formatted_price: string;\n                    freeTrialPeriod: string;\n                    introductoryPrice: string;\n                    introductoryPriceAmountMicros: string;\n                    introductoryPriceCycles: string;\n                    introductoryPricePeriod: string;\n                    subscriptionPeriod: string;\n                }\n            } */\n            let RecurrenceMode;\n            (function (RecurrenceMode) {\n                RecurrenceMode[\"FINITE_RECURRING\"] = \"FINITE_RECURRING\";\n                RecurrenceMode[\"INFINITE_RECURRING\"] = \"INFINITE_RECURRING\";\n                RecurrenceMode[\"NON_RECURRING\"] = \"NON_RECURRING\";\n            })(RecurrenceMode = Bridge.RecurrenceMode || (Bridge.RecurrenceMode = {}));\n        })(Bridge = GooglePlay.Bridge || (GooglePlay.Bridge = {}));\n    })(GooglePlay = CdvPurchase.GooglePlay || (CdvPurchase.GooglePlay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/*\n * Copyright (C) 2012-2013 by Guillaume Charhon\n * Modifications 10/16/2013 by Brian Thurlow\n */\n/*global cordova */\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let GooglePlay;\n    (function (GooglePlay) {\n        /**\n         * Replace SKU ProrationMode.\n         *\n         * See https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode\n         *\n         * @deprecated Use {@link ReplacementMode}\n         */\n        let ProrationMode;\n        (function (ProrationMode) {\n            /** Replacement takes effect immediately, and the remaining time will be prorated and credited to the user. */\n            ProrationMode[\"IMMEDIATE_WITH_TIME_PRORATION\"] = \"IMMEDIATE_WITH_TIME_PRORATION\";\n            /** Replacement takes effect immediately, and the billing cycle remains the same. */\n            ProrationMode[\"IMMEDIATE_AND_CHARGE_PRORATED_PRICE\"] = \"IMMEDIATE_AND_CHARGE_PRORATED_PRICE\";\n            /** Replacement takes effect immediately, and the new price will be charged on next recurrence time. */\n            ProrationMode[\"IMMEDIATE_WITHOUT_PRORATION\"] = \"IMMEDIATE_WITHOUT_PRORATION\";\n            /** Replacement takes effect when the old plan expires, and the new price will be charged at the same time. */\n            ProrationMode[\"DEFERRED\"] = \"DEFERRED\";\n            /** Replacement takes effect immediately, and the user is charged full price of new plan and is given a full billing cycle of subscription, plus remaining prorated time from the old plan. */\n            ProrationMode[\"IMMEDIATE_AND_CHARGE_FULL_PRICE\"] = \"IMMEDIATE_AND_CHARGE_FULL_PRICE\";\n        })(ProrationMode = GooglePlay.ProrationMode || (GooglePlay.ProrationMode = {}));\n        /**\n         * Supported replacement modes to replace an existing subscription with a new one.\n         *\n         * @see {@link https://developer.android.com/google/play/billing/subscriptions#replacement-modes}\n         */\n        let ReplacementMode;\n        (function (ReplacementMode) {\n            /** Replacement takes effect immediately, and the remaining time will be prorated and credited to the user. */\n            ReplacementMode[\"WITH_TIME_PRORATION\"] = \"IMMEDIATE_WITH_TIME_PRORATION\";\n            /** Replacement takes effect immediately, and the billing cycle remains the same. */\n            ReplacementMode[\"CHARGE_PRORATED_PRICE\"] = \"IMMEDIATE_AND_CHARGE_PRORATED_PRICE\";\n            /** Replacement takes effect immediately, and the new price will be charged on next recurrence time. */\n            ReplacementMode[\"WITHOUT_PRORATION\"] = \"IMMEDIATE_WITHOUT_PRORATION\";\n            /** Replacement takes effect when the old plan expires, and the new price will be charged at the same time. */\n            ReplacementMode[\"DEFERRED\"] = \"DEFERRED\";\n            /** Replacement takes effect immediately, and the user is charged full price of new plan and is given a full billing cycle of subscription, plus remaining prorated time from the old plan. */\n            ReplacementMode[\"CHARGE_FULL_PRICE\"] = \"IMMEDIATE_AND_CHARGE_FULL_PRICE\";\n        })(ReplacementMode = GooglePlay.ReplacementMode || (GooglePlay.ReplacementMode = {}));\n        let Bridge;\n        (function (Bridge_2) {\n            let log = function log(msg) {\n                console.log(\"InAppBilling[js]: \" + msg);\n            };\n            let PurchaseState;\n            (function (PurchaseState) {\n                PurchaseState[PurchaseState[\"UNSPECIFIED_STATE\"] = 0] = \"UNSPECIFIED_STATE\";\n                PurchaseState[PurchaseState[\"PURCHASED\"] = 1] = \"PURCHASED\";\n                PurchaseState[PurchaseState[\"PENDING\"] = 2] = \"PENDING\";\n            })(PurchaseState = Bridge_2.PurchaseState || (Bridge_2.PurchaseState = {}));\n            class Bridge {\n                constructor() {\n                    this.options = {};\n                }\n                init(success, fail, options) {\n                    if (!options)\n                        options = {};\n                    if (options.log)\n                        log = options.log;\n                    this.options = {\n                        showLog: options.showLog !== false,\n                        onPurchaseConsumed: options.onPurchaseConsumed,\n                        onPurchasesUpdated: options.onPurchasesUpdated,\n                        onSetPurchases: options.onSetPurchases,\n                    };\n                    if (this.options.showLog) {\n                        log('setup ok');\n                    }\n                    // Set a listener (see \"listener()\" function above)\n                    const listener = this.listener.bind(this);\n                    window.cordova.exec(listener, function (err) { }, \"InAppBillingPlugin\", \"setListener\", []);\n                    window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"init\", []);\n                }\n                load(success, fail, skus, inAppSkus, subsSkus) {\n                    var hasSKUs = false;\n                    // Optional Load SKUs to Inventory.\n                    if (typeof skus !== \"undefined\") {\n                        if (typeof skus === \"string\") {\n                            skus = [skus];\n                        }\n                        if (skus.length > 0) {\n                            if (typeof skus[0] !== 'string') {\n                                var msg = 'invalid productIds: ' + JSON.stringify(skus);\n                                if (this.options.showLog) {\n                                    log(msg);\n                                }\n                                fail(msg, CdvPurchase.ErrorCode.INVALID_PRODUCT_ID);\n                                return;\n                            }\n                            if (this.options.showLog) {\n                                log('load ' + JSON.stringify(skus));\n                            }\n                            hasSKUs = true;\n                        }\n                    }\n                    window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"load\", [skus, inAppSkus, subsSkus]);\n                }\n                listener(msg) {\n                    // Handle changes to purchase that are being notified\n                    // through the PurchasesUpdatedListener on the native side (android)\n                    if (this.options.showLog) {\n                        log('listener: ' + JSON.stringify(msg));\n                    }\n                    if (!msg || !msg.type) {\n                        return;\n                    }\n                    if (msg.type === \"setPurchases\" && this.options.onSetPurchases) {\n                        this.options.onSetPurchases(msg.data.purchases);\n                    }\n                    if (msg.type === \"purchasesUpdated\" && this.options.onPurchasesUpdated) {\n                        this.options.onPurchasesUpdated(msg.data.purchases);\n                    }\n                    if (msg.type === \"purchaseConsumed\" && this.options.onPurchaseConsumed) {\n                        this.options.onPurchaseConsumed(msg.data.purchase);\n                    }\n                    if (msg.type === \"onPriceChangeConfirmationResultOK\" && this.options.onPriceChangeConfirmationResult) {\n                        this.options.onPriceChangeConfirmationResult(\"OK\");\n                    }\n                    if (msg.type === \"onPriceChangeConfirmationResultUserCanceled\" && this.options.onPriceChangeConfirmationResult) {\n                        this.options.onPriceChangeConfirmationResult(\"UserCanceled\");\n                    }\n                    if (msg.type === \"onPriceChangeConfirmationResultUnknownSku\" && this.options.onPriceChangeConfirmationResult) {\n                        this.options.onPriceChangeConfirmationResult(\"UnknownProduct\");\n                    }\n                }\n                getPurchases(success, fail) {\n                    if (this.options.showLog) {\n                        log('getPurchases()');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"getPurchases\", [\"null\"]);\n                }\n                buy(success, fail, productId, additionalData) {\n                    if (this.options.showLog) {\n                        log('buy()');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"buy\", [\n                        productId, extendAdditionalData(additionalData)\n                    ]);\n                }\n                subscribe(success, fail, productId, additionalData) {\n                    var _a;\n                    if (this.options.showLog) {\n                        log('subscribe()');\n                    }\n                    if (((_a = additionalData.googlePlay) === null || _a === void 0 ? void 0 : _a.oldPurchaseToken) && this.options.showLog) {\n                        log('subscribe() -> upgrading from an old purchase');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"subscribe\", [\n                        productId, extendAdditionalData(additionalData)\n                    ]);\n                }\n                consumePurchase(success, fail, purchaseToken) {\n                    if (this.options.showLog) {\n                        log('consumePurchase()');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"consumePurchase\", [purchaseToken]);\n                }\n                acknowledgePurchase(success, fail, purchaseToken) {\n                    if (this.options.showLog) {\n                        log('acknowledgePurchase()');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"acknowledgePurchase\", [purchaseToken]);\n                }\n                getAvailableProducts(inAppSkus, subsSkus, success, fail) {\n                    if (this.options.showLog) {\n                        log('getAvailableProducts()');\n                    }\n                    return window.cordova.exec(success, errorCb(fail), \"InAppBillingPlugin\", \"getAvailableProducts\", [inAppSkus, subsSkus]);\n                }\n                manageSubscriptions() {\n                    return window.cordova.exec(function () { }, function () { }, \"InAppBillingPlugin\", \"manageSubscriptions\", []);\n                }\n                manageBilling() {\n                    return window.cordova.exec(function () { }, function () { }, \"InAppBillingPlugin\", \"manageBilling\", []);\n                }\n                launchPriceChangeConfirmationFlow(productId) {\n                    return window.cordova.exec(function () { }, function () { }, \"InAppBillingPlugin\", \"launchPriceChangeConfirmationFlow\", [productId]);\n                }\n            }\n            Bridge_2.Bridge = Bridge;\n            // Generates a `fail` function that accepts an optional error code\n            // in the first part of the error string.\n            //\n            // format: `code|message`\n            //\n            // `fail` function will be called with `message` as a first argument\n            // and `code` as a second argument (or undefined). This ensures\n            // backward compatibility with legacy code\n            function errorCb(fail) {\n                return function (error) {\n                    if (!fail)\n                        return;\n                    const tokens = typeof error === 'string' ? error.split('|') : [];\n                    if (tokens.length > 1 && /^[-+]?(\\d+)$/.test(tokens[0])) {\n                        var code = tokens[0];\n                        var message = tokens[1];\n                        fail(message, +code);\n                    }\n                    else {\n                        fail(error);\n                    }\n                };\n            }\n            function ensureObject(obj) {\n                return !!obj && obj.constructor === Object ? obj : {};\n            }\n            function extendAdditionalData(ad) {\n                const additionalData = ensureObject(ad === null || ad === void 0 ? void 0 : ad.googlePlay);\n                if (!additionalData.accountId && (ad === null || ad === void 0 ? void 0 : ad.applicationUsername)) {\n                    additionalData.accountId = CdvPurchase.Utils.md5(ad.applicationUsername);\n                }\n                return additionalData;\n            }\n        })(Bridge = GooglePlay.Bridge || (GooglePlay.Bridge = {}));\n    })(GooglePlay = CdvPurchase.GooglePlay || (CdvPurchase.GooglePlay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"../../offer.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let GooglePlay;\n    (function (GooglePlay) {\n        class GProduct extends CdvPurchase.Product {\n        }\n        GooglePlay.GProduct = GProduct;\n        class InAppOffer extends CdvPurchase.Offer {\n            constructor() {\n                super(...arguments);\n                this.type = 'inapp';\n            }\n        }\n        GooglePlay.InAppOffer = InAppOffer;\n        class SubscriptionOffer extends CdvPurchase.Offer {\n            constructor(options, decorator) {\n                super(options, decorator);\n                this.type = 'subs';\n                this.tags = options.tags;\n                this.token = options.token;\n            }\n        }\n        GooglePlay.SubscriptionOffer = SubscriptionOffer;\n        class Products {\n            constructor(decorator) {\n                /** List of products managed by the GooglePlay adapter */\n                this.products = [];\n                /** List of offers managed by the GooglePlay adapter */\n                this.offers = [];\n                this.decorator = decorator;\n            }\n            getProduct(id) {\n                return this.products.find(p => p.id === id);\n            }\n            getOffer(id) {\n                return this.offers.find(p => p.id === id);\n            }\n            /**  */\n            addProduct(registeredProduct, vp) {\n                const existingProduct = this.getProduct(registeredProduct.id);\n                const p = existingProduct !== null && existingProduct !== void 0 ? existingProduct : new GProduct(registeredProduct, this.decorator);\n                p.title = vp.title || vp.name || p.title;\n                if (GooglePlay.Adapter.trimProductTitles)\n                    p.title = p.title.replace(/ \\(.*\\)$/, '');\n                p.description = vp.description || p.description;\n                // Process the product depending on the format\n                if ('product_format' in vp && vp.product_format === \"v12.0\") {\n                    if (vp.product_type === \"subs\")\n                        this.onSubsV12Loaded(p, vp);\n                    else\n                        this.onInAppLoaded(p, vp);\n                }\n                // else if ('billing_period_unit' in vp) {\n                //     return this.iabSubsV11Loaded(p, vp);\n                // }\n                else {\n                    this.onInAppLoaded(p, vp);\n                }\n                if (!existingProduct) {\n                    this.products.push(p);\n                }\n                return p;\n            }\n            onSubsV12Loaded(product, vp) {\n                // console.log('iabSubsV12Loaded: ' + JSON.stringify(vp));\n                vp.offers.forEach((productOffer) => {\n                    // Add the base plan's pricing phase to offers that do not end-up as infinite recurring.\n                    const lastPhase = productOffer.pricing_phases.slice(-1)[0];\n                    if ((lastPhase === null || lastPhase === void 0 ? void 0 : lastPhase.recurrence_mode) === CdvPurchase.RecurrenceMode.FINITE_RECURRING) {\n                        const baseOffer = findBasePlan(productOffer.base_plan_id);\n                        if (baseOffer && (baseOffer !== productOffer)) {\n                            productOffer.pricing_phases.push(...baseOffer.pricing_phases);\n                        }\n                    }\n                    // Convert the offer to the generic representation\n                    const offer = this.iabSubsOfferV12Loaded(product, vp, productOffer);\n                    product.addOffer(offer);\n                });\n                function findBasePlan(basePlanId) {\n                    if (!basePlanId)\n                        return null;\n                    for (const offer of vp.offers) {\n                        if (offer.base_plan_id === basePlanId && !offer.offer_id) {\n                            return offer;\n                        }\n                    }\n                    return null;\n                }\n                /*\n                var firstOffer = vp.offers[0];\n                if (firstOffer && firstOffer.pricing_phases.length > 0) {\n                    const attributes = {\n                        state: store.VALID,\n                        title: vp.name,\n                        description: vp.description,\n                        offers: vp.offers.map(function (offer) {\n                            return vp.productId + '@' + offer.token;\n                        }),\n                    };\n                    this.iabSubsAddV12Attributes(attributes, firstOffer);\n                    const p = this.getProduct(vp.productId);\n                    p.set(attributes);\n                    p.trigger(\"loaded\");\n                }\n                */\n                return product;\n            }\n            makeOfferId(productId, productOffer) {\n                let id = productId;\n                if (productOffer.base_plan_id) {\n                    if (productOffer.offer_id) {\n                        return productId + '@' + productOffer.base_plan_id + '@' + productOffer.offer_id;\n                    }\n                    return productId + '@' + productOffer.base_plan_id;\n                }\n                return productId + '@' + productOffer.token;\n            }\n            iabSubsOfferV12Loaded(product, vp, productOffer) {\n                const offerId = this.makeOfferId(vp.productId, productOffer);\n                const existingOffer = this.getOffer(offerId);\n                const pricingPhases = productOffer.pricing_phases.map(p => this.toPricingPhase(p));\n                if (existingOffer) {\n                    existingOffer.pricingPhases = pricingPhases;\n                    return existingOffer;\n                }\n                else {\n                    const offer = new SubscriptionOffer({ id: offerId, product, pricingPhases, token: productOffer.token, tags: productOffer.tags }, this.decorator);\n                    this.offers.push(offer);\n                    return offer;\n                }\n                /*\n                // Backward compatibility (might be incomplete if user have complex pricing models, but might as well be complete...)\n                if (productOffer.pricing_phases.length > 0) {\n                    iabSubsAddV12Attributes(offerAttributes, productOffer);\n                }\n                var offerP = store.get(offerAttributes.id);\n                if (!offerP) {\n                    store.register(offerAttributes);\n                    offerP = store.get(offerAttributes.id);\n                }\n                offerP.set(offerAttributes);\n                offerP.trigger(\"loaded\");\n                */\n            }\n            /*\n            private iabSubsV11Loaded(p: Product, vp: SubscriptionV11): Product {\n                // console.log('iabSubsV11Loaded: ' + JSON.stringify(vp));\n                var p = store.products.byId[vp.productId];\n                var attributes = {\n                    state: store.VALID,\n                    title: vp.name || trimTitle(vp.title),\n                    description: vp.description,\n                };\n                var currency = vp.price_currency_code || \"\";\n                var price = vp.formatted_price || vp.price;\n                var priceMicros = vp.price_amount_micros;\n                var subscriptionPeriod = vp.subscriptionPeriod ? vp.subscriptionPeriod : \"\";\n                var introPriceSubscriptionPeriod = vp.introductoryPricePeriod ? vp.introductoryPricePeriod : \"\";\n                var introPriceNumberOfPeriods = vp.introductoryPriceCycles ? vp.introductoryPriceCycles : 0;\n                var introPricePeriodUnit = normalizeISOPeriodUnit(introPriceSubscriptionPeriod);\n                var introPricePeriodCount = normalizeISOPeriodCount(introPriceSubscriptionPeriod);\n                var introPricePeriod = (introPriceNumberOfPeriods || 1) * (introPricePeriodCount || 1);\n                var introPriceMicros = vp.introductoryPriceAmountMicros ? vp.introductoryPriceAmountMicros : \"\";\n                var introPrice = vp.introductoryPrice ? vp.introductoryPrice : \"\";\n                var introPricePaymentMode;\n\n                if (vp.freeTrialPeriod) {\n                    introPricePaymentMode = 'FreeTrial';\n                    try {\n                        introPricePeriodUnit = normalizeISOPeriodUnit(vp.freeTrialPeriod);\n                        introPricePeriodCount = normalizeISOPeriodCount(vp.freeTrialPeriod);\n                        introPricePeriod = introPricePeriodCount;\n                    }\n                    catch (e) {\n                        store.log.warn('Failed to parse free trial period: ' + vp.freeTrialPeriod);\n                    }\n                }\n                else if (vp.introductoryPrice) {\n                    if (vp.introductoryPrice < vp.price && subscriptionPeriod === introPriceSubscriptionPeriod) {\n                        introPricePaymentMode = 'PayAsYouGo';\n                    }\n                    else if (introPriceNumberOfPeriods === 1) {\n                        introPricePaymentMode = 'UpFront';\n                    }\n                }\n\n                if (!introPricePaymentMode) {\n                    introPricePeriod = null;\n                    introPricePeriodUnit = null;\n                }\n\n                var parsedSubscriptionPeriod = {};\n                if (subscriptionPeriod) {\n                    parsedSubscriptionPeriod.unit = normalizeISOPeriodUnit(subscriptionPeriod);\n                    parsedSubscriptionPeriod.count = normalizeISOPeriodCount(subscriptionPeriod);\n                }\n\n                var trialPeriod = vp.trial_period || null;\n                var trialPeriodUnit = vp.trial_period_unit || null;\n                var billingPeriod = parsedSubscriptionPeriod.count || vp.billing_period || null;\n                var billingPeriodUnit = parsedSubscriptionPeriod.unit || vp.billing_period_unit || null;\n\n                var pricingPhases = [];\n                if (trialPeriod) {\n                    pricingPhases.push({\n                        paymentMode: 'FreeTrial',\n                        recurrenceMode: store.FINITE_RECURRING,\n                        period: vp.freeTrialPeriod || toISO8601Duration(trialPeriodUnit, trialPeriod),\n                        cycles: 1,\n                        price: null,\n                        priceMicros: 0,\n                        currency: currency,\n                    });\n                }\n                else if (introPricePeriod) {\n                    pricingPhases.push({\n                        paymentMode: 'PayAsYouGo',\n                        recurrenceMode: store.FINITE_RECURRING,\n                        period: vp.introPriceSubscriptionPeriod || toISO8601Duration(introPricePeriodUnit, introPricePeriodCount),\n                        cycles: vp.introductoryPriceCycles || 1,\n                        price: null, // formatted price not available\n                        priceMicros: introPriceMicros,\n                        currency: currency,\n                    });\n                }\n\n                pricingPhases.push({\n                    paymentMode: 'PayAsYouGo',\n                    recurrenceMode: store.INFINITE_RECURRING,\n                    period: vp.subscriptionPeriod || toISO8601Duration(billingPeriodUnit, billingPeriod), // ISO8601 duration\n                    cycles: 0,\n                    price: price,\n                    priceMicros: priceMicros,\n                    currency: currency,\n                });\n                attributes.pricingPhases = pricingPhases;\n\n                if (store.compatibility > 0 && store.compatibility < 11.999) {\n                    Object.assign(attributes, {\n                        price: price,\n                        priceMicros: priceMicros,\n                        currency: currency,\n                        trialPeriod: trialPeriod,\n                        trialPeriodUnit: trialPeriodUnit,\n                        billingPeriod: billingPeriod,\n                        billingPeriodUnit: billingPeriodUnit,\n                        introPrice: introPrice,\n                        introPriceMicros: introPriceMicros,\n                        introPricePeriod: introPricePeriod,\n                        introPricePeriodUnit: introPricePeriodUnit,\n                        introPricePaymentMode: introPricePaymentMode,\n                    });\n                }\n\n                if (store.compatibility > 0 && store.compatibility < 9.999) {\n                    Object.assign(attributes, {\n                        introPriceNumberOfPeriods: introPricePeriod,\n                        introPriceSubscriptionPeriod: introPricePeriodUnit,\n                    });\n                }\n\n                p.set(attributes);\n                p.trigger(\"loaded\");\n            }\n            */\n            onInAppLoaded(p, vp) {\n                var _a, _b, _c, _d;\n                // console.log('iabInAppLoaded: ' + JSON.stringify(vp));\n                const existingOffer = this.getOffer(vp.productId);\n                const pricingPhases = [{\n                        price: (_b = (_a = vp.formatted_price) !== null && _a !== void 0 ? _a : vp.price) !== null && _b !== void 0 ? _b : `${((_c = vp.price_amount_micros) !== null && _c !== void 0 ? _c : 0) / 1000000} ${vp.price_currency_code}`,\n                        priceMicros: (_d = vp.price_amount_micros) !== null && _d !== void 0 ? _d : 0,\n                        currency: vp.price_currency_code,\n                        recurrenceMode: CdvPurchase.RecurrenceMode.NON_RECURRING,\n                    }];\n                if (existingOffer) {\n                    // state: store.VALID,\n                    // title: vp.name || trimTitle(vp.title),\n                    // description: vp.description,\n                    // currency: vp.price_currency_code || \"\",\n                    // price: vp.formatted_price || vp.price,\n                    // priceMicros: vp.price_amount_micros,\n                    existingOffer.pricingPhases = pricingPhases;\n                    p.offers = [existingOffer];\n                }\n                else {\n                    const newOffer = new InAppOffer({ id: vp.productId, product: p, pricingPhases }, this.decorator);\n                    this.offers.push(newOffer);\n                    p.offers = [newOffer];\n                }\n                // p.set({\n                //     state: store.VALID,\n                //     title: vp.name || trimTitle(vp.title),\n                //     description: vp.description,\n                //     currency: vp.price_currency_code || \"\",\n                //     price: vp.formatted_price || vp.price,\n                //     priceMicros: vp.price_amount_micros,\n                // });\n                // p.trigger(\"loaded\");\n                return p;\n            }\n            toPaymentMode(phase) {\n                return phase.price_amount_micros === 0\n                    ? CdvPurchase.PaymentMode.FREE_TRIAL\n                    : phase.recurrence_mode === GooglePlay.Bridge.RecurrenceMode.NON_RECURRING\n                        ? CdvPurchase.PaymentMode.UP_FRONT\n                        : CdvPurchase.PaymentMode.PAY_AS_YOU_GO;\n            }\n            toRecurrenceMode(mode) {\n                switch (mode) {\n                    case GooglePlay.Bridge.RecurrenceMode.FINITE_RECURRING: return CdvPurchase.RecurrenceMode.FINITE_RECURRING;\n                    case GooglePlay.Bridge.RecurrenceMode.INFINITE_RECURRING: return CdvPurchase.RecurrenceMode.INFINITE_RECURRING;\n                    case GooglePlay.Bridge.RecurrenceMode.NON_RECURRING: return CdvPurchase.RecurrenceMode.NON_RECURRING;\n                }\n            }\n            toPricingPhase(phase) {\n                return {\n                    price: phase.formatted_price,\n                    priceMicros: phase.price_amount_micros,\n                    currency: phase.price_currency_code,\n                    billingPeriod: phase.billing_period,\n                    billingCycles: phase.billing_cycle_count,\n                    recurrenceMode: this.toRecurrenceMode(phase.recurrence_mode),\n                    paymentMode: this.toPaymentMode(phase),\n                };\n            }\n        }\n        GooglePlay.Products = Products;\n    })(GooglePlay = CdvPurchase.GooglePlay || (CdvPurchase.GooglePlay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let GooglePlay;\n    (function (GooglePlay) {\n        let PublisherAPI;\n        (function (PublisherAPI) {\n            let GoogleErrorReason;\n            (function (GoogleErrorReason) {\n                /** The subscription purchase is no longer available for query because it has been expired for too long. */\n                GoogleErrorReason[\"SUBSCRIPTION_NO_LONGER_AVAILABLE\"] = \"subscriptionPurchaseNoLongerAvailable\";\n                /** The purchase token is no longer valid. */\n                GoogleErrorReason[\"PURCHASE_TOKEN_NO_LONGER_VALID\"] = \"purchaseTokenNoLongerValid\";\n            })(GoogleErrorReason = PublisherAPI.GoogleErrorReason || (PublisherAPI.GoogleErrorReason = {}));\n            /**\n           * Those are actually HTTP status codes.\n           *\n           * Duplicated here for documentation purposes.\n           */\n            let ErrorCode;\n            (function (ErrorCode) {\n                /** The subscription purchase is no longer available for query because it has been expired for too long. */\n                ErrorCode[ErrorCode[\"GONE\"] = 410] = \"GONE\";\n            })(ErrorCode = PublisherAPI.ErrorCode || (PublisherAPI.ErrorCode = {}));\n        })(PublisherAPI = GooglePlay.PublisherAPI || (GooglePlay.PublisherAPI = {}));\n    })(GooglePlay = CdvPurchase.GooglePlay || (CdvPurchase.GooglePlay = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /**\n     * Test Adapter and related classes.\n     */\n    let Test;\n    (function (Test) {\n        const platform = CdvPurchase.Platform.TEST;\n        let verifiedPurchases = [];\n        function updateVerifiedPurchases(tr) {\n            tr.products.forEach(p => {\n                var _a, _b, _c, _d;\n                const existing = verifiedPurchases.find(v => p.id === v.id);\n                const attributes = {\n                    id: p.id,\n                    purchaseDate: (_a = tr.purchaseDate) === null || _a === void 0 ? void 0 : _a.getTime(),\n                    expiryDate: (_b = tr.expirationDate) === null || _b === void 0 ? void 0 : _b.getTime(),\n                    lastRenewalDate: (_c = tr.lastRenewalDate) === null || _c === void 0 ? void 0 : _c.getTime(),\n                    renewalIntent: tr.renewalIntent,\n                    renewalIntentChangeDate: (_d = tr.renewalIntentChangeDate) === null || _d === void 0 ? void 0 : _d.getTime(),\n                };\n                if (existing) {\n                    Object.assign(existing, attributes);\n                }\n                else {\n                    verifiedPurchases.push(attributes);\n                }\n            });\n        }\n        /**\n         * Test Adapter used for local testing with mock products.\n         *\n         * This adapter simulates a payment platform that supports both In-App Products and Payment Requests.\n         *\n         * The list of supported In-App Products\n         *\n         * @see {@link Test.TEST_PRODUCTS}\n         */\n        class Adapter {\n            constructor(context) {\n                this.id = CdvPurchase.Platform.TEST;\n                this.name = 'Test';\n                this.ready = false;\n                this.products = [];\n                this.receipts = [];\n                this.supportsParallelLoading = true;\n                this.context = context;\n                this.log = context.log.child(\"Test\");\n            }\n            get isSupported() {\n                return true;\n            }\n            initialize() {\n                return __awaiter(this, void 0, void 0, function* () { return; });\n            }\n            loadReceipts() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return new Promise((resolve) => {\n                        setTimeout(() => {\n                            this.context.listener.receiptsReady(CdvPurchase.Platform.TEST);\n                            resolve(this.receipts);\n                        }, 600);\n                    });\n                });\n            }\n            loadProducts(products) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return products.map(registerProduct => {\n                        if (!Test.testProductsArray.find(p => p.id === registerProduct.id && p.type === registerProduct.type)) {\n                            return testStoreError(CdvPurchase.ErrorCode.PRODUCT_NOT_AVAILABLE, 'This product is not available', registerProduct.id);\n                        }\n                        // Ensure it's not been loaded already.\n                        const existingProduct = this.products.find(p => p.id === registerProduct.id);\n                        if (existingProduct)\n                            return existingProduct;\n                        // Enable the active subscription if loaded by the user.\n                        if (registerProduct.id === Test.testProducts.PAID_SUBSCRIPTION_ACTIVE.id) {\n                            setTimeout(() => {\n                                this.reportActiveSubscription();\n                            }, 500); // it'll get reported in 500ms\n                        }\n                        const product = Test.initTestProduct(registerProduct.id, this.context.apiDecorators);\n                        if (!product)\n                            return testStoreError(CdvPurchase.ErrorCode.PRODUCT_NOT_AVAILABLE, 'Could not load this product', registerProduct.id);\n                        this.products.push(product);\n                        this.context.listener.productsUpdated(CdvPurchase.Platform.TEST, [product]);\n                        return product;\n                    });\n                });\n            }\n            order(offer) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    // Purchasing products with \"-fail-\" in the id will fail.\n                    if (offer.id.indexOf(\"-fail-\") > 0) {\n                        return testStoreError(CdvPurchase.ErrorCode.PURCHASE, 'Purchase failed.', offer.productId);\n                    }\n                    const product = this.products.find(p => p.id === offer.productId);\n                    if (!CdvPurchase.Internal.LocalReceipts.canPurchase(this.receipts, product)) {\n                        return testStoreError(CdvPurchase.ErrorCode.PURCHASE, 'Product already owned', offer.productId);\n                    }\n                    // a receipt containing a transaction with the given product.\n                    const response = prompt(`Do you want to purchase ${offer.productId} for ${offer.pricingPhases[0].price}?\\nEnter \"Y\" to confirm.\\nEnter \"E\" to fail with an error.\\Anything else to cancel.`);\n                    if ((response === null || response === void 0 ? void 0 : response.toUpperCase()) === 'E')\n                        return testStoreError(CdvPurchase.ErrorCode.PURCHASE, 'Purchase failed', offer.productId);\n                    if ((response === null || response === void 0 ? void 0 : response.toUpperCase()) !== 'Y')\n                        return testStoreError(CdvPurchase.ErrorCode.PAYMENT_CANCELLED, 'Purchase flow has been cancelled by the user', offer.productId);\n                    // purchase succeeded, let's generate a mock receipt.\n                    const receipt = new CdvPurchase.Receipt(platform, this.context.apiDecorators);\n                    const tr = new CdvPurchase.Transaction(platform, receipt, this.context.apiDecorators);\n                    receipt.transactions = [tr];\n                    tr.products = [{\n                            id: offer.productId,\n                            offerId: offer.id,\n                        }];\n                    tr.state = CdvPurchase.TransactionState.APPROVED;\n                    tr.purchaseDate = new Date();\n                    tr.transactionId = offer.productId + '-' + (new Date().getTime());\n                    tr.isAcknowledged = false;\n                    if (offer.productType === CdvPurchase.ProductType.PAID_SUBSCRIPTION) {\n                        tr.expirationDate = new Date(+new Date() + 604800000);\n                        tr.renewalIntent = CdvPurchase.RenewalIntent.RENEW;\n                    }\n                    updateVerifiedPurchases(tr);\n                    this.receipts.push(receipt);\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.TEST, [receipt]);\n                });\n            }\n            finish(transaction) {\n                return new Promise(resolve => {\n                    setTimeout(() => {\n                        transaction.state = CdvPurchase.TransactionState.FINISHED;\n                        transaction.isAcknowledged = true;\n                        updateVerifiedPurchases(transaction);\n                        const product = this.products.find(p => transaction.products[0].id === p.id);\n                        if ((product === null || product === void 0 ? void 0 : product.type) === CdvPurchase.ProductType.CONSUMABLE)\n                            transaction.isConsumed = true;\n                        const receipts = this.receipts.filter(r => r.hasTransaction(transaction));\n                        this.context.listener.receiptsUpdated(platform, receipts);\n                        resolve(undefined);\n                    }, 500);\n                });\n            }\n            receiptValidationBody(receipt) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return;\n                });\n            }\n            handleReceiptValidationResponse(receipt, response) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return;\n                });\n            }\n            /**\n             * This function simulates a payment process by prompting the user to confirm the payment.\n             *\n             * It creates a `Receipt` and `Transaction` object and returns the `Transaction` object if the user enters \"Y\" in the prompt.\n             *\n             * @param paymentRequest - An object containing information about the payment, such as the amount and currency.\n             * @param additionalData - Additional data to be included in the receipt.\n             *\n             * @returns A promise that resolves to either an error object (if the user enters \"E\" in the prompt),\n             * a `Transaction` object (if the user confirms the payment), or `undefined` (if the user does not confirm the payment).\n             *\n             * @example\n             *\n             * const paymentRequest = {\n             *   amountMicros: 1000000,\n             *   currency: \"USD\",\n             *   items: [{ id: \"product-1\" }, { id: \"product-2\" }]\n             * };\n             * const result = await requestPayment(paymentRequest);\n             * if (result?.isError) {\n             *   console.error(`Error: ${result.message}`);\n             * } else if (result) {\n             *   console.log(`Transaction approved: ${result.transactionId}`);\n             * } else {\n             *   console.log(\"Payment cancelled by user\");\n             * }\n             */\n            requestPayment(paymentRequest, additionalData) {\n                var _a;\n                return __awaiter(this, void 0, void 0, function* () {\n                    yield CdvPurchase.Utils.asyncDelay(100); // maybe app has some UI to update... and \"prompt\" prevents that\n                    const response = prompt(`Mock payment of ${((_a = paymentRequest.amountMicros) !== null && _a !== void 0 ? _a : 0) / 1000000} ${paymentRequest.currency}. Enter \"Y\" to confirm. Enter \"E\" to trigger an error.`);\n                    if ((response === null || response === void 0 ? void 0 : response.toUpperCase()) === 'E')\n                        return testStoreError(CdvPurchase.ErrorCode.PAYMENT_NOT_ALLOWED, 'Payment not allowed', null);\n                    if ((response === null || response === void 0 ? void 0 : response.toUpperCase()) !== 'Y')\n                        return;\n                    const receipt = new CdvPurchase.Receipt(platform, this.context.apiDecorators);\n                    const transaction = new CdvPurchase.Transaction(CdvPurchase.Platform.TEST, receipt, this.context.apiDecorators);\n                    transaction.purchaseDate = new Date();\n                    transaction.products = paymentRequest.items.filter(p => p).map(product => ({ id: (product === null || product === void 0 ? void 0 : product.id) || '' })),\n                        transaction.state = CdvPurchase.TransactionState.APPROVED;\n                    transaction.transactionId = 'payment-' + new Date().getTime();\n                    transaction.amountMicros = paymentRequest.amountMicros;\n                    transaction.currency = paymentRequest.currency;\n                    receipt.transactions = [transaction];\n                    this.receipts.push(receipt);\n                    setTimeout(() => {\n                        this.context.listener.receiptsUpdated(platform, [receipt]);\n                    }, 400);\n                    return transaction;\n                });\n            }\n            manageSubscriptions() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    alert('Pseudo subscription management interface. Close it when you are done.');\n                    return;\n                });\n            }\n            manageBilling() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    alert('Pseudo billing management interface. Close it when you are done.');\n                    return;\n                });\n            }\n            reportActiveSubscription() {\n                if (this.receipts.find(r => r.transactions[0].transactionId === transactionId(1))) {\n                    // already reported\n                    return;\n                }\n                const RENEWS_EVERY_MS = 2 * 60000; // 2 minutes\n                const receipt = new CdvPurchase.Receipt(platform, this.context.apiDecorators);\n                const makeTransaction = (n) => {\n                    var _a, _b;\n                    const tr = new CdvPurchase.Transaction(platform, receipt, this.context.apiDecorators);\n                    tr.products = [{\n                            id: Test.testProducts.PAID_SUBSCRIPTION_ACTIVE.id,\n                            offerId: Test.testProducts.PAID_SUBSCRIPTION_ACTIVE.extra.offerId,\n                        }];\n                    tr.state = CdvPurchase.TransactionState.APPROVED;\n                    tr.transactionId = transactionId(n);\n                    tr.isAcknowledged = n == 1;\n                    tr.renewalIntent = CdvPurchase.RenewalIntent.RENEW;\n                    const firstPurchase = +(((_b = (_a = receipt === null || receipt === void 0 ? void 0 : receipt.transactions) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.purchaseDate) || new Date());\n                    tr.purchaseDate = new Date(firstPurchase);\n                    tr.lastRenewalDate = new Date(firstPurchase + RENEWS_EVERY_MS * (n - 1));\n                    tr.expirationDate = new Date(firstPurchase + RENEWS_EVERY_MS * n);\n                    updateVerifiedPurchases(tr);\n                    return tr;\n                };\n                receipt.transactions.push(makeTransaction(1));\n                this.receipts.push(receipt);\n                this.context.listener.receiptsUpdated(CdvPurchase.Platform.TEST, [receipt]);\n                function transactionId(n) {\n                    return 'test-active-subscription-transaction-' + n;\n                }\n                let transactionNumber = 1;\n                setInterval(() => {\n                    this.log.info('auto-renewing the mock subscription');\n                    transactionNumber += 1;\n                    receipt.transactions.push(makeTransaction(transactionNumber));\n                    this.context.listener.receiptsUpdated(CdvPurchase.Platform.TEST, [receipt]);\n                }, RENEWS_EVERY_MS);\n            }\n            static verify(receipt, callback) {\n                setTimeout(() => {\n                    var _a, _b;\n                    callback({\n                        receipt,\n                        payload: {\n                            ok: true,\n                            data: {\n                                id: (_b = (_a = receipt.transactions[0]) === null || _a === void 0 ? void 0 : _a.products[0]) === null || _b === void 0 ? void 0 : _b.id,\n                                latest_receipt: true,\n                                transaction: { type: 'test' },\n                                collection: verifiedPurchases,\n                            }\n                        }\n                    });\n                }, 500);\n            }\n            checkSupport(functionality) {\n                return true;\n            }\n            restorePurchases() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return undefined;\n                });\n            }\n        }\n        Test.Adapter = Adapter;\n        function testStoreError(code, message, productId) {\n            return CdvPurchase.storeError(code, message, CdvPurchase.Platform.TEST, productId);\n        }\n    })(Test = CdvPurchase.Test || (CdvPurchase.Test = {}));\n})(CdvPurchase || (CdvPurchase = {}));\n/// <reference path=\"../../utils/compatibility.ts\" />\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Test;\n    (function (Test) {\n        const platform = CdvPurchase.Platform.TEST;\n        /**\n         * Definition of the test products.\n         */\n        Test.testProducts = {\n            /**\n             * A valid consumable product.\n             *\n             * - id: \"test-consumable\"\n             * - type: ProductType.CONSUMABLE\n             */\n            CONSUMABLE: {\n                platform,\n                id: 'test-consumable',\n                type: CdvPurchase.ProductType.CONSUMABLE,\n            },\n            /**\n             * A consumable product for which the purchase will always fail.\n             *\n             * - id: \"test-consumable-fail\"\n             * - type: ProductType.CONSUMABLE\n             */\n            CONSUMABLE_FAILING: {\n                platform,\n                id: 'test-consumable-fail',\n                type: CdvPurchase.ProductType.CONSUMABLE,\n            },\n            /**\n             * A valid non-consumable product.\n             *\n             * - id: \"test-non-consumable\"\n             * - type: ProductType.NON_CONSUMABLE\n             */\n            NON_CONSUMABLE: {\n                platform,\n                id: 'test-non-consumable',\n                type: CdvPurchase.ProductType.NON_CONSUMABLE,\n            },\n            /**\n             * A paid-subscription that auto-renews for the duration of the session.\n             *\n             * This subscription has a free trial period, that renews every week, 3 times.\n             * It then costs $4.99 per month.\n             *\n             * - id: \"test-subscription\"\n             * - type: ProductType.PAID_SUBSCRIPTION\n             */\n            PAID_SUBSCRIPTION: {\n                platform,\n                id: 'test-subscription',\n                type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n            },\n            /**\n             * A paid-subscription that is already active when the app starts.\n             *\n             * It behaves as if the user subscribed on a different device. It will renew forever.\n             *\n             * - id: \"test-subscription-active\"\n             * - type: ProductType.PAID_SUBSCRIPTION\n             */\n            PAID_SUBSCRIPTION_ACTIVE: {\n                platform,\n                id: 'test-subscription-active',\n                type: CdvPurchase.ProductType.PAID_SUBSCRIPTION,\n                /** @internal */\n                extra: {\n                    offerId: 'test-paid-subscription-active-offer1',\n                }\n            },\n        };\n        /**\n         * List of test products definitions as an array.\n         */\n        Test.testProductsArray = CdvPurchase.Utils.objectValues(Test.testProducts);\n        /**\n         * Initialize a test product.\n         *\n         * @internal\n         */\n        function initTestProduct(productId, decorator) {\n            const key = Object.keys(Test.testProducts).find(key => Test.testProducts[key] && Test.testProducts[key].id === productId);\n            if (!key)\n                return;\n            const product = new CdvPurchase.Product(Test.testProducts[key], decorator);\n            switch (key) {\n                case 'CONSUMABLE':\n                    product.title = 'Test Consumable';\n                    product.description = 'A consumable product that you can purchase';\n                    product.addOffer(new CdvPurchase.Offer({\n                        id: 'test-consumable-offer1',\n                        pricingPhases: [{\n                                price: '$4.99',\n                                currency: 'USD',\n                                priceMicros: 4990000,\n                                paymentMode: CdvPurchase.PaymentMode.UP_FRONT,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.NON_RECURRING,\n                            }],\n                        product,\n                    }, decorator));\n                    break;\n                case 'CONSUMABLE_FAILING':\n                    product.title = 'Failing Consumable';\n                    product.description = 'A consumable product that cannot be purchased';\n                    product.addOffer(new CdvPurchase.Offer({\n                        id: 'test-consumable-fail-offer1',\n                        pricingPhases: [{\n                                price: '$1.99',\n                                currency: 'USD',\n                                priceMicros: 1990000,\n                                paymentMode: CdvPurchase.PaymentMode.UP_FRONT,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.NON_RECURRING,\n                            }],\n                        product,\n                    }, decorator));\n                    break;\n                case 'NON_CONSUMABLE':\n                    product.title = 'Non Consumable';\n                    product.description = 'A non consumable product';\n                    product.addOffer(new CdvPurchase.Offer({\n                        id: 'test-non-consumable-offer1',\n                        pricingPhases: [{\n                                price: '$9.99',\n                                currency: 'USD',\n                                priceMicros: 9990000,\n                                paymentMode: CdvPurchase.PaymentMode.UP_FRONT,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.NON_RECURRING,\n                            }],\n                        product,\n                    }, decorator));\n                    break;\n                case 'PAID_SUBSCRIPTION':\n                    product.title = 'A subscription product';\n                    product.description = 'An auto-renewing paid subscription with a trial period';\n                    product.addOffer(new CdvPurchase.Offer({\n                        id: 'test-paid-subscription-offer1',\n                        product,\n                        pricingPhases: [{\n                                price: '$0.00',\n                                currency: 'USD',\n                                priceMicros: 0,\n                                paymentMode: CdvPurchase.PaymentMode.FREE_TRIAL,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.FINITE_RECURRING,\n                                billingCycles: 3,\n                                billingPeriod: 'P1W',\n                            }, {\n                                price: '$4.99',\n                                currency: 'USD',\n                                priceMicros: 4990000,\n                                paymentMode: CdvPurchase.PaymentMode.PAY_AS_YOU_GO,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.INFINITE_RECURRING,\n                                billingPeriod: 'P1M',\n                            }],\n                    }, decorator));\n                    break;\n                case 'PAID_SUBSCRIPTION_ACTIVE':\n                    product.title = 'An owned subscription product';\n                    product.description = 'An active paid subscription';\n                    product.addOffer(new CdvPurchase.Offer({\n                        id: Test.testProducts.PAID_SUBSCRIPTION_ACTIVE.extra.offerId,\n                        product,\n                        pricingPhases: [{\n                                price: '$19.99',\n                                currency: 'USD',\n                                priceMicros: 19990000,\n                                paymentMode: CdvPurchase.PaymentMode.PAY_AS_YOU_GO,\n                                recurrenceMode: CdvPurchase.RecurrenceMode.INFINITE_RECURRING,\n                                billingPeriod: 'P1Y',\n                            }],\n                    }, decorator));\n                    break;\n                default:\n                    const unhandledSwitchCase = key;\n                    throw new Error(`Unhandled enum case: ${unhandledSwitchCase}`);\n            }\n            return product;\n        }\n        Test.initTestProduct = initTestProduct;\n    })(Test = CdvPurchase.Test || (CdvPurchase.Test = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let WindowsStore;\n    (function (WindowsStore) {\n        class Adapter {\n            constructor() {\n                this.id = CdvPurchase.Platform.WINDOWS_STORE;\n                this.name = 'WindowsStore';\n                this.ready = false;\n                this.supportsParallelLoading = false;\n                this.products = [];\n                this.receipts = [];\n            }\n            initialize() {\n                return __awaiter(this, void 0, void 0, function* () { return; });\n            }\n            get isSupported() {\n                return false;\n            }\n            loadProducts(products) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return products.map(p => windowsStoreError(CdvPurchase.ErrorCode.PRODUCT_NOT_AVAILABLE, 'TODO', p.id));\n                });\n            }\n            loadReceipts() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return [];\n                });\n            }\n            order(offer) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return windowsStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'TODO: Not implemented', offer.productId);\n                });\n            }\n            finish(transaction) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return windowsStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'TODO: Not implemented', null);\n                });\n            }\n            handleReceiptValidationResponse(receipt, response) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return;\n                });\n            }\n            receiptValidationBody(receipt) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return;\n                });\n            }\n            requestPayment(payment, additionalData) {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return windowsStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'requestPayment not supported', null);\n                });\n            }\n            manageSubscriptions() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return windowsStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'manageSubscriptions not supported', null);\n                });\n            }\n            manageBilling() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return windowsStoreError(CdvPurchase.ErrorCode.UNKNOWN, 'manageBilling not supported', null);\n                });\n            }\n            checkSupport(functionality) {\n                return false;\n            }\n            restorePurchases() {\n                return __awaiter(this, void 0, void 0, function* () {\n                    return undefined;\n                });\n            }\n        }\n        WindowsStore.Adapter = Adapter;\n        function windowsStoreError(code, message, productId) {\n            return CdvPurchase.storeError(code, message, CdvPurchase.Platform.WINDOWS_STORE, productId);\n        }\n    })(WindowsStore = CdvPurchase.WindowsStore || (CdvPurchase.WindowsStore = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        let Ajax;\n        (function (Ajax) {\n            /** HTTP status returned when a request times out */\n            Ajax.HTTP_REQUEST_TIMEOUT = 408;\n        })(Ajax = Utils.Ajax || (Utils.Ajax = {}));\n        /**\n         * Simplified version of jQuery's ajax method based on XMLHttpRequest.\n         *\n         * Uses cordova's http plugin when installed.\n         *\n         * Only supports JSON requests.\n         */\n        function ajax(log, options) {\n            if (typeof window !== 'undefined' && window.cordova && window.cordova.plugin && window.cordova.plugin.http) {\n                return ajaxWithHttpPlugin(log, options);\n            }\n            var doneCb = function () { };\n            var xhr = new XMLHttpRequest();\n            if (options.timeout) {\n                xhr.timeout = options.timeout;\n                xhr.ontimeout = function ( /*event*/) {\n                    log.warn(\"ajax -> request to \" + options.url + \" timeout\");\n                    Utils.callExternal(log, 'ajax.error', options.error, Ajax.HTTP_REQUEST_TIMEOUT, \"Timeout\");\n                };\n            }\n            xhr.open(options.method || 'POST', options.url, true);\n            xhr.onreadystatechange = function ( /*event*/) {\n                try {\n                    if (xhr.readyState === 4) {\n                        if (xhr.status === 200) {\n                            Utils.callExternal(log, 'ajax.success', options.success, JSON.parse(xhr.responseText));\n                        }\n                        else {\n                            log.warn(\"ajax -> request to \" + options.url + \" failed with status \" + xhr.status + \" (\" + xhr.statusText + \")\");\n                            Utils.callExternal(log, 'ajax.error', options.error, xhr.status, xhr.statusText);\n                        }\n                    }\n                }\n                catch (e) {\n                    log.warn(\"ajax -> request to \" + options.url + \" failed with an exception: \" + e.message);\n                    if (options.error)\n                        options.error(417, e.message, null);\n                }\n                if (xhr.readyState === 4)\n                    Utils.callExternal(log, 'ajax.done', doneCb);\n            };\n            const customHeaders = options.customHeaders;\n            if (customHeaders) {\n                Object.keys(customHeaders).forEach(function (header) {\n                    log.debug('ajax -> adding custom header: ' + header);\n                    xhr.setRequestHeader(header, customHeaders[header]);\n                });\n            }\n            xhr.setRequestHeader(\"Accept\", \"application/json\");\n            log.debug('ajax -> send request to ' + options.url);\n            if (options.data) {\n                xhr.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n                xhr.send(JSON.stringify(options.data));\n            }\n            else {\n                xhr.send();\n            }\n            return {\n                done: function (cb) { doneCb = cb; return this; }\n            };\n        }\n        Utils.ajax = ajax;\n        /**\n         * Simplified version of jQuery's ajax method based on XMLHttpRequest.\n         *\n         * Uses the http plugin.\n         */\n        function ajaxWithHttpPlugin(log, options) {\n            let doneCb = function () { };\n            const ajaxOptions = {\n                method: (options.method || 'get').toLowerCase(),\n                data: options.data,\n                serializer: 'json',\n                // responseType: 'json',\n            };\n            if (options.customHeaders) {\n                log.debug('ajax[http] -> adding custom headers: ' + JSON.stringify(options.customHeaders));\n                ajaxOptions.headers = options.customHeaders;\n            }\n            log.debug('ajax[http] -> send request to ' + options.url);\n            const ajaxDone = (response) => {\n                try {\n                    if (response.status == 200) {\n                        Utils.callExternal(log, 'ajax.success', options.success, JSON.parse(response.data));\n                    }\n                    else {\n                        log.warn(\"ajax[http] -> request to \" + options.url + \" failed with status \" + response.status + \" (\" + response.error + \")\");\n                        Utils.callExternal(log, 'ajax.error', options.error, response.status, response.error);\n                    }\n                }\n                catch (e) {\n                    log.warn(\"ajax[http] -> request to \" + options.url + \" failed with an exception: \" + e.message);\n                    if (options.error)\n                        Utils.callExternal(log, 'ajax.error', options.error, 417, e.message);\n                }\n                Utils.callExternal(log, 'ajax.done', doneCb);\n            };\n            window.cordova.plugin.http.sendRequest(options.url, ajaxOptions, ajaxDone, ajaxDone);\n            return {\n                done: function (cb) { doneCb = cb; return this; }\n            };\n        }\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /**\n         * Calls an user-registered callback.\n         *\n         * Won't throw exceptions, only logs errors.\n         *\n         * @param name a short string describing the callback\n         * @param callback the callback to call (won't fail if undefined)\n         *\n         * @example\n         * ```js\n         * Utils.callExternal(store.log, \"ajax.error\", options.error, 404, \"Not found\");\n         * ```\n         *\n         * @internal\n         */\n        function callExternal(log, name, callback, ...args) {\n            try {\n                const args = Array.prototype.slice.call(arguments, 3);\n                // store.log.debug(\"calling \" + name + \"(\" + JSON.stringify(args2) + \")\");\n                if (callback)\n                    callback.apply(CdvPurchase.store, args);\n            }\n            catch (e) {\n                log.logCallbackException(name, e);\n            }\n        }\n        Utils.callExternal = callExternal;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /** @internal */\n        function delay(fn, milliseconds) {\n            return setTimeout(fn, milliseconds);\n        }\n        Utils.delay = delay;\n        /** @internal */\n        function debounce(fn, milliseconds) {\n            return createDebouncer(fn, milliseconds).call;\n        }\n        Utils.debounce = debounce;\n        /** @internal */\n        function createDebouncer(fn, milliseconds) {\n            let timeout = null;\n            let waiting = [];\n            const later = function (context, args) {\n                const toCall = waiting;\n                waiting = [];\n                timeout = null;\n                fn();\n                toCall.forEach(fn => fn());\n            };\n            const debounced = function () {\n                if (timeout)\n                    window.clearTimeout(timeout);\n                timeout = setTimeout(later, milliseconds);\n            };\n            return {\n                call: debounced,\n                wait: () => new Promise(resolve => {\n                    if (timeout)\n                        waiting.push(resolve);\n                    else\n                        resolve();\n                })\n            };\n        }\n        Utils.createDebouncer = createDebouncer;\n        /** @internal */\n        function asyncDelay(milliseconds) {\n            return new Promise(resolve => setTimeout(resolve, milliseconds));\n        }\n        Utils.asyncDelay = asyncDelay;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /**\n         * Generate a plain english version of the billing cycle in a pricing phase.\n         *\n         * Example outputs:\n         *\n         * - \"3x 1 month\": for `FINITE_RECURRING`, 3 cycles, period \"P1M\"\n         * - \"for 1 year\": for `NON_RECURRING`, period \"P1Y\"\n         * - \"every week\": for `INFINITE_RECURRING, period \"P1W\"\n         *\n         * @example\n         * Utils.formatBillingCycleEN(offer.pricingPhases[0])\n         */\n        function formatBillingCycleEN(pricingPhase) {\n            switch (fixedRecurrenceMode(pricingPhase)) {\n                case CdvPurchase.RecurrenceMode.FINITE_RECURRING:\n                    return `${pricingPhase.billingCycles}x ${Utils.formatDurationEN(pricingPhase.billingPeriod)}`;\n                case CdvPurchase.RecurrenceMode.NON_RECURRING:\n                    return 'for ' + Utils.formatDurationEN(pricingPhase.billingPeriod);\n                default: // INFINITE_RECURRING\n                    return 'every ' + Utils.formatDurationEN(pricingPhase.billingPeriod, { omitOne: true });\n            }\n        }\n        Utils.formatBillingCycleEN = formatBillingCycleEN;\n        /**\n         * FINITE_RECURRING with billingCycles=1 is like NON_RECURRING\n         * FINITE_RECURRING with billingCycles=0 is like INFINITE_RECURRING\n         */\n        function fixedRecurrenceMode(pricingPhase) {\n            var _a;\n            const cycles = (_a = pricingPhase.billingCycles) !== null && _a !== void 0 ? _a : 0;\n            if (pricingPhase.recurrenceMode === CdvPurchase.RecurrenceMode.FINITE_RECURRING) {\n                if (cycles == 1)\n                    return CdvPurchase.RecurrenceMode.NON_RECURRING;\n                if (cycles <= 0)\n                    return CdvPurchase.RecurrenceMode.INFINITE_RECURRING;\n            }\n            return pricingPhase.recurrenceMode;\n        }\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /**\n         * Format a simple ISO 8601 duration to plain English.\n         *\n         * This works for non-composite durations, i.e. that have a single unit with associated amount. For example: \"P1Y\" or \"P3W\".\n         *\n         * See https://en.wikipedia.org/wiki/ISO_8601#Durations\n         *\n         * This method is provided as a utility for getting simple things done quickly. In your application, you'll probably\n         * need some other method that supports multiple locales.\n         *\n         * @param iso - Duration formatted in IS0 8601\n         * @return The duration in plain english. Example: \"1 year\" or \"3 weeks\".\n         */\n        function formatDurationEN(iso, options) {\n            if (!iso)\n                return '';\n            const l = iso.length;\n            const n = iso.slice(1, l - 1);\n            if (n === '1') {\n                if (options === null || options === void 0 ? void 0 : options.omitOne) {\n                    return ({ 'D': 'day', 'W': 'week', 'M': 'month', 'Y': 'year', }[iso[l - 1]]) || iso[l - 1];\n                }\n                else {\n                    return ({ 'D': '1 day', 'W': '1 week', 'M': '1 month', 'Y': '1 year', }[iso[l - 1]]) || iso[l - 1];\n                }\n            }\n            else {\n                const u = ({ 'D': 'days', 'W': 'weeks', 'M': 'months', 'Y': 'years', }[iso[l - 1]]) || iso[l - 1];\n                return `${n} ${u}`;\n            }\n        }\n        Utils.formatDurationEN = formatDurationEN;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        const HEX2STR = \"0123456789abcdef\".split(\"\");\n        function toHexString(r) {\n            for (var n = \"\", e = 0; e < 4; e++)\n                n += HEX2STR[r >> 8 * e + 4 & 15] + HEX2STR[r >> 8 * e & 15];\n            return n;\n        }\n        function hexStringFromArray(array) {\n            const out = [];\n            for (var arrayLength = array.length, i = 0; i < arrayLength; i++)\n                out.push(toHexString(array[i]));\n            return out.join(\"\");\n        }\n        function add32(r, n) {\n            return r + n & 4294967295;\n        }\n        function complexShift(r, n, e, t, o, u, shiftFunction) {\n            function shiftAdd32(op0, op1, v1) {\n                return add32(op0 << op1 | op0 >>> 32 - op1, v1);\n            }\n            function add32x4(i0, i1, j0, j1) {\n                return add32(add32(i1, i0), add32(j0, j1));\n            }\n            return shiftAdd32(add32x4(r, n, t, u), o, e);\n        }\n        var step1Function = function (shiftFunction, n, e, t, o, u, f, a) { return complexShift(e & t | ~e & o, n, e, u, f, a, shiftFunction); };\n        var step2Function = function (shiftFunction, n, e, t, o, u, f, a) { return complexShift(e & o | t & ~o, n, e, u, f, a, shiftFunction); };\n        var step3Function = function (shiftFunction, n, e, t, o, u, f, a) { return complexShift(e ^ t ^ o, n, e, u, f, a, shiftFunction); };\n        var step4Function = function (shiftFunction, n, e, t, o, u, f, a) { return complexShift(t ^ (e | ~o), n, e, u, f, a, shiftFunction); };\n        function hashStep(inOutVec4, strAsInts, shiftFunction) {\n            if (!shiftFunction)\n                shiftFunction = add32;\n            let v0 = inOutVec4[0];\n            let v1 = inOutVec4[1];\n            let v2 = inOutVec4[2];\n            let v3 = inOutVec4[3];\n            var step1 = step1Function.bind(null, shiftFunction);\n            v0 = step1(v0, v1, v2, v3, strAsInts[0], 7, -680876936);\n            v3 = step1(v3, v0, v1, v2, strAsInts[1], 12, -389564586);\n            v2 = step1(v2, v3, v0, v1, strAsInts[2], 17, 606105819);\n            v1 = step1(v1, v2, v3, v0, strAsInts[3], 22, -1044525330);\n            v0 = step1(v0, v1, v2, v3, strAsInts[4], 7, -176418897);\n            v3 = step1(v3, v0, v1, v2, strAsInts[5], 12, 1200080426);\n            v2 = step1(v2, v3, v0, v1, strAsInts[6], 17, -1473231341);\n            v1 = step1(v1, v2, v3, v0, strAsInts[7], 22, -45705983);\n            v0 = step1(v0, v1, v2, v3, strAsInts[8], 7, 1770035416);\n            v3 = step1(v3, v0, v1, v2, strAsInts[9], 12, -1958414417);\n            v2 = step1(v2, v3, v0, v1, strAsInts[10], 17, -42063);\n            v1 = step1(v1, v2, v3, v0, strAsInts[11], 22, -1990404162);\n            v0 = step1(v0, v1, v2, v3, strAsInts[12], 7, 1804603682);\n            v3 = step1(v3, v0, v1, v2, strAsInts[13], 12, -40341101);\n            v2 = step1(v2, v3, v0, v1, strAsInts[14], 17, -1502002290);\n            v1 = step1(v1, v2, v3, v0, strAsInts[15], 22, 1236535329);\n            var step2 = step2Function.bind(null, shiftFunction);\n            v0 = step2(v0, v1, v2, v3, strAsInts[1], 5, -165796510);\n            v3 = step2(v3, v0, v1, v2, strAsInts[6], 9, -1069501632);\n            v2 = step2(v2, v3, v0, v1, strAsInts[11], 14, 643717713);\n            v1 = step2(v1, v2, v3, v0, strAsInts[0], 20, -373897302);\n            v0 = step2(v0, v1, v2, v3, strAsInts[5], 5, -701558691);\n            v3 = step2(v3, v0, v1, v2, strAsInts[10], 9, 38016083);\n            v2 = step2(v2, v3, v0, v1, strAsInts[15], 14, -660478335);\n            v1 = step2(v1, v2, v3, v0, strAsInts[4], 20, -405537848);\n            v0 = step2(v0, v1, v2, v3, strAsInts[9], 5, 568446438);\n            v3 = step2(v3, v0, v1, v2, strAsInts[14], 9, -1019803690);\n            v2 = step2(v2, v3, v0, v1, strAsInts[3], 14, -187363961);\n            v1 = step2(v1, v2, v3, v0, strAsInts[8], 20, 1163531501);\n            v0 = step2(v0, v1, v2, v3, strAsInts[13], 5, -1444681467);\n            v3 = step2(v3, v0, v1, v2, strAsInts[2], 9, -51403784);\n            v2 = step2(v2, v3, v0, v1, strAsInts[7], 14, 1735328473);\n            v1 = step2(v1, v2, v3, v0, strAsInts[12], 20, -1926607734);\n            var step3 = step3Function.bind(null, shiftFunction);\n            v0 = step3(v0, v1, v2, v3, strAsInts[5], 4, -378558);\n            v3 = step3(v3, v0, v1, v2, strAsInts[8], 11, -2022574463);\n            v2 = step3(v2, v3, v0, v1, strAsInts[11], 16, 1839030562);\n            v1 = step3(v1, v2, v3, v0, strAsInts[14], 23, -35309556);\n            v0 = step3(v0, v1, v2, v3, strAsInts[1], 4, -1530992060);\n            v3 = step3(v3, v0, v1, v2, strAsInts[4], 11, 1272893353);\n            v2 = step3(v2, v3, v0, v1, strAsInts[7], 16, -155497632);\n            v1 = step3(v1, v2, v3, v0, strAsInts[10], 23, -1094730640);\n            v0 = step3(v0, v1, v2, v3, strAsInts[13], 4, 681279174);\n            v3 = step3(v3, v0, v1, v2, strAsInts[0], 11, -358537222);\n            v2 = step3(v2, v3, v0, v1, strAsInts[3], 16, -722521979);\n            v1 = step3(v1, v2, v3, v0, strAsInts[6], 23, 76029189);\n            v0 = step3(v0, v1, v2, v3, strAsInts[9], 4, -640364487);\n            v3 = step3(v3, v0, v1, v2, strAsInts[12], 11, -421815835);\n            v2 = step3(v2, v3, v0, v1, strAsInts[15], 16, 530742520);\n            v1 = step3(v1, v2, v3, v0, strAsInts[2], 23, -995338651);\n            var step4 = step4Function.bind(null, shiftFunction);\n            v0 = step4(v0, v1, v2, v3, strAsInts[0], 6, -198630844);\n            v3 = step4(v3, v0, v1, v2, strAsInts[7], 10, 1126891415);\n            v2 = step4(v2, v3, v0, v1, strAsInts[14], 15, -1416354905);\n            v1 = step4(v1, v2, v3, v0, strAsInts[5], 21, -57434055);\n            v0 = step4(v0, v1, v2, v3, strAsInts[12], 6, 1700485571);\n            v3 = step4(v3, v0, v1, v2, strAsInts[3], 10, -1894986606);\n            v2 = step4(v2, v3, v0, v1, strAsInts[10], 15, -1051523);\n            v1 = step4(v1, v2, v3, v0, strAsInts[1], 21, -2054922799);\n            v0 = step4(v0, v1, v2, v3, strAsInts[8], 6, 1873313359);\n            v3 = step4(v3, v0, v1, v2, strAsInts[15], 10, -30611744);\n            v2 = step4(v2, v3, v0, v1, strAsInts[6], 15, -1560198380);\n            v1 = step4(v1, v2, v3, v0, strAsInts[13], 21, 1309151649);\n            v0 = step4(v0, v1, v2, v3, strAsInts[4], 6, -145523070);\n            v3 = step4(v3, v0, v1, v2, strAsInts[11], 10, -1120210379);\n            v2 = step4(v2, v3, v0, v1, strAsInts[2], 15, 718787259);\n            v1 = step4(v1, v2, v3, v0, strAsInts[9], 21, -343485551);\n            inOutVec4[0] = shiftFunction(v0, inOutVec4[0]);\n            inOutVec4[1] = shiftFunction(v1, inOutVec4[1]);\n            inOutVec4[2] = shiftFunction(v2, inOutVec4[2]);\n            inOutVec4[3] = shiftFunction(v3, inOutVec4[3]);\n        }\n        ;\n        function stringToIntArray(r) {\n            for (var ret = [], e = 0; e < 64; e += 4)\n                ret[e >> 2] = r.charCodeAt(e) + (r.charCodeAt(e + 1) << 8) + (r.charCodeAt(e + 2) << 16) + (r.charCodeAt(e + 3) << 24);\n            return ret;\n        }\n        function computeMD5(str, shiftFunction) {\n            let lastCharIndex;\n            const strLength = str.length;\n            const vec4 = [1732584193, -271733879, -1732584194, 271733878];\n            for (lastCharIndex = 64; lastCharIndex <= strLength; lastCharIndex += 64)\n                hashStep(vec4, stringToIntArray(str.substring(lastCharIndex - 64, lastCharIndex)), shiftFunction);\n            const vec16 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n            const reminderLength = (str = str.substring(lastCharIndex - 64)).length;\n            // process by batch of 64\n            let vec16Index;\n            for (vec16Index = 0; vec16Index < reminderLength; vec16Index++)\n                vec16[vec16Index >> 2] |= str.charCodeAt(vec16Index) << (vec16Index % 4 << 3);\n            vec16[vec16Index >> 2] |= 128 << (vec16Index % 4 << 3);\n            if (vec16Index > 55) {\n                hashStep(vec4, vec16, shiftFunction);\n                for (vec16Index = 16; vec16Index--;)\n                    vec16[vec16Index] = 0;\n            }\n            vec16[14] = 8 * strLength;\n            hashStep(vec4, vec16, shiftFunction);\n            return vec4;\n        }\n        ;\n        /**\n         * Returns the MD5 hash-value of the passed string.\n         *\n         * Based on the work of Jeff Mott, who did a pure JS implementation of the MD5 algorithm that was published by Ronald L. Rivest in 1991.\n         * Code was imported from https://github.com/pvorb/node-md5\n         *\n         * I cleaned up the all-including minified version of it.\n         */\n        function md5(str) {\n            if (!str)\n                return '';\n            let shiftFunction;\n            if (\"5d41402abc4b2a76b9719d911017c592\" !== hexStringFromArray(computeMD5(\"hello\")))\n                shiftFunction = function (r, n) {\n                    const e = (65535 & r) + (65535 & n);\n                    return (r >> 16) + (n >> 16) + (e >> 16) << 16 | 65535 & e;\n                };\n            return hexStringFromArray(computeMD5(str, shiftFunction));\n        }\n        Utils.md5 = md5;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /** Returns an UUID v4. Uses `window.crypto` internally to generate random values. */\n        function platformId() {\n            var _a, _b, _c;\n            if ((_a = window.cordova) === null || _a === void 0 ? void 0 : _a.platformId)\n                return (_b = window.cordova) === null || _b === void 0 ? void 0 : _b.platformId;\n            if ((_c = window.Capacitor) === null || _c === void 0 ? void 0 : _c.getPlatform)\n                return window.Capacitor.getPlatform();\n            return 'web';\n        }\n        Utils.platformId = platformId;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        /**\n         * Return a safer version of a callback that runs inside a try/catch block.\n         *\n         * @param logger - Used to log errors.\n         * @param className - Type of callback, helps debugging when a function failed.\n         * @param callback - The callback function is turn into a safer version.\n         */\n        function safeCallback(logger, className, callback, callbackName, reason) {\n            return function (value) {\n                safeCall(logger, className, callback, value, callbackName, reason);\n            };\n        }\n        Utils.safeCallback = safeCallback;\n        /**\n         * Run a callback inside a try/catch block.\n         *\n         * @param logger - Used to log errors.\n         * @param className - Type of callback, helps debugging when a function failed.\n         * @param callback - The callback function is turn into a safer version.\n         * @param value - Value passed to the callback.\n         */\n        function safeCall(logger, className, callback, value, callbackName, reason) {\n            if (!callback) {\n                return; // cannot call an undefined callback.\n            }\n            if (!callbackName) {\n                callbackName = callback.name || ('#' + Utils.md5(callback.toString()));\n            }\n            setTimeout(() => {\n                try {\n                    logger.debug(`Calling callback: type=${className} name=${callbackName} reason=${reason}`);\n                    callback(value);\n                }\n                catch (error) {\n                    logger.error(`Error in callback: type=${className} name=${callbackName} reason=${reason}`);\n                    logger.debug(callback.toString());\n                    const errorAsError = error;\n                    if ('message' in errorAsError)\n                        logger.error(errorAsError.message);\n                    if ('fileName' in error)\n                        logger.error('in ' + error.fileName + ':' + error.lineNumber);\n                    if ('stack' in errorAsError)\n                        logger.error(errorAsError.stack);\n                }\n            }, 0);\n        }\n        Utils.safeCall = safeCall;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Utils;\n    (function (Utils) {\n        function getCryptoExtension() {\n            return (window.crypto || window.msCrypto);\n        }\n        /** Returns an UUID v4. Uses `window.crypto` internally to generate random values. */\n        function uuidv4() {\n            // @ts-ignore\n            return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) {\n                return (c ^ getCryptoExtension().getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);\n            });\n        }\n        Utils.uuidv4 = uuidv4;\n    })(Utils = CdvPurchase.Utils || (CdvPurchase.Utils = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Validator;\n    (function (Validator) {\n        /**\n         * @internal\n         */\n        let Internal;\n        (function (Internal) {\n            function isArray(arg) {\n                return Object.prototype.toString.call(arg) === '[object Array]';\n            }\n            function isObject(arg) {\n                return Object.prototype.toString.call(arg) === '[object Object]';\n            }\n            // List of functions allowed by store.validator_privacy_policy\n            function getPrivacyPolicy(store) {\n                if (typeof store.validator_privacy_policy === 'string')\n                    return store.validator_privacy_policy.split(',');\n                else if (isArray(store.validator_privacy_policy))\n                    return store.validator_privacy_policy;\n                else // default: no tracking\n                    return ['analytics', 'support', 'fraud'];\n            }\n            function getDeviceInfo(store) {\n                const privacyPolicy = getPrivacyPolicy(store); // string[]\n                function allowed(policy) {\n                    return privacyPolicy.indexOf(policy) >= 0;\n                }\n                // Different versions of the plugin use different response fields.\n                // Sending this information allows the validator to reply with only expected information.\n                const ret = {\n                    plugin: 'cordova-plugin-purchase/' + CdvPurchase.PLUGIN_VERSION,\n                };\n                const wdw = window;\n                // the cordova-plugin-device global object\n                const device = isObject(wdw.device) ? wdw.device : {};\n                // Send the receipt validator information about the device.\n                // This will allow to make vendor or device specific fixes and detect class\n                // of devices with issues.\n                // Knowing running version of OS and libraries also required for handling\n                // support requests.\n                if (allowed('analytics') || allowed('support')) {\n                    // Version of ionic (if applicable)\n                    const ionic = wdw.Ionic || wdw.ionic;\n                    if (ionic && ionic.version)\n                        ret.ionic = ionic.version;\n                    // Information from the cordova-plugin-device (if installed)\n                    if (device.cordova)\n                        ret.cordova = device.cordova; // Version of cordova\n                    if (device.model)\n                        ret.model = device.model; // Device model\n                    if (device.platform)\n                        ret.platform = device.platform; // OS\n                    if (device.version)\n                        ret.version = device.version; // OS version\n                    if (device.manufacturer)\n                        ret.manufacturer = device.manufacturer; // Device manufacturer\n                }\n                // Device identifiers are used for tracking users across services\n                // It is sometimes required for support requests too, but I choose to\n                // keep this out.\n                if (allowed('tracking')) {\n                    if (device.serial)\n                        ret.serial = device.serial; // Hardware serial number\n                    if (device.uuid)\n                        ret.uuid = device.uuid; // Device UUID\n                }\n                // Running from a simulator is an error condition for in-app purchases.\n                // Since only developers run in a simulator, let's always report that.\n                if (device.isVirtual)\n                    ret.isVirtual = device.isVirtual; // Simulator\n                // Probably nobody wants to disable fraud discovery.\n                // A fingerprint of the device identifiers is used for fraud discovery.\n                // An alert should be triggered by the validator when a lot of devices\n                // share a single receipt.\n                if (allowed('fraud')) {\n                    // For fraud discovery, we only need a fingerprint of the device.\n                    var fingerprint = '';\n                    if (device.serial)\n                        fingerprint = 'serial:' + device.serial; // Hardware serial number\n                    else if (device.uuid)\n                        fingerprint = 'uuid:' + device.uuid; // Device UUID\n                    else {\n                        // Using only model and manufacturer, we might end-up with many\n                        // users sharing the same fingerprint, which is fine for fraud discovery.\n                        if (device.model)\n                            fingerprint += '/' + device.model;\n                        if (device.manufacturer)\n                            fingerprint = '/' + device.manufacturer;\n                    }\n                    // Fingerprint is hashed to keep required level of privacy.\n                    if (fingerprint)\n                        ret.fingerprint = CdvPurchase.Utils.md5(fingerprint);\n                }\n                return ret;\n            }\n            Internal.getDeviceInfo = getDeviceInfo;\n        })(Internal = Validator.Internal || (Validator.Internal = {}));\n    })(Validator = CdvPurchase.Validator || (CdvPurchase.Validator = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    let Validator;\n    (function (Validator) {\n        let Request;\n        (function (Request) {\n            ;\n        })(Request = Validator.Request || (Validator.Request = {}));\n    })(Validator = CdvPurchase.Validator || (CdvPurchase.Validator = {}));\n})(CdvPurchase || (CdvPurchase = {}));\nvar CdvPurchase;\n(function (CdvPurchase) {\n    /** Receipt data as validated by the receipt validation server */\n    class VerifiedReceipt {\n        /**\n         * @internal\n         */\n        constructor(receipt, response, decorator) {\n            var _a;\n            /** @internal */\n            this.className = 'VerifiedReceipt';\n            this.id = response.id;\n            this.sourceReceipt = receipt;\n            this.collection = (_a = response.collection) !== null && _a !== void 0 ? _a : [];\n            this.latestReceipt = response.latest_receipt;\n            this.nativeTransactions = [response.transaction];\n            this.warning = response.warning;\n            this.validationDate = response.date ? new Date(response.date) : new Date();\n            Object.defineProperty(this, 'raw', { 'enumerable': false, get() { return response; } });\n            Object.defineProperty(this, 'finish', { 'enumerable': false, get() { return () => decorator.finish(this); } });\n        }\n        /** Platform this receipt originated from */\n        get platform() { return this.sourceReceipt.platform; }\n        /** Get raw response data from the receipt validation request */\n        get raw() { return {}; } // actual implementation as \"defineProperty\" in constructor.\n        /**\n         * Update the receipt content\n         *\n         * @internal\n         */\n        set(receipt, response) {\n            var _a;\n            this.id = response.id;\n            this.sourceReceipt = receipt;\n            this.collection = (_a = response.collection) !== null && _a !== void 0 ? _a : [];\n            this.latestReceipt = response.latest_receipt;\n            this.nativeTransactions = [response.transaction];\n            this.warning = response.warning;\n        }\n        /** Finish all transactions in the receipt */\n        finish() {\n            return __awaiter(this, void 0, void 0, function* () { });\n        }\n    }\n    CdvPurchase.VerifiedReceipt = VerifiedReceipt;\n})(CdvPurchase || (CdvPurchase = {}));\n"],"x_google_ignoreList":[12]}